为不存在的 id n 抛出新的 ResourceNotFoundError(id)

throw new ResourceNotFoundError(id) for id n that's not exist

提问人:Lior Nachmias 提问时间:3/26/2023 更新时间:3/26/2023 访问量:36

问:

我正在构建一个小型全栈系统(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 数据库中有两个表 - 剧院和电影。它们共享一个外键,该键引用 theatres 表中的“theatreId”列。外键是 movies 表中的外键。

现在,用户有可能发送一些不存在的theatreId,在这种情况下,我想抛出新的ResourceNotFoundError。然而,也有可能 theatreId 确实存在,但没有任何电影与这个剧院相匹配。在这种情况下,我不想抛出这个错误。 我还希望它在性能方面很好,用多个查询正弦检查数据库会减慢整个过程。

MySQL 节点 .js 打字稿 表达 错误处理

评论


答:

0赞 Taha Ergun 3/26/2023 #1

首先,在查询电影表之前,检查 theatres 表中是否存在 提供的影院。然后,您可以查询电影。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;
}

评论

0赞 Lior Nachmias 3/26/2023
好吧,所以我应该提一下,我确实考虑过......但是,两个查询是不是有点多?
0赞 Taha Ergun 3/27/2023
您正在对主键列执行单选查询,因此不会出现性能问题。
0赞 Lior Nachmias 6/11/2023
太好了,谢谢!