Home > Net >  How can I combine two or more API requests into a single endpoint with node.js and express
How can I combine two or more API requests into a single endpoint with node.js and express

Time:01-26

I'm a relative beginner. I have two separate API calls that are now working (getPlayerAge and getPlayerRank) but I'm trying to combine the two into a single endpoint (getBothPlayerAgeAndRank) so both results are in one JSON. I'm working in Angular, Typescript, Express, Node.js. How do I go about it to get 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;

CodePudding user response:

First, create a middleware function in which you can check the validation for this api like the player is available or not

// you can write this middleware function in a separate middleware file as well

Thums rule of APIs is validation must be check before the controllers

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

then

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"});
    }
})

CodePudding user response:

You can use async/await syntax.

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 });
  }
}
  • Related