问题描述
我无法理解 MoleculerJS 的基本概念。我在收到 SQS 消息时调用了一个方法。
const msg = await receiveOneMessageFromSQS();
/*
example structure of msg
{
userId: 1
}
*/
await ctx.call(`AnothorService.AnotherAction`,msg);
我将需要 Context 对象,以便我可以调用另一个服务操作(这是正确的吗?)。但是如您所见,我在接收来自 SQS 的消息的范围内没有 Context 对象。
问题
我是否遵循正确的方法来实现我想做的事情?如果是这样,我如何构造一个 Context 对象?
需要的完整代码
@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();
}
}
解决方法
lifecycle methods 没有任何输入参数,这意味着默认情况下您没有上下文对象。
但是,您可以使用 await this.broker.call("service.name",{data})
并调用其他服务。