對於不存在的 id n 拋出 new ResourceNotFoundError(id)
P粉060528326
P粉060528326 2023-09-13 16:13:55
0
1
535

我正在建立一個小型全端系統(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 表中的「theatreId」列的外鍵。外鍵是電影表中的外鍵。

現在,用戶有可能會發送一些不存在的 theatreId,在這種情況下,我想拋出新的 ResourceNotFoundError。然而,也有可能 theatreId 確實存在,但只是沒有任何電影與該劇院匹配。在這種情況下,我不想拋出該錯誤。 我還希望它在效能方面表現良好,使用多個查詢檢查資料庫會減慢整個過程。

P粉060528326
P粉060528326

全部回覆(1)
P粉071743732

首先,在查詢 Movies 表之前,檢查 Theaters 表中是否存在具有所提供的 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;
}
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!