March 23rd, 2019
์ผ๋จ ์ง๋ ํฌ์คํ ์์ ๋ค๋ค๋ 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()
}
})
์ด์ ๊ฐ์ด ๊ฐ๊ฒฐํ๊ฒ ๊ณ ์น ์ ์๋ค.
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)
์์์ ์ฌ์ฉํ ๋ ๊ฐ์ง ์ต์ 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.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)
})
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')
})
์ด๋ฌํ ๋ฐฉ์์ผ๋ก ์ ๋ฆฌํ๋ฉด ๋๋ค.