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
The original item to be inserted.
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:
|
ObjectWas this helpful?
1// In data.js23export function myCollection_beforeInsert(item, context) {4 let hookContext = context; // see below56 // some change to the received item78 return item;9}1011/*12 * hookContext:13 *14 * {15 * "collectionName": "myCollection",16 * "userId": "f45jf8d2-grkj-2opd-4ovk-9rfj4wo5tvj3",17 * "userRole": "siteOwner"18 * }19 */
1// In data.js23export function myCollection_beforeInsert(item, context) {4 let hookContext = context; // see below56 // some change to the received item7 item.title = toUpperFirst(item.title);8 item.first_name = toUpperFirst(item.first_name);9 item.last_name = toUpperFirst(item.last_name);1011 return item;12}1314function toUpperFirst(s) {15 return s.charAt(0).toUpperCase() + s.slice(1);16}1718/*19 * hookContext:20 *21 * {22 * "collectionName": "myCollection",23 * "userId": "f45jf8d2-grkj-2opd-4ovk-9rfj4wo5tvj3",24 * "userRole": "siteOwner"25 * }26 */
1// In data.js23export function myCollection_beforeInsert(item, context) {4 let hookContext = context; // see below56 //validate the email field and reject in case of failure7 const emailRegex = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;89 if (emailRegex.test(item.email)) {10 return item;11 } else {12 return Promise.reject('Invalid email address.');13 }14}1516/*17 * hookContext:18 *19 * {20 * "collectionName": "myCollection",21 * "userId": "f45jf8d2-grkj-2opd-4ovk-9rfj4wo5tvj3",22 * "userRole": "siteOwner"23 * }24 */