๐Ÿ“backend ์ผ์ง€๐Ÿ“

GONIยท2021๋…„ 9์›” 28์ผ
0
post-thumbnail

[user์ƒ์„ฑ ์ฝ”๋“œ] - ๊ฐ„๋‹จํ•˜๊ฒŒ post(signup)๊ณผ์ •๋งŒ ๊ธฐ๋กํ•ด๋ณด๋ ค๊ณ  ํ•œ๋‹ค.


app.jsํŒŒ์ผ

(๊ธฐ๋กํ•  ๊ฒƒ์ด ์—๋Ÿฌ ํ•ธ๋“ค๋ง ๋ฟ...)

app.use("/api/users", usersRoutes)
  1. ์กด์žฌํ•˜์ง€ ์•Š๋Š” ๋ผ์šฐํŠธ์— ๋Œ€ํ•œ ์—๋Ÿฌ ํ•ธ๋“ค๋ง
app.use((req, res, next) => {
  return next(new ExpressError("ํŽ˜์ด์ง€๋ฅผ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค.", 404))
})
  1. Express ์˜ค๋ฅ˜์ฒ˜๋ฆฌ document๋ฅผ ์ฐธ๊ณ ํ•œ ์—๋Ÿฌ ํ•ธ๋“ค๋ง ๋ฏธ๋“ค์›จ์–ด
app.use((err, req, res, next) => {
  console.log("error: ", err.stack)
  res
    .status(err.code || 500)
    .json({ message: err.message || "An unknown error occurred!" })
})

users-route.jsํŒŒ์ผ

const express = require("express")
const router = express.Router()

validtaion check ๋ชจ๋“ˆ

const { check } = require("express-validator")
router.post(
  "/signup",
  [
    check("name").not().isEmpty()
    check("email").normalizeEmail().isEmail(),
    check("password").isLength({ min: 5 }),
  ],
  users.signUpUser,
)

users-controller.jsํŒŒ์ผ

ํ˜„์žฌ๋Š” ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค๊ฐ€ ๋งŒ๋“ค์–ด์ง€์ง€ ์•Š์€ ์ƒํƒœ์ด๋ฏ€๋กœ ์ง์ ‘ ๋ฐฐ์—ด์— pushํ•˜๋Š” ๋ฐฉ๋ฒ•์„ ์‚ฌ์šฉํ•˜์˜€๋‹ค.

module.exports.signUpUser = (req, res, next) => {
  const errors = ValidationResult(req)
  if (!errors.isEmpty()) {
    console.log(errors)
    return next(new ExpressError("์œ ํšจํ•˜์ง€ ์•Š์€ ๋ฐ์ดํ„ฐ ์ž…๋‹ˆ๋‹ค.", 422))
  }
  const { name, email, password } = req.body
  const createdUser = {
    id: uuid(),
    name,
    email,
    password,
  }
  USERS_DB.push(createdUser)
  res.json({ user: createdUser })
}

validation ์ฒดํฌ๋ฅผ ํ•œ ๊ฒฝ์šฐ

const errors = ValidationResult(req)

ํ•ด๋‹น ์ฝ”๋“œ๋ฅผ ํ†ตํ•ด ์—๋Ÿฌ ๋ฐœ์ƒ ์—ฌ๋ถ€๋ฅผ ํŒ๋‹จํ•  ์ˆ˜ ์žˆ๊ณ ,
๋‹ค๋ฅธ ๊ฒฝ์šฐ์—๋Š” ์˜ˆ์™ธ๊ฐ€ ๋  ์ƒํ™ฉ์„ ์ƒ๊ฐํ•˜์—ฌ next()์— error๋ฅผ ๋„ฃ์–ด์ฃผ๋ฉด ๋œ๋‹ค.

์—ญ์‹œ error handling์ด ์•„์ง๊นŒ์ง„ ์ œ์ผ ์‹ ๊ฒฝ์“ธ๊ฒŒ ๋งŽ์€ ๊ฒƒ ๊ฐ™๋‹ค,,,,

profile
์˜ค๋กœ์ง€ ๋‚˜์˜ ๊ธฐ์–ต๋ ฅ์„ ์œ„ํ•œ ์ผ์ง€

0๊ฐœ์˜ ๋Œ“๊ธ€