0

I want have 2 functions in report.js file I want to one is report_data which is api controller and second is test I want to use test function in report_data function.
Below is my code of both functions.

var sequelize = require('../config/sequelize');
const Op = sequelize.Sequelize.Op;
var errors = require('../config/errors');
var error = errors.errors;
const helpers = require('../helpers/validations');
const logger = require('../helpers/logger').logger;
const fs = require('fs');

module.exports = {
    report_data: async (req, res) => {
        if (!req.body.id) {
            logger.warn(error.MANDATORY_FIELDS);
            return res.status(500).send(error.MANDATORY_FIELDS)
        }

        sequelize.sequelize.transaction(async (t1) => {
            console.log('socket connected')
        test(io)
           
            let result = error.OK
            logger.info(result);
            return res.status(200).send(result)

        }).catch(function (err) 
            logger.warn(err);
            console.log(err)
            return res.status(500).send(error.SERVER_ERROR)
        })
    },

    test: function (io) {
        console.log(io.sockets)
    }
};
Aryan
  • 3,338
  • 4
  • 18
  • 43

1 Answers1

0

The easiest would be to declare test as a named global function:

function test(io) {
    console.log(io.sockets)
}

module.exports = {
    report_data: async (req, res) => {
        // now you call call `test()` here
    },
    test: test,
}
Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268
  • is it possible to use it without declaring it global – Aryan Oct 08 '20 at 16:43
  • 2
    It's not a global. It's local to the module. – Bergi Oct 08 '20 at 16:45
  • in this function i am geting io object but not able to understand how to get values from it – Aryan Oct 08 '20 at 16:53
  • right now in report_data i am trying this` test(io.emit('connectToRoom', "You are in room no. " + userId))` but it shows `io is not defined` – Aryan Oct 08 '20 at 16:56
  • @Arya `report_data` has no variable named `io`. What do you expect `io` to be? Is it a variable? Is it a module you need to import? Or what? Keep these in mind and post a new question that provides this information. – Code-Apprentice Oct 08 '20 at 16:59
  • as you can see in this answer https://stackoverflow.com/a/38514118/12761193 they are exporting socket i other module and i am doing same like it – Aryan Oct 08 '20 at 17:03
  • @Arya What you have isn't quite the same as what is explained in that answer. I suggest you take a closer look and modify your code accordingly. One thing you need to reconcile here: do you really want to export both the `report_data()` and `test()` functions? Is `test()` used anywhere outside of `report_data()`? – Code-Apprentice Oct 08 '20 at 17:31
  • @Arya And please post a new question. I will no longer respond to comments here. – Code-Apprentice Oct 08 '20 at 17:31