【发布时间】:2020-08-28 22:08:09
【问题描述】:
我想就这个问题寻求帮助。 这段代码的目标是:
- 使用请求正文的
artist属性中的信息更新具有指定艺术家ID 的artist,并将其保存到数据库中。在响应正文的artist属性上返回带有更新艺术家的 200 响应 - 如果缺少任何必填字段,则返回 400 响应
- 如果具有提供的
artistID 的艺术家不存在,则返回 404 响应。
这是失败的路线:
artistsRouter.put('/:artistId', (req, res, next) => {
if(areParamsRight(req.body.artist)){ // areParamsRight checks for the correct types and body's fields
db.serialize(() => {
db.run('UPDATE Artist SET name = $name, date_of_birth = $date_of_birth, biography = $biography WHERE id = $iD',
{ $name: req.body.artist.name,
$date_of_birth: req.body.artist.dateOfBirth,
$biography: req.body.artist.biography,
$is_currently_employed: req.body.artist.isCurrentlyEmployed,
$iD: req.artist.id }, (error) => { if(error) { next(error) }
});
db.get(`SELECT * FROM Artist WHERE id = $thisId `, { $thisId: req.artist.id } , (err, artist) => {
if(err){
next(err);
} else {
res.status(200).send(artist);
console.log('response sent. ')
}
})
})
} else {
res.setStatus(400);
}
});
我尝试了以下方法:
- 使用 .serialize() 避免竞争条件。
- 已验证 SQL 工作正常。
- 验证请求中的数据类型。
- 检查是否附加了 req.artist.id。
- 划分路线:
artistsRouter.put('/:artistId', (req, res, next) => {
if(areParamsRight(req.body.artist)){
db.serialize(() => {
db.run('UPDATE Artist SET name = $name, date_of_birth = $date_of_birth, biography = $biography WHERE id = $iD',
{ $name: req.body.artist.name,
$date_of_birth: req.body.artist.dateOfBirth,
$biography: req.body.artist.biography,
$is_currently_employed: req.body.artist.isCurrentlyEmployed,
$iD: req.artist.id }, (error) => { if(error) { next(error) }
});
next();
})
} else {
res.setStatus(400);
}
});
artistsRouter.put('/:artistId', (req, res, next) => {
db.get(`SELECT * FROM Artist WHERE id = $thisId `, { $thisId: req.artist.id } , (err, artist) => {
if(err){
next(err);
} else {
res.status(200).send(artist);
console.log('response sent. ')
}
})
})
在辅助函数下方。它似乎工作正常,因为它也用于 POST 路由。
// this function will accept req object and will return true if params are the proper type.
function areParamsRight(obj) {
const name = obj.name, dateOfBirth = obj.dateOfBirth, biography = obj.biography;
if( Object.keys(obj).includes('name' && 'dateOfBirth' && 'biography')
&& typeof name === 'string' && typeof dateOfBirth === 'string' && typeof biography === 'string' ){
return true;
} else return false;
}
module.exports = areParamsRight;
提前谢谢你。
【问题讨论】:
-
areParamsRight()是做什么的?" 请出示该代码。 -
我已经编辑了帖子。你所要求的在最后。
标签: javascript node.js sqlite express routes