I have created a helper.js
file that will contain helper functions
. In order to use the helper functions, I have to import the file in all the locations where I want it to be used. Is there any way I can load/import
the helper.js
file globally
?
helper.js
module.exports = {
responseObject: function (status, message, data, error) {
return {
status: status,
message: message,
data: data,
error: error
}
}
}
index.js
// load mongoose
require('./db/mongoose')
const express = require('express')
const app = express()
const port = process.env.PORT || 3000
app.use(helper)
// load routers
const userRouter = require('./routers/user')
app.use(express.json()) // automatically converts incoming requests to json
app.use(userRouter)
app.listen(port)
UserController.js
const User = require("../models/user")
const helper = require("../helper")
exports.createUser = async (req, res) => {
const user = new User(req.body)
try {
await user.save()
res.status(201).send({
status: true,
message: 'Registration success',
data: user,
error: {}
})
} catch (error) {
const response = helper.responseObject(false, "Wrong", {}, error)
res.status(400).send(response);
}
}