"Post" middelwares are defined the same way as "pre" middlewares. The main difference is that if you reject the Promise of your middleware because an error occured, the original method still resolves and a Symbol is added to the response containing the post hooks error(s).
// user.model.jsconstschema=newSchema({ username: { ... },... });// add "post" save middlewareschema.post('save',functionpostSave(){returnnewPromise((resolve, reject) => {constemail=this.email;// ... do anything needed, maybe send an email?if (someError) {// If there is any error reject the Promisereturnreject({ code:500, message:'Houston something went wrong.' }); } });});// ....// user.controller.jsconstgstore=require('gstore-node')();constUser=require('./user.model');constuser=newUser({ name:'John', email:'john@snow.com' });user.save().then((entity) => {// You should do this check if you have post hooks that can failif (entity[gstore.ERR_HOOKS]) {console.log(entity[gstore.ERR_HOOKS][0].message); // 'Houston something went wrong.' }...});
Note The response from a "post" hook on delete() contains the key(s) of the entitie(s) deleted.
// key can be one Key or an Array of Keys deleteduserSchema.post('delete',functionpostDelete({ key }){...returnPromise.resolve();});
You can also pass an Array of middleware to execute
When you save or delete an entity from inside a transaction, gstore adds an execPostHooks() method to the transaction instance.
If the transaction succeeds and you have any post('save') or post('delete') hooks on any of the entities modified during the transaction you need to call this method to execute them.