Search.../

beforeInsert( )

A hook that is triggered before an insert() operation.

Description

The beforeInsert() hook runs when:

  • The insert() function is called.
  • An action is performed on a dataset that inserts a new item into the collection.
  • An item is inserted using the Content Manager.
  • An item is imported into the Sandbox or Live collection.

The hook also runs when an action is performed on a dataset that inserts a new item into the collection that the dataset is connected to.

Return an object or a Promise that resolves to an object from the beforeInsert() function. The returned object will be inserted into the collection instead of the original item passed to the insert() function.

If the returned value is of the wrong type, the value is ignored.

A rejected Promise blocks the call to insert() and also calls the onFailure() hook if it has been registered.

Because the beforeInsert() hook is called before insert() is executed, it can affect the item that is inserted into the collection or block the insert().

Syntax

function beforeInsert(item: Object, context: HookContext): Promise<Object> | Object

beforeInsert Parameters

NAME
TYPE
DESCRIPTION
item

Object

The original item to be inserted.

context

HookContext

Contextual information about the hook.

Returns

The item to be inserted instead of the original item specified by the caller. Returning a rejected promise will block the operation and will return a rejected promise to the caller as well as trigger the onFailure() hook.

Return Type:

Promise<Object>

 | 

Object

Was this helpful?

A beforeInsert hook

Code Example

Copy Code
1// In data.js
2
3export function myCollection_beforeInsert(item, context) {
4 let hookContext = context; // see below
5
6 // some change to the received item
7
8 return item;
9}
10
11/*
12 * hookContext:
13 *
14 * {
15 * "collectionName": "myCollection",
16 * "userId": "f45jf8d2-grkj-2opd-4ovk-9rfj4wo5tvj3",
17 * "userRole": "siteOwner"
18 * }
19 */
Change the item to insert using a beforeInsert hook

Code Example

Copy Code
1// In data.js
2
3export function myCollection_beforeInsert(item, context) {
4 let hookContext = context; // see below
5
6 // some change to the received item
7 item.title = toUpperFirst(item.title);
8 item.first_name = toUpperFirst(item.first_name);
9 item.last_name = toUpperFirst(item.last_name);
10
11 return item;
12}
13
14function toUpperFirst(s) {
15 return s.charAt(0).toUpperCase() + s.slice(1);
16}
17
18/*
19 * hookContext:
20 *
21 * {
22 * "collectionName": "myCollection",
23 * "userId": "f45jf8d2-grkj-2opd-4ovk-9rfj4wo5tvj3",
24 * "userRole": "siteOwner"
25 * }
26 */