0

I have proxy config like that:

proxy: {
  "/api/smth": {
    target: "http://api.example.com/",
    secure: false,
    changeOrigin: true,
  },
}

Now I want to redirect api calls /api/*/meta to local files %PROJ_ROOT%/meta/*.json.

How can I configure that?

Qwertiy
  • 19,681
  • 15
  • 61
  • 128

1 Answers1

0

Simple version:

proxy: {
  "/api/*/meta": {
    selfHandleResponse: true,
    bypass(req, resp) {
      const id = req.url.match(/api\/([-\w]+)\/meta/)[1];
      resp.header("Content-Type", "application/json");
      fs.createReadStream(`./meta/${id}.json`).pipe(resp);
    },
  },
  "/api/smth": {
    target: "http://api.example.com/",
    secure: false,
    changeOrigin: true,
  },
}

Version with status code:

proxy: {
  "/api/*/meta": {
    selfHandleResponse: true,
    bypass(req, resp) {
      const id = req.url.match(/api\/([-\w]+)\/meta/)[1];
      const jsonStream = fs.createReadStream(`./meta/${id}.json`);

      jsonStream.on("open", () => {
        resp.header("Content-Type", "application/json");
        jsonStream.pipe(resp);
      });

      jsonStream.on("error", err => {
        resp.status(err.code === 'ENOENT' ? 404 : 500);
        resp.send(err);
      });
    },
  },
  "/api/smth": {
    target: "http://api.example.com/",
    secure: false,
    changeOrigin: true,
  },
}
Qwertiy
  • 19,681
  • 15
  • 61
  • 128