How to use asynchandler in class in nodejs - javascript

I am trying to change my routers into class but I don't know how to wrap the asyncHandler in function inside the class
userController.js
const asyncHandler = require('express-async-handler')
class UserController {
async Register(req, res){
const {firstName} = req.body
return res.status(200).send(firstName)
}
}
const userController = new UserController()
module.exports = userController
userRouter.js
const express = require('express')
const userController = require('../controllers/userController')
const router = express.Router()
router.post('/register', userController.Register)
module.exports = router

You can actually use asyncHandler like this,
As per the docs
router.post('/register', asyncHandler(userController.Register))

Related

How to use class methods without useing "type": "module" in node js

js developer.
I am making express and jade web app. Now I am trying to call class method in index.router.js from login.controller.js, I have been looking for a way to call the method without adding "type": "module" in package.json. This is because my teacher said I should avoid using it for now. I have been looking for a solution for this, but I haven't figured out how. Thanks for reading!
Here's my code:
//This is index.route.js
const express = require('express');
const app = express();
const IndexRouter = express.Router();
const LoginController = require('../controllers/login.controller')
IndexRouter.use('/', LoginController.login())
module.exports = IndexRouter
//This is login.controller.js
module.exports = class LoginController{
async login (req,res) {
res.send("Login Page")
}
}
Create Class Objects and use class objects to access class
methods
In index.route.js
const express = require('express');
const app = express();
const IndexRouter = express.Router();
const LoginController = require('../controllers/login.controller')
const loginController = new LoginController();
IndexRouter.use('/', loginController.login())
module.exports = IndexRouter
In login.controller.js
class LoginController {
async login(req, res) {
res.send("Login Page")
}
}
module.exports = LoginController;
For Ex.
class LoginController {
login(req, res) {
console.log("LoginController Login");
}
}
const loginController = new LoginController();
loginController.login();
Or can directly access Login function without using class
In index.route.js
const express = require('express');
const app = express();
const IndexRouter = express.Router();
const { login } = require('../controllers/login.controller')
IndexRouter.use('/', login()); // or use('/', login) if using middleware
module.exports = IndexRouter
In login.controller.js
async function login(req, res) {
res.send("Login Page")
}
module.exports = {
login
};

how to get all of registered users

How can I get all the registered users in my course-booking system?
this is my controllers user.js
const User = require("../models/User") //import user model
const bcrypt = require("bcrypt") //import bcrypt
const auth = require("../auth")
module.exports.getAllUsers = (params) => {
return User.find(params.userId).then(resultFromFind => {
return resultFromFind
})
}
and this is my routes user.js
const express = require("express")
const router = express.Router()
const UserController = require("../controllers/user")
const auth = require("../auth")
router.get('/all', auth.verify, (req, res) => {
const users = auth.decode(req.headers.authorization)
UserController.getAllUsers().then(user => res.send(user))
})
I don't know why I get this error on my console.. please help
GET http://localhost:3000/api/users/all 500 (Internal Server Error)
You need to pass the params as a parameter of getAllUsers()
const express = require("express")
const router = express.Router()
const UserController = require("../controllers/user")
const auth = require("../auth")
router.get('/all', auth.verify, (req, res) => {
const users = auth.decode(req.headers.authorization)
UserController.getAllUsers(req.params).then(user => res.send(user)) // <------------------------
})

Get parameter from previous route handler in express js

Say I have file1.js:
import Router from "express-promise-router";
export const router1 = Router();
router1.get("/", async (req, res) => {
// I want to get here :id from router2 in file2
})
And file2.js (in the same directory for simplicity):
import Router from "express-promise-router";
import { router1 } from "./file1";
export const router2 = Router();
router2.use("/:id/path", router1);
I want to use /:id from file2.js in file1.js (see my comment in example code).
How can I do that?
In other words, how can I percolate '/:something' parameter down the routers chain?
Note - this doesn't work:
router1.get("/", async (req, res) => {
const { params: {id} } = req;
})
I found the answer.
From express api:
So should add the option mergeParams set to true when declaring the router handler.
In general:
const router = express.Router({mergeParams: true});.
For the question's example code in file1.js:
import Router from "express-promise-router";
export const router1 = Router({mergeParams: true});
router1.get("/", async (req, res) => {
const { params: {id} } = req; // now this works
})

How do I use external routes in my routes index file

I have a users.js and a index.js file.
users.js
const express = require('express');
const router = express.Router();
const {catchErrors} = require('../handlers/errorHandlers');
const authController = require('../controllers/authController');
router.post('login/', catchErrors(authController.login));
module.exports.router = router;
index.js
// Route handlers
let userRouter = require('./users');
router.use('/user', userRouter);
module.exports = router;
I tried this and it's not working. I would appreciate any advice.
In your users.js file you're exporting an object with the property router (module.exports.router = router) which would look like..
module.exports = {
router: router
}
and in your index you're importing the object from users.js but not accessing the router when passing it to router.use(...).
You should pass the router in your index.js file
index.js
const express = require('express');
const router = express.Router();
// You can access the router on the require
const userRouter = require('./users').router;
router.use('/user', userRouter);
// Or on the object after the require
const userRouter = require('./users');
router.use('/user', userRouter.router);

Route.get() requires a callback function but got a [object Undefined]. What did I do wrong?

I have checked many answers in other pages and forums, but I still don't get it. What did I do wrong? Help me
*edited. I have added requiring routes and app.use. It looks like function isLOggedIn is not exporting but I don't know how to do that. I did like this in another app, it worked there.
auth-routes.js
const express = require("express"),
router = express.Router(),
passport = require("passport")
function isLoggedIn(req, res, next) {
if (req.isAuthenticated()) {
return next()
}
res.redirect("/auth/login")
}
module.exports = router
user-routes.js
const express = require("express"),
router = express.Router(),
authRoutes = require("./auth-routes")
router.get("/profile", authRoutes.isLoggedIn, (req, res) => {
res.render("user/profile", {user: req.user})
})
module.exports = router
requring routes
const titleRoutes = require("./routes/title-routes")
const authRoutes = require("./routes/auth-routes")
const userRoutes = require("./routes/user-routes")
app.use
app.use(titleRoutes)
app.use("/auth", authRoutes)
app.use("/user", userRoutes)
In auth-routes.js you don't export isLoggedIn. So in user-routes.js, authRoutes.isLoggedIn is undefined.
You can change:
module.exports = router
into:
exports.isLoggedIn = isLoggedIn
or using module.exports into:
module.exports = { isLoggedIn: isLoggedIn }
A useful link to understand export in nodejs https://www.sitepoint.com/understanding-module-exports-exports-node-js/

Categories