Download as:
Rating : ⭐⭐⭐⭐⭐
Price: $10.99
Language:EN
Pages: 4

Defined inside the service schema directly

If there are any problem, it can throw an Error. Please note, you can’t break/skip the further executions of hooks or action handler.

Main usages:




property populating
remove sensitive data.

"*": "resolveLoggedUser",
// Define multiple hooks for action `remove`
remove: [
function isAuthenticated(ctx) {
if (!ctx.user)
throw new Error("Forbidden");
},
function isOwner(ctx) {
if (!this.checkOwner(ctx.params.id, ctx.user.id))
throw new Error("Only owner can remove it.");
}
],
// Applies to all actions that start with "create-"
"create-*": [
async function (ctx){}
],
// Applies to all actions that end with "-user"
"*-user": [
async function (ctx){}
],}},
methods: {
async resolveLoggedUser(ctx) {
if (ctx.meta.user)
ctx.user = await ctx.call("users.get", { id: ctx.meta.user.id }); }}}

After & Error hooks

Execution order

It is important to keep in mind that hooks have a specific execution order. This is especially important to remember when multiple hooks are registered at different (service and/or action) levels. Overall, the hooks have the following execution logic:

broker.createService({
name:"greeter",
hooks:{
before:{
"*"(ctx){
broker.logger.info(chalk.cyan("Before all hook")); },
hello(ctx){
broker.logger.info(chalk.magenta(" Before hook")); }
},
after:{
"*"(ctx, res){
broker.logger.info(chalk.cyan("After all hook")); return res;
},
hello(ctx, res){
broker.logger.info(chalk.magenta(" After hook")); return res;
}}},

actions:{
hello:{
hooks:{
before(ctx){

},

Output produced by global, service & action level hooks

Reusability

The most efficient way of reusing hooks is by declaring them as service methods in a separate file and import them with the mixin mechanism. This way a single hook can be easily shared across multiple actions.

}}};

Local Storage

The locals property of Context object is a simple storage that can be used to store some additional data and pass it to the action handler. locals property and hooks are a powerful combo:

Copyright © 2009-2023 UrgentHomework.com, All right reserved.