gpt4 book ai didi

javascript - NodeJS 删除 API

转载 作者:太空宇宙 更新时间:2023-11-04 03:23:18 24 4
gpt4 key购买 nike

我必须使用 Node 构建一个 API 并将其表达为具有以下要求的包:

DELETE on /api/posts — there will be one query parameters: id. If the server has a post with the given ID, it should remove it and the response should be only the 200 status code. No other posts should be affected; in particular, their IDs won't change. If the server did not have a post with the given ID, the response should be the 404 status code.

我有以下代码可以正常工作

app.delete('/api/posts', (req, res) => {
let id = req.query.id;
if (typeof id !== 'number')
id = parseInt(id, 10);
let index;
for (let i = 0; i < posts.length; i += 1) {
if (posts[i].id === id) {
index = i;
break;
}
}
if (index == null) {
res.status(404).send();
return;
}
posts.splice(index, 1);
res.json(posts);
});

我的问题是,这种方法是否正确或者代码可以进一步改进吗?我刚刚开始学习 API 和 Node...

最佳答案

我不喜欢路线定义中的逻辑。所以我会这样写:

路由.js:

const posts = require('./posts.js')

app.delete('/api/posts', (req, res) => {
posts.delete(req.query.id)
.then(res.json)
.catch(() => { res.status(404).send() })
})

posts.js:

class posts {
constructor() {
this.posts = []
}
add(newPost) {
this.posts.push(newPost)
}

delete(postId) {
if (// test ob gelöscht werden kann) {
// löschen
return Promise.resolve(this.posts)
} else {
return Promise.reject(new Error('Can not delete post'))
}
}
}

这更像是伪代码,但希望您明白我的意思。我能够毫无困难地识别路线的用途和需求。如果我满足要求并收到错误,那么我会深入研究类定义。对我来说,这更容易维护。

关于javascript - NodeJS 删除 API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47832244/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com