moleculerjs / moleculer

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

Call throws "options of undefined" when destructed from ctx #1033

Closed DenisFerrero closed 2 years ago

DenisFerrero commented 2 years ago

Prerequisites

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

Current Behavior

call method inside an action throws an error:

 TypeError: Cannot read property 'options' of undefined

at \node_modules\moleculer\src\context.js:260:12

NOTE This only happens when using the JS Object destructing feature

Expected Behavior

Returns related data asked to the target action called

Failure Information

I placed a breakpoint where the error was throw and when the breakpoint was hit, I read the variable state and I noticed that the value of this is undefined

Steps to Reproduce

Please provide detailed steps for reproducing the issue.

  1. Declare a new action
  2. Rather than access ctx variable, destruct it to directly access the call method
  3. Call another existing action this way using the call method

Reproduce code snippet

Codesandbox demo

const { ServiceBroker } = require("moleculer");

const broker = new ServiceBroker();

broker.createService({
  name: "demo",
  actions: {
    default(ctx) {
      return `Hello World!`;
    },
    async destructingCtx({ call }) {
      return await call("demo.default");
    },
    async directCtx(ctx) {
      return await ctx.call("demo.default");
    }
  }
});

broker.start().then(async () => {
  // NOT Working call
  broker.logger.info("--- Calling action with destructring ---");
  let res = await broker
    .call("demo.destructingCtx")
    .catch((err) => broker.logger.error(err.message));
  // Expected output: undefined
  broker.logger.info(res);

  // Working call
  broker.logger.info("--- Calling action without destructring ---");
  res = await broker
    .call("demo.directCtx")
    .catch((err) => broker.logger.error(err.message));
  // Expected output: Hello world
  broker.logger.info(res);

  // Stop broker
  broker.stop();
});

Context

Please provide any relevant information about your setup. This is important in case the issue is not reproducible except for under certain conditions.

Failure Logs

[2021-11-18T06:46:42.770Z] ERROR pc-30060/API:    Request error! TypeError : Cannot read property 'options' of undefined 
 TypeError: Cannot read property 'options' of undefined
    at call (c:\projects\backend\node_modules\moleculer\src\context.js:260:12)
icebob commented 2 years ago

A destructed method of a class loses the this value