How to access post parameters from bodyParser using moleculer.js

1.2k Views Asked by At

I am digging into moleculer.js the only thing i am finding difficult to understand;how to get parameters inside actions of a service below given is my code

const ApiGateway = require("moleculer-web");
module.exports = {
name: "api",
mixins: [ApiGateway],
settings: {
    port: process.env.PORT || 3000,
    bodyParsers: {
        json: true,
        urlencoded: { extended: true }
    },
    routes: [{
        path: "/api",
        whitelist: [

            "**"
        ]
    }],

    assets: {
        folder: "public"
    }
},
};

Below is my user service where i want to get post parameters

module.exports = {
name: "users",
dependencies: ["guard"],

actions: {
    create: {
        restricted: [
            "api"
        ],

        async handler(ctx,route, req, res) {
            this.logger.info(req);
            this.logger.info("'users.create' has been called.");
            const token=await ctx.call("guard.generate",{service:"abc"});

what i want is

            const token=await ctx.call("guard.generate",{service:req.body.name});

instead of

            const token=await ctx.call("guard.generate",{service:"abc"});
            const verify=await ctx.call("guard.check",{token:token});
            return [token,verify,req];
        }
    },
   }
1

There are 1 best solutions below

0
On BEST ANSWER

Moleculer´s Actions has the following signature: <actionName> (ctx) {// logic} or <actionName>: { handler (ctx) { // logic}}. So what you have to do is this:

module.exports = {
  name: "users",

  actions: {
    welcome: {
      handler(ctx) {
        console.log(ctx.params) // Print the request params
        // Call other actions ctx.call('serviceName.actionName`, ...data...)
        return ctx.params
      }
    }
  }
}

More info about Actions: https://moleculer.services/docs/0.13/actions.html

The function signaturehandler(ctx,route, req, res) is a route hook that is used only in API gateway. More info about Route hooks: https://moleculer.services/docs/0.13/moleculer-web.html#Route-hooks

Also, the req and res can't be passed to other services because these objects are not serializable.

Anyway, you might consider checking the video tutorial: https://www.youtube.com/watch?v=t4YR6MWrugw

It covers Moleculer's core concepts and shows how to call actions