-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
51 lines (39 loc) · 1.17 KB
/
index.ts
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
import { App } from "@tinyhttp/app";
import { cors } from "@tinyhttp/cors";
import { query } from "./api.js";
import { redis } from "./redis.js";
import { deriveValue } from "./value.js";
const TTL = 60 * 60 * 24;
const app = new App();
app
.use(cors())
.get("/api/:itemid", async (req, res) => {
const itemIds = req.params["itemid"]
.split(",")
.map(Number)
.filter(Number.isInteger);
const results = [];
for (const itemId of itemIds) {
const cacheKey = `value:${itemId}`;
if (!(await redis.exists(cacheKey))) {
const date = new Date();
const sales = await query(itemId);
const value = deriveValue(sales);
const volume = sales.reduce((acc, s) => acc + s.quantity, 0);
await redis.set(
cacheKey,
JSON.stringify({ value, volume, date, itemId }),
{
EX: TTL,
},
);
}
const result = (await redis.get(cacheKey)) as string;
results.push(JSON.parse(result));
}
return res.send(itemIds.length === 1 ? results[0] : results);
})
.get("/", async (_, res) => {
return res.send("🏷️🔫");
})
.listen(3000);