-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmockProxy.js
62 lines (55 loc) · 1.75 KB
/
mockProxy.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
const { readFile } = require("fs");
const { join } = require("path");
const { createServer, request: httpRequest } = require("http");
const { request: httpsRequest } = require("https");
const { parse: parseUrl } = require("url");
const basePath = join(__dirname, "mocks/");
const baseUrl = (process.env.API_BASE_URL || "https://api.nature.global/").replace(/\/$/, "");
console.log("listen at http://localhost:1234");
createServer((req, res) => {
const defaultHeaders = {
"access-control-allow-origin": req.headers.origin,
};
if (req.method === "OPTIONS") {
res.writeHead(200, { ...defaultHeaders, "access-control-allow-headers": req.headers["access-control-request-headers"] });
res.end();
return;
}
const proxy = () => {
const url = `${baseUrl}${req.url}`;
console.log(req.method, req.url, "->", "proxy:", url);
const parsedUrl = parseUrl(url);
const options = {
...parsedUrl,
headers: {
...req.headers,
host: parsedUrl.host,
},
method: req.method,
agent: false,
};
const reqFunc = options.protocol === "https:" ? httpsRequest : httpRequest;
req.pipe(
reqFunc(options, (resp) => {
resp.pause();
res.writeHead(200, { ...resp.headers, ...defaultHeaders, "Content-Type": "application/json" });
resp.pipe(res);
resp.resume();
}),
);
};
if (req.method === "GET") {
readFile(join(basePath, req.url), (err, data) => {
if (err) {
proxy();
} else {
console.log(req.method, req.url, "->", "path:", join(basePath, req.url));
res.writeHead(200, { ...defaultHeaders, "Content-Type": "application/json" });
res.write(data);
res.end();
}
});
return;
}
proxy();
}).listen(1234);