Nodejs-Assignment-7

 Create User API & Product API using async & await. Handle asynchronous errors using try/catch OR express-async-handler module.



User API for ref

---------------------

//create mini-express app(A router)
const exp = require("express");
const userApp = exp.Router();

const expressAsyncHandler = require("express-async-handler");

const bryptjs = require("bcryptjs");

//body parser middleware
userApp.use(exp.json());

//CREATE user API

//create user
userApp.post(
"/user-signup",
expressAsyncHandler(async (request, response) => {
//get userCollectionObj
const userCollectionObj = request.app.get("userCollectionObj");

//get newUser from request
const newUser = request.body;

//check for duplicate user by username
let userOfDB = await userCollectionObj.findOne({
username: newUser.username,
});
//if user already existed, send res to clint as "User already existed"
if (userOfDB != null) {
response.status(200).send({ message: "User already existed" });
}
//if user not existed
else {
//hash the password
let hashedPassword = await bryptjs.hash(newUser.password, 5);

//replace plain pass with hashed password
newUser.password = hashedPassword;
//insert user
await userCollectionObj.insertOne(newUser);
//send res
response.status(201).send({ message: "User created" });
}
})
);

//export userApp
module.exports = userApp;

Comments

Popular posts from this blog