node.jsmoleculer

Constructing Context Object in MoleculerJS


I'm having trouble understanding the basic concept of MoleculerJS. I have a method called when a SQS message received.

const msg = await receiveOneMessageFromSQS();
/*
example structure of msg
{
  userId: 1
}
*/

Now I need to call another service and send "msg" as a service parameter.

await ctx.call(`AnothorService.AnotherAction`, msg);

I will need the Context object so I can call another service action (is this correct??). But as you see I don't have a Context object in the scope where I receive messages from SQS.

Question

Am I following a correct way to achieve what I want to do? If so, how can I construct a Context object?

Full code if needed

@Service({
    name: 'serviceName',
})
export class ServiceNameService extends MoleculerService {
    sqsClient: SQSClient;

    constructor(
        broker: Moleculer.ServiceBroker,
        schema: Moleculer.ServiceSchema<Moleculer.ServiceSettingSchema>,
    ) {
        super(broker, schema);
        this.sqsClient = new SQSClient({ region: "eu-central-1" });
    }
public async started() {
        const readFromSQS = async () => {
            const msg = await receiveOneMessageFromSQS();
            if (msg) {
              // PROBLEM HERE. No ctx here.
              await ctx.call(`AnothorService.AnotherAction`, msg);
            }
        };
        setInterval(async () => {
            await readFromSQS();
        }, 20000);
        return await connectionInstance();
    }
}

Solution

  • lifecycle methods don't have any input params meaning that you don't have context object by default.

    However, you can use await this.broker.call("service.name", {data}) and call another service.