即使在 moleculer.io 中的 `beforeCall()` 挂钩中将套接字附加到 `ctx` 后,仍获得 `undefined` 值

Getting `undefined` value even after attaching socket to `ctx` in `beforeCall()` hook in moleculer.io

我正在使用 moleculerjs 来处理后端的微服务,并且通过一个前端应用程序来处理通过套接字进行的通信。为此,我使用 moleculer.io。我 运行 遇到的问题是,即使我在 onBeforeCall() 挂钩中将套接字连接到 ctx,当我 console.log ctx 在控制器函数中。

我的网关看起来像这样(注意套接字被添加到 onBeforeCall() 挂钩中的 ctx 对象:

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, socket, res) { // after hook
                // console.log('after hook', res)
                // res: The response data.
              }
            }
          }
        }
      }
    },

    events: {},

    actions: {}
  }
};

我的 auth.service 看起来像这样 - 注意试图访问 ctx.socket:

register() 函数
"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.socketundefined。我在这里错过了什么?我假设 onBeforeCall() 就是为这种目的而设计的,但也许我误解了什么。

我应该或可以采用其他方法来确保套接字在被调用函数中可用吗?澄清一下,套接字在 onBeforeCall() 挂钩中可用。我需要弄清楚如何让它在线下可用。

你不能那样做。您不能向 ctx 中添加任何内容。 ServiceBroker 将仅序列化和传输 ctx.paramsctx.meta 属性。但是你不能把socket放进去,因为你喜欢的Socket对象是不可序列化的,所以你不能在远程服务中访问它。它可以在单体项目中工作,而不是在微服务项目中。

最后我找到了一个方法来做到这一点。正如@Icebob 指出的那样,您不能将套接字直接连接到 ctx,而是可以将它连接到 ctx.meta,就像这样:

onBeforeCall: async function(ctx, socket, action, params, callOptions) { // before hook
  ctx.meta.socket = socket;
},

通过这样做,我能够在 register() 函数中成功访问套接字。