moleculerjs / moleculer

:rocket: Progressive microservices framework for Node.js
https://moleculer.services/
MIT License
6.16k stars 586 forks source link

ctx.meta is empty in events #902

Closed mabc224 closed 3 years ago

mabc224 commented 3 years ago

Prerequisites

Please answer the following questions for yourself before submitting an issue.

Current Behavior

I am calling an action, and the action has ctx.meta available. as I set it during authorize phase. In hooks -> after, I change some response based on condition and emit an event. Emitting event has all data but missing meta. When I access ctx.meta, it is empty.

Expected Behavior

It should have ctx.meta available.

Failure Information

Steps to Reproduce

  1. Call action

  2. in hooks, after phase, emit an event, this.broker.emit('user..created', data, ['test']);

  3. try to access, ctx.meta, It is empty

Reproduce code snippet

https://codesandbox.io/s/moleculer-sample-forked-wji7t?file=/index.js

const broker = new ServiceBroker({
    logger: console,
    transporter: "NATS"
});

broker.createService({
    name: "test",
    events: {
        "user.created": {
            async handler(ctx) {
                console.log("Hello Meta: ", ctx.meta);
            }
        }
    },
    actions: {
        create(ctx) {
            ctx.meta.isAllowed = true;
            const newUser = {
                id: 1,
                name: 'any',
                isAllowed: ctx.meta.isAllowed
            }
            return newUser;
        }
    },
    hooks: {

        after: {
            async create(ctx, res) {
                ctx.broker.emit('user.created', res, ['test']);
                return res;
            }
        }
    }
});

Context

intech commented 3 years ago

Correct example: https://codesandbox.io/s/moleculer-sample-forked-3lget

moahammadalt commented 2 years ago

Can you write the example here, codesandbox code is not available anymore

ujwal-setlur commented 1 year ago

I am seeing this issue as well. How do I inject meta into an event?

ujwal-setlur commented 1 year ago

Ok, I figured it out. If you specify a meta key in the options object, the ctx.meta is then populated:

await serviceBroker.emit(
    'eventName',
    { foo: 'bar' },
    {
      meta: {
        auth: {}
      }
    }
  );