不存在的 id n 抛出新的 ResourceNotFoundError(id)"/>
为不存在的 id n 抛出新的 ResourceNotFoundError(id)
我正在构建一个小型的 Full Stack 系统(typescript、express、NodeJs),在其中一条路线中,用户可以根据所选的剧院要求电影,这是具体的服务:
async function getMoviesByTheatreId(theatreId : number) : Promise<MovieModel[]> {
// SQL:
const sql = 'SELECT * FROM movies where theatreId = ?;'
// Call dal:
const movies = await dal.execute(sql ,[theatreId]);
// Return:
return movies;
}
澄清 MYSQL 数据库中有两个表 - theaters 和 movies。它们共享一个引用剧院表中“theatreId”列的外键。外键是电影表中的那个。
现在,用户有可能发送一些不存在的 theatreId,在这种情况下,我想抛出新的 ResourceNotFoundError。然而,也有可能 theatreId 确实存在,但没有任何电影与该剧院匹配。在那种情况下,我不想抛出那个错误。 我也希望它在性能方面表现出色,因为使用多个查询检查数据库会减慢整个过程。
回答如下:首先,在查询电影表之前,检查剧院表中是否存在提供
theatreId
的剧院。然后,你可以查询电影。
这里是示例代码:
async function getMoviesByTheatreId(theatreId : number) : Promise<MovieModel[]> {
const theatreSql = 'SELECT * FROM theatres WHERE theatreId = ?';
const theatre = await dal.execute(theatreSql, [theatreId]);
if (theatre.length === 0) {
// throw new ResourceNotFoundError('Theatre not found');
}
// SQL to retrieve movies with provided theatreId:
const moviesSql = 'SELECT * FROM movies WHERE theatreId = ?;'
// Call dal:
const movies = await dal.execute(moviesSql ,[theatreId]);
// Return:
return movies;
}
更多推荐
为不存在的 id n 抛出新的 ResourceNotFoundError(id)
发布评论