Репо: https://github.com/leongaban/api-design-node/tree/master
Моя коллекция Почтальон: https://www.getpostman.com/collections/b5a03b07836ad34b7758
Ожидаемый:
Текущий "символы льва:
[
{
"id": "1",
"name": "Teemo",
"pride": "LoL",
"age": "1",
"gender": "male"
},
{
"id": "2",
"name": "Nasus",
"pride": "LoL",
"age": "10",
"gender": "male"
}
]
PUT http://localhost:3000/lions/1
Тело:
{
"age": "1",
"gender": "female",
"name": "LuLu",
"pride": "LoL"
}
Должно вернуть этот новый список на GET всех львов:
[
{
"id": "1",
"name": "LuLu",
"pride": "LoL",
"age": "1",
"gender": "female"
},
{
"id": "2",
"name": "Nasus",
"pride": "LoL",
"age": "10",
"gender": "male"
}
]
Результаты
[
{
"id": "2",
"name": "Nasus",
"pride": "2",
"age": "2",
"gender": "female"
},
{
"0": { // <-- This should not be here
"id": "1",
"name": "Teemo",
"pride": "1",
"age": "1",
"gender": "female"
},
"age": "1",
"gender": "female",
"name": "LuLu",
"pride": "LoL"
}
]
Полный server.js
const express = require('express')
const app = express()
const bodyParser = require('body-parser')
const path = require('path')
const port = 3000
app.use(express.static('client'))
app.use(bodyParser.urlencoded({ extended: true }))
app.use(bodyParser.json())
let lions = []
let id = 0
app.get('/lions', function(req, res) {
console.log('GET lions:', lions)
res.json(lions)
})
app.get('/lions/:id', function(req, res) {
let lion = lions.filter((lion => lion.id === req.params.id))
res.json(lion || {})
})
app.post('/lions', function(req, res) {
id++
const lion = Object.assign({ id: id.toString() }, req.body)
lions.push(lion)
res.json(lion)
});
app.put('/lions/:id', function(req, res) {
const paramId = req.params.id
const updated = req.body
if (updated.id) {
delete updated.id
}
const oldLion = lions.filter((lion => lion.id === paramId))
if (!oldLion) {
res.send()
}
const newLion = Object.assign(updated, oldLion)
console.log('newLion', newLion)
lions = lions.filter(lion => lion.id !== paramId)
lions.push(newLion)
res.json(newLion)
});
app.listen(port, () => console.log(`NODE RUNNING on port: ${port}`))
Функция PUT
app.put('/lions/:id', function(req, res) {
const paramId = req.params.id
const updated = req.body
if (updated.id) {
delete updated.id
}
// Here I find the oldLion to replace by id:
const oldLion = lions.filter((lion => lion.id === paramId))
if (!oldLion) {
res.send()
}
// Here I create a new object for the new "lion":
const newLion = Object.assign(updated, oldLion)
console.log('newLion', newLion)
// Here I filter out the old lion:
lions = lions.filter(lion => lion.id !== paramId)
// New lion is pushed in:
lions.push(newLion)
res.json(newLion)
});