如何解决即使在molecularr.io中的`beforeCall()`钩子中将套接字附加到`ctx`后也获得`undefined`值
我正在使用molecularrjs 来处理后端的微服务,并使用其中一个前端应用程序来处理通过套接字进行的通信。为此,我使用了 moleculer.io
。我遇到的问题是,即使我将套接字连接到 ctx
钩子中的 onBeforeCall()
,但当我在控制器中 console.log ctx
时套接字不存在功能。
我的网关看起来像这样(注意套接字被添加到 ctx
钩子中的 onBeforeCall()
对象:
const SocketIOService = require("moleculer-io");
module.exports = {
name: 'oas',mixins: [SocketIOService],settings: {
port: 5000,io: {
namespaces: {
'/': {
events: {
'call': {
aliases: {
'auth.register': 'oas.controllers.auth.register'
},whitelist: [
'**',],onBeforeCall: async function(ctx,socket,action,params,callOptions) { // before hook
console.log('socket: ',socket); // This exists here
ctx.socket = socket; // Here I attach the socket to the ctx object
},onAfterCall: async function(ctx,res) { // after hook
// console.log('after hook',res)
// res: The response data.
}
}
}
}
}
},events: {},actions: {}
}
};
我的 auth.service 看起来像这样 - 注意尝试访问 register()
的 ctx.socket
函数:
"use strict";
/**
* @typedef {import('moleculer').Context} Context Moleculer's Context
*/
module.exports = {
name: "oas.controllers.auth",/**
* Settings
*/
settings: {
},/**
* Dependencies
*/
dependencies: [],/**
* Actions
*/
actions: {
async register(ctx) {
console.log('ctx.socket: ',ctx.socket); // This is undefined
// Other code...
},/**
* Events
*/
events: {
},/**
* Methods
*/
methods: {
},/**
* Service created lifecycle event handler
*/
created() {
},/**
* Service started lifecycle event handler
*/
async started() {
},/**
* Service stopped lifecycle event handler
*/
async stopped() {
}
};
在被调用的 register()
函数中,ctx.socket
是 undefined
。我在这里缺少什么?我认为 onBeforeCall()
的设计目的正是用于这种目的,但也许我误解了一些东西。
我应该或可以采用其他方法来确保套接字在被调用函数中可用吗?只是为了澄清,套接字在 onBeforeCall()
钩子中可用。我需要弄清楚如何让它上线。
解决方法
你不能那样做。您不能将任何内容放入 ctx
。 ServiceBroker 将仅序列化和传输 ctx.params
和 ctx.meta
属性。但是你不能把socket放进去,因为你喜欢的Socket对象是不可序列化的,所以在远程服务中是无法访问的。它可以在单体项目中工作,而不是在微服务项目中。
最后我找到了一种方法来做到这一点。正如@Icebob 指出的那样,您不能直接将套接字连接到 ctx
,而是将它连接到 ctx.meta
,如下所示:
onBeforeCall: async function(ctx,socket,action,params,callOptions) { // before hook
ctx.meta.socket = socket;
},
通过这样做,我能够成功访问 register()
函数中的套接字。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。