๐ฉ๐ป ๋ฐฑ์๋(Back-End)/Node js
[E-Commerce App with REST API] (3) Async Request Handler ํ์ฉํ ์๋ฌ & bcrypt์ hashl, Salt ์ ์ฉ
์ง์ง์ํ์นด
2023. 3. 21. 01:44
728x90
๋ฐ์ํ
<๋ณธ ๋ธ๋ก๊ทธ๋ Developers Corner ์ ์ ํ๋ธ๋ฅผ ์ฐธ๊ณ ํด์ ๊ณต๋ถํ๋ฉฐ ์์ฑํ์์ต๋๋ค :-)>
=> Node.js E-Commerce App with REST API: Let's Build a Real-Life Example!
๐ท Async Request Handler
async๋ฅผ ์ฝ๊ฒ ์ฌ์ฉ
Request Handler๋ฅผ ์ฒ๋ฆฌํ๋๋ฐ ๊ณตํต์ ์ผ๋ก ์ค๋ฅ์ฒ๋ฆฌ๋ฅผ ํ ์ ์๊ฑฐ๋ ๊ฐ๋จํ๊ฒ ๊ตฌํ
npm i express-async-handler
โ
request handler์์ ์ค๋ฅ ์ฒ๋ฆฌ ๋ฐฉ๋ฒ
- promise().catch(next)
- async function, try ~ catch, next
๐ท bcrypt๋ก ๋น๋ฐ๋ฒํธ hash ์ ์ฉํ๊ธฐ
๐ท ์ฝ๋
โ index.js
const express = require("express");
const bodyParser = require("body-parser");
const dbConnect = require("./config/dbConnect");
const {notFound, errorHandler} = require("./middlewares/errorHandler");
const app = express();
require("dotenv").config();
const PORT = process.env.PORT || 8000;
const authRouter = require("./routes/authRoute");
// mongoDB
dbConnect();
// Bodyparser
// express์๋ฒ๋ก POST์์ฒญ์ ํ ๋ inputํ๊ทธ์ value๋ฅผ ์ ๋ฌ
// URL-encoded ํ์์ ๋ฌธ์์ด๋ก ๋์ด์ค๊ธฐ ๋๋ฌธ์ ๊ฐ์ฒด๋ก์ ๋ณํ ํ์
app.use(bodyParser.json());
app.use(express.urlencoded({ extended: false }));
app.use("/api/user", authRouter);
app.use(notFound);
app.use(errorHandler);
app.use("/", (req, res) => {
res.send("hihi");
})
app.listen(PORT, () => {
console.log(`๐ Server started on port http://localhost:${PORT}`);
});
โ E-CommerceApp/index.js
// not found
const notFound = (req, res, next) => {
const error = new Error(`Not Found : ${req.originalUrl}`);
res.status(404);
next(error);
};
// Error Handler
// - 1xx
// : ์์ฒญ์ ๋ฐ์์ผ๋ฉฐ ํ๋ก์ธ์ค ๊ณ์ ์งํ
// - 2xx
// : ์์ฒญ์ ์ฑ๊ณต์ ์ผ๋ก ๋ฐ์์ผ๋ฉฐ ์ธ์ํ๊ณ ์์ฉ
// - 3xx
// : ์์ฒญ ์๋ฃ๋ฅผ ์ํด ์ถ๊ฐ ์์
์กฐ์น ํ์
// - 4xx
// : ์์ฒญ์ ๋ฌธ๋ฒ์ด ์๋ชป๋์๊ฑฐ๋ ์์ฒญ ์ฒ๋ฆฌ ๋ถ๊ฐ๋ฅ
// - 5xx
// : ์๋ฒ๊ฐ ๋ช
๋ฐฑํ ์ ํจํ ์์ฒญ์ ๋ํด ์ถฉ์กฑ์ ์คํจ
const errorHandler = (err, req, res, next) => {
const statuscode = res.statusCode == 200 ? 500 : res.statusCode;
res.status(statuscode);
res.json({
message: err?.message,
stack: err?.stack
});
};
module.exports = {
notFound,
errorHandler
};
โ controllers/userCtrl.js
const User = require("../models/User");
const bcrypt = require("bcrypt");
const asyncHandler = require("express-async-handler");
const createUser = asyncHandler(async (req, res) => {
const { firstname, lastname, email, mobile, password } = req.body;
const findUser = await User.findOne({ email: email });
// email์ด db์ ์๋ค๋ฉด
if (!findUser) {
// Create a new User
// 1) ์ฐ์ ๋น๋ฐ๋ฒํธ ํด์ฌํ(์ํธํ)
const hashedPassword = await bcrypt.hash(password, 10);
// 2) ์ User ์ ๋ณด ๋ง๋ค๊ธฐ
const newUser = await User.create({
firstname, lastname, email, mobile, password: hashedPassword
});
res.json(newUser);
} else {
// User already exists
throw new Error("User already exists");
}
});
module.exports = { createUser };
728x90
๋ฐ์ํ