I am struggling with setting up an Express JS router.
I am facing difficulty passing req and res to my class method.
Not Working app.get('/', controller.index)
Working
app.get('/', (res,req) => controller.index(req,res)
The routing flow I implemented follows this path:
app.js (Main file) > /routes/index.js > /routes/user.route.js > /controllers/user.controller.js > /services/user.services.js
app.js
import express from 'express';
import cors from 'cors';
import routes from './routes';
import db from './models';
import dotenv from 'dotenv';
dotenv.config();
const app = express();
const port = process.env.PORT || 3001;
app.use(cors())
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
// Database Initialize
db.sequelize.sync()
.then(() => {
console.log("🚀 Database Connected.");
}).catch((err) => {
console.log("❌ Failed Connect to Database");
})
// Router
app.use(routes);
//global dir
global.__basedir = __dirname;
app.enable("trust proxy");
app.listen(port, () => {
// logger.info("Checking the API status: Everything is OK");
console.log(`🚀 App listening on port ${port}`);
})
routes/index.js
import express from "express";
import appRoutes from './app.routes';
import roleRoutes from './role.routes';
import userRoutes from './user.routes';
import authRoutes from './auth.routes';
const app = express();
// App Routes
app.use('/app', appRoutes);
// Role Routes
app.use('/role', roleRoutes);
// User Routes
app.use('/user', userRoutes);
// Auth Routes
app.use('/auth', authRoutes);
export default app;
routes/user.routes.js
import express from 'express';
import userController from '../controllers/user.controller';
import validateAuth from '../middlewares/validateAuth';
const app = express();
const controller = new userController;
app.get('/', controller.index);
export default app;
controllers/user.controller.js
import userServices from "../services/user.services";
import baseController from "./base.controller";
export default class userController extends baseController {
constructor() {
super(new userServices());
}
}
controllers/base.controller.js
import response from "../helpers/response";
import lang from "../helpers/lang";
import dotenv from "dotenv";
dotenv.config();
export default class baseController {
constructor(service) {
this.service = service
}
/**
* Index
* Get all data with pagination
*/
async index(res, req) {
try {
const data = await this.service.paginate(req.query);
if(data) {
return response.success({
res,
message: lang[process.env.LANG].DATA_LOADED,
data
});
} else {
throw new Error(lang[process.env.LANG].REQUEST_FAILED);
}
} catch(err) {
console.log(err)
return response.error({
res,
message: err.message,
});
}
}
}
services/user.services.js
import baseServices from "./base.services";
import db from "../models";
export default class userServices extends baseServices {
constructor() {
const attributes = [
"roleId",
"appId",
"username",
"password",
"name",
"phone",
"email",
"isActive",
];
super(db.user, attributes);
}
/**
* Paginate
* @param {{
* search: string,
* limit: number,
* offset: number,
* sortBy: string,
* orderBy: string,
* user: object
* }} data
* return Promise
*/
paginate(data) {
const { search, limit, page, sortBy, orderBy, user } = data;
const offset = limit
? parseInt(limit) * parseInt(page) - parseInt(limit)
: 0;
let filter = {};
if (search)
Object.assign(filter, { name: { [Op.like]: `%${search}%` } });
const condition = {
where: filter ? filter : "",
order: sortBy ? [[sortBy, orderBy]] : [["name", "asc"]],
limit: limit ? parseInt(limit) : 10,
offset,
include: ["role", "app"]
};
return this.model.findAndCountAll(condition);
}
}
services/base.services.js
import db from "../models";
const Op = db.Sequelize.Op;
/**
* Base Services Class
*/
export default class baseServices {
constructor(model, attributes = []) {
this.model = model;
this.attributes = attributes
}
}
Response
Not Working app.get('/', controller.index)
Error Response
Working
app.get('/', (res,req) => controller.index(req,res)
I attempted changing const app = express()
and const app = express.Router()
but the issue persists.