如何使用node.js和express将两个或多个API请求组合到单个端点中

gev0vcfq  于 2023-01-30  发布在  Node.js
关注(0)|答案(2)|浏览(180)

我是一个相对的初学者。我有两个独立的API调用,现在正在工作(getPlayerAge和getPlayerRank),但我试图将这两个组合成一个端点(getBothPlayerAgeAndRank),这样两个结果都在一个JSON中。我正在使用Angular,Typescript,Express,Node.js。我如何着手获得return [getPlayerAge,getPlayerRank]?

import * as Promise from 'bluebird';
import { Request, Response, Router } from 'express';

import * as https from 'https';
import * as http from 'http';

import * as apicache from 'apicache';

import { PlayerModule } from '../modules';

const router = Router();
const cache = apicache.middleware;

router.get('/getPlayerAge',  (req: Request, res: Response, next: () => void) => {
    let playerName: string;
    if (!req.query.player) {
        res.json([]);
        next();
    } else {
        playerName = req.query.player;
        PlayerModule.getPlayerAge(playerName)
            .then((results) => {
                if (results.length > 0) {
                    res.json(results[0]);
                } else {
                    res.sendStatus(404);
                }
            })
            .catch((reason) => {
                //console.error(reason);
                res.sendStatus(500);
            })
            .finally(next);
    }
});

router.get('/getPlayerRank', (req: Request, res: Response, next: () => void) => {
    let playerName: string;
    if (!req.query.player) {
        res.json([]);
        next();
    } else {
        playerName = req.query.player;
        PlayerModule.getPlayerRank(playerName)
            .then((results) => {
                if (results.length > 0) {
                    res.json(results[0]);
                } else {
                    res.sendStatus(404);
                }
            })
            .catch((reason) => {
                //console.error(reason);
                res.sendStatus(500);
            })
            .finally(next);
    }
});

export const PlayerRoutes = router;
trnvg8h3

trnvg8h31#

首先,创建一个中间件函数,您可以在其中检查此API的验证,例如播放器是否可用
//您也可以在单独的中间件文件中编写此中间件函数
API的Thums规则是验证必须在控制器之前检查

checkValidation(req, res, next) {
    const { player } = req.query;
    if (!player) {
      res.status(404).json({message: "Player missing"});
      return;
    } else {
        next();
    }
}

那么

router.get('/getPlayerAge', checkValidation, async (req, res) => {
    const player = {req.query};
    const ageDetails = await PlayerModule.getPlayerAge(player);
    if(ageDetails && ageDetails.length > 0) {
        const rankDetails = await PlayerModule.getPlayerRank(player);
        res.status(200).json({message: "success", ageDetails, });
    } else {
        res.status(404).json({message: "No data found"});
    }
})
db2dz4w8

db2dz4w82#

可以使用async/await语法。

router.get('/users', async (req: Request, res: Response) => { // async
  try {
    const { player } = req.query;
    if (!player) {
      res.sendStatus(404);
      return;
    }

    const ages = await PlayerModule.getPlayerAge(player); // await. Why ages???
    const ranks = await PlayerModule.getPlayerRank(player);

    if (ages.length === 0 || ranks.length === 0) {
      res.sendStatus(404);
      return;
    }

    res.send({ age: ages[0], rank: ranks[0] }); // response { age: 18, rank: 1} ???
  } catch (error) {
    console.log(error);
    res.status(500).json({ message: error.message });
  }
}

相关问题