Home > OS >  Api route that sends local server file upon failure
Api route that sends local server file upon failure

Time:06-15

I'm trying to setup a route that does a node-fetch from a third party API to send back info to the client.

I was wondering if its possible to set it up so that if the third party API fails, the server defaults to a localized file it sends to the client?

routes.get("/data", async (req: Request, res: Response, next: NextFunction) => {
  try {
    res.header("Cache-Control", "no-store");
    res.header("Content-Type", "application/json");

    const data = await fetch("https://api.blahblah.com/files");

    const jsndata = await data.json();

    const formatData = jsndata.filter((item: { fork: boolean }) => {
      return item.fork === false;
    });

    res.send(formatData);
  } catch (err: unknown) {
    if (err === 400) {
      res.send(JSON.stringify(localData));
    } else {
      next(err);
    }
  }
});

CodePudding user response:

Check the Response.ok property and if it is false, respond with your local file.

For example

routes.get("/data", async (req, res, next) => {
  try {
    res.header("Cache-Control", "no-store");

    const response = await fetch("https://api.blahblah.com/files");
    if (!response.ok) {
      return res.json(localData); // respond with local data
    }

    const jsndata = await response.json();

    const formatData = jsndata.filter((item: { fork: boolean }) => {
      return item.fork === false;
    });

    res.json(formatData);
  } catch (err: unknown) {
    next(err);
  }
});
  • Related