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

编程入门 行业动态 更新时间:2024-10-07 04:25:17

为<a href=https://www.elefans.com/category/jswz/34/1770716.html style=不存在的 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)

本文发布于:2024-05-13 16:35:42,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1760113.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:不存在   抛出   id   ResourceNotFoundError

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!