Nailer's blog

Node-RESTful API (2)

March 23rd, 2019

nodejs ์ผ๋‹จ ์ง€๋‚œ ํฌ์ŠคํŒ…์—์„œ ๋‹ค๋ค˜๋˜ async/await์„ ํ™œ์šฉํ•˜์—ฌ ์‹ค์Šต ํ”„๋กœ์ ํŠธ๋ฅผ ์ˆ˜์ •ํ•˜๋ฉด

app.post('/users', async (req, res) => {
  const user = new User(req.body)

  try {
    await user.save()
    res.status(201).send(user)
  } catch(error) {
    res.status(400).send()
  }
})

์ด์™€ ๊ฐ™์ด ๊ฐ„๊ฒฐํ•˜๊ฒŒ ๊ณ ์น  ์ˆ˜ ์žˆ๋‹ค.

Resource Updating Endpoint


Updating a User

app.patch('/users/:id', async (req, res) => {
  const updates = Object.keys(req.body)
  const allowedUpdates = ['name', 'email', 'password', 'age' ] 
  const isValidOperation = updates.every(update => allowedUpdates.includes(update))

  if(!isValidOperation) {
    return res.status(400).send({ error: 'Invailid Updates' })
  }
  try {
    const user = await User.findByIdAndUpdate(req.params.id, req.body, { new: true, runValidators: true })
    if (!user) {
      return res.status(404).send()
    }
    res.status(202).send(user)
  } catch (error) {
    res.status(400).send(error)
  }
})

const updates = Object.keys(req.body)

**Object.keys()**๋Š” object์—์„œ key๊ฐ’๋“ค์— ๋Œ€์‘ํ•˜๋Š” ๋ฌธ์ž์—ด๋“ค์„ ์š”์†Œ๋กœ ๊ฐ–๋Š” ๋ฐฐ์—ด์„ ๋ฐ˜ํ™˜ํ•œ๋‹ค. ๋ฐ˜ํ™˜๋œ ์š”์†Œ๋Š” loop๋ฌธ์„ ์‹คํ–‰ํ•  ๋•Œ ์ฃผ์–ด์ง€๋Š” ์ˆœ์„œ์™€ ๋™์ผํ•˜๋‹ค.

const isValidOperation = updates.every(update => allowedUpdates.includes(update))

Array.prototype.every()

The every() method tests whether all elements in the array pass the test implemented by the provided function. (์ „๋ถ€ true์ผ ๊ฒฝ์šฐ์—๋งŒ true)

findByIdAndUpdate() docs

์œ„์—์„œ ์‚ฌ์šฉํ•œ ๋‘ ๊ฐ€์ง€ ์˜ต์…˜ new์™€ runValidators๋Š”

  • new: bool - if true, return the modified document rather than the original. defaults to false (option์ด ์—†์„ ๋•Œ๋Š” original document๋ฅผ ruturnํ–ˆ์Œ)
  • runValidators: if true, runs update validators on this command. Update validators validate the update operation against the model's schema.

Resource Deletion Endpoint


app.delete('/users/:id', async (req, res) => {
  
  try {
    const user = await User.findByIdAndDelete(req.params.id)
    if(!user) {
      res.status(404).send()
    }
    res.status(200).send(user)
  } catch (error) {
    res.status(500).send()
  }
})

user๊ฐ€ ์—†์„๊ฒฝ์šฐ 404 not found๋กœ ์ฒ˜๋ฆฌ

error์ผ ๊ฒฝ์šฐ 500 internal server error ์ฝ”๋“œ๋ฅผ ๋ณด๋‚ด์ค€๋‹ค.

๋น„๊ต์  ๊ฐ„๋‹จํ•œ ์ฝ”๋“œ๋กœ ํ•ด๋‚ผ ์ˆ˜ ์žˆ๋‹ค.

์ด๋Ÿฌํ•œ ๋ชจ๋“  ์š”์ฒญ๋“ค์„ index.js ํ•˜๋‚˜์˜ ํŒŒ์ผ์— ๊ทธ ์ฒ˜๋ฆฌ๋ฅผ ์ž‘์„ฑํ•˜๋ฉด ์œ ์ง€๋ณด์ˆ˜๋ฅผ ํ•˜๊ธฐ ์–ด๋ ต๋‹ค.

๊ทธ๋ž˜์„œ express.Router๋ฅผ ํ™œ์šฉํ•ด์„œ refactoring์„ ์ง„ํ–‰ํ•œ๋‹ค.

๊น”๋”ํ•ด์ง„ index.js

const express = require('express')
require('./db/mongoose')

const userRouter = require('./routers/user')
const taskRouter = require('./routers/task')

const app = express()
const port = process.env.PORT || 3000

app.use(express.json()) // json์„ ์ž๋™์œผ๋กœ parseํ•ด์ค€๋‹ค.
app.use(userRouter)
app.use(taskRouter)


app.listen(port, () => {
  console.log('Server is up on port ' + port)
})

image-20190325160357485

routers ํด๋”์•ˆ์— ์ •๋ฆฌํ•˜๊ณ 

const express = require('express')
const router = new express.Router()
const User = require('../models/user')

router.get('/test', (req, res) => {
  res.send('This is user.js test')
})

์ด๋Ÿฌํ•œ ๋ฐฉ์‹์œผ๋กœ ์ •๋ฆฌํ•˜๋ฉด ๋œ๋‹ค.

Related Posts

Created by SeongHeum CHOI, 2020