Luis Guzmán
Luis Guzmán

Reputation: 1

Why Hook is called in all update services methods

I'm create a hook file with the following information, which is Hooks.js Hooks.js is working to authenticate an actions with JWT when need it, I dont need it in all servies calls.

As my understanding the syntax to call a hook was app/use route/hooks and those hooks were only applied to and specific route and not globally.

module.exports = {
  errorHandler: (context) => {
    if (context.error) {
      context.error.stack = null;
      return context;
    }
  },
  isValidToken: (context) => {
    const token = context.params.headers.authorization;  
    const payload = Auth.validateToken(token);
    console.log(payload);
    if(payload !== "Invalid" && payload !== "No Token Provided"){
        context.data = payload._id;
    }
    else {
        throw new errors.NotAuthenticated('Authentication Error Token');
    }
  },
  isValidDomain: (context) => {
    if (
      config.DOMAINS_WHITE_LIST.includes(
        context.params.headers.origin || context.params.headers.host
      )
    ) {
      return context;
    }
    throw new errors.NotAuthenticated("Not Authenticated Domain");
  },
  normalizedId: (context) => {
    context.id = context.id || context.params.route.id;
  },
  normalizedCode: (context) => {
    context.id = context.params.route.code;
  },
};

Then I create a file for services and routes, like the following:

const Hooks = require("../../Hooks/Hooks");
const userServices = require("./user.services");

module.exports = (app) => {
  app
    .use("/users", {
      find: userServices.find,
      create: userServices.createUser,
    })
    .hooks({
      before: {
        find: [Hooks.isValidDomain],
        create: [Hooks.isValidDomain],
      },
    });

  app
    .use("/users/:code/validate", {
      update: userServices.validateCode,
    })
    .hooks({
      before: {
        update: [Hooks.isValidDomain, Hooks.normalizedCode],
      },
    });

  app
    .use("/users/personal", {
      update: userServices.personalInfo,
    })
    .hooks({
      before: {
        update: [Hooks.isValidDomain, Hooks.isValidToken],
      },
    });
};

Why Hooks.isValidToken applies to all my update methods? Even if I'm not calling it?

Please help.

Upvotes: 0

Views: 37

Answers (1)

Daff
Daff

Reputation: 44215

app.hooks registers an application level hook which runs for all services. If you only want it for a specific service and method it needs to be app.service('users').hooks().

Upvotes: 1

Related Questions