Search code examples
javascriptnode.jsexpressscopeopenapi-generator

Unable to pass an object to exported javascript module on nodejs / expressjs


I am not able to pass an object to function exported from another module. Here's how the story goes.

I am exporting a function from module TagService.js

file: TagService.js

addTag = ({tag}) => {
  //some activity
}

module.exports = { addTag, //other functions}

Invoking the function from module ServiceHandler.js

file: ServiceHandler.js

const Controller = require('./Controller');
const service = require('../services/TagService');
const addTag = async (request, response) => {
  await Controller.handleRequest(request, response, service.addTag);
};

Here's how the controller is structured in Controller.js

file: Controller.js

static async handleRequest(request, response, serviceOperation) {
  //some activity    
  const serviceResponse = await serviceOperation(this.collectRequestParams(request));
  //some more activity...
}

static collectRequestParams(request) {
  //some activity
  return requestParams;
}

Now, in the Controller, requestParams is returned successfully. But when the call steps into addTag function at TagService, the object tag is not passed!

A little bit more background. This is code generated from openapi-generator for the nodejs-express-server stub.

Here's the openapi.yaml template for tag service.

/samyojya-tag:
    post:
      operationId: addTag
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/Tag'
      responses:
        "201":
          content:
...
schemas:
  Tag:
      example:
        name: name
        id: 1
        type: type
      properties:
        id:
          type: string
        name:
          type: string
        category:
          type: string
      type: object
      xml:
        name: Tag

Using node 12.16.2 and express 4.16.1


Solution

  • I guess the problem is that you destructure the object with ({...})

    In your case you can only access the property tag from your passed object, if your passed object dont have a property called named tag, its undefined.

    You should change this ({tag}) to this (tag) to have the full access of your passed object

    var obj = {
       test: "i work",
       tag: "i work too"
    }
    
    function test({tag}){
       console.log(tag);
    }
    
    function test2(tag){
       console.log(tag);
    }
    
    test(obj)
    test2(obj);