Vishal
Vishal

Reputation: 129

How do I access Request and Response object in other files Node js(Express)

Below is my project folder structure :

app
    Controller
        testController.js
    Service
        testInfoService.js
        testMoreDataService.js
config
node-modules
public
    index.js
routes
    routes.js

Here some code :

routes.js

router.get('/config', (req, res) => {
    require(controllerDirectoryPath+"/testController.js").index(req, res)
})

testController.js

const testInfoService  = require('somePath/Service/testInfoService')
const index = async (req, res) =>{
    console.log('Request object : ');
    console.log(req);
    console.log('Response object : ');
    console.log(res);

    //getting more info from service 
    testMoreInfo = await testInfoService.getMoreInformation(args)
    return res.status(200).send(testMoreInfo);
}
module.exports = {index:index}

testInfoService.js

const testMoreDataService = require("somePath/testMoreDataService")
const getMoreInformation = async (args)=> {
    ...some code here 
    response =  await testMoreDataService.getMoreData(args)
    return response
}
module.exports = {getMoreInformation:getMoreInformation}

testMoreDataService.js

const getMoreData = async (args)=> {
    **//here I want to use Request and Response object**
    ...some code here 

    return response
}
module.exports = {getMoreData:getMoreData}

Is there any way I can access req and res object in my service?

I am using node : 12.16.2 with Express. Main file is public/index.js

Also let me know is this the correct way I am following for any application(REST-API)?

Upvotes: 1

Views: 1471

Answers (1)

Ramaraja
Ramaraja

Reputation: 2626

The structure is correct,

Route -> Controller -> Service

You don't have to propagate the actual req, res object all the way down to all the services. In your controller, you would fetch the following,

  • Query parameter. Eg. req.query.limit
  • Path variable. Eg.req.param.id
  • Request body. Eg. req.body/req.body.name

Once you get the required information in the controller, you could construct an object or pass the relevant information to your service.

Do all the business logic in your service and return the final information to the controller.

The controller would then send this response back to the client.

Upvotes: 1

Related Questions