-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathserver.js
52 lines (46 loc) · 1.47 KB
/
server.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
const http = require('node:http');
const { RateLimit } = require('async-sema');
const CACHE = new Map();
const API = 'https://api.scryfall.com';
// NOTE See https://scryfall.com/docs/api for more details on the rate limit
const limit = RateLimit(9);
const handler = async (request, response) => {
if (!CACHE.has(request.url)) {
await limit();
const promise = fetch(`${API}${request.url}`).then(async (it) => {
if (!it.ok) {
const error = await it.text();
console.error(`Error while requesting '${request.url}'`, error);
throw it.statusText;
}
return it.text();
});
CACHE.set(request.url, promise);
if (process.env.DEBUG) {
console.info(`Cached request for "${request.url}"`);
}
}
try {
const data = await CACHE.get(request.url);
response.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' });
response.write(data);
} catch (error) {
response.writeHead(500, { 'Content-Type': 'text/plain; charset=utf-8' });
// TODO Retrieve error details from API response
const message = `Error in response for "${request.url}" (${error})`;
response.write(message);
console.error(message);
} finally {
response.end();
if (process.env.DEBUG) {
console.count(`GET ${request.url}`);
}
}
};
const HOST = 'localhost';
const PORT = '3333';
http
.createServer(handler)
.listen(PORT, HOST, () =>
console.info(`Cache server is running on http://${HOST}:${PORT}`),
);