Skip to content
This repository was archived by the owner on Jul 2, 2022. It is now read-only.

Commit 6353abe

Browse files
committed
cache snapshot response
1 parent dfa2077 commit 6353abe

File tree

3 files changed

+23
-4
lines changed

3 files changed

+23
-4
lines changed

package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@
4040
"form-data": "^4.0.0",
4141
"is-uuid": "^1.0.2",
4242
"knex": "^0.95.4",
43+
"memory-cache": "^0.2.0",
4344
"moment-timezone": "^0.5.33",
4445
"node-telegram-bot-api": "^0.53.0",
4546
"pg": "^8.6.0",

src/api/handlers/snapshots.ts

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,27 @@
11
import getLatestSnapshot from "../../db/queries/getLatestSnapshot";
22
import type { Context } from "../context";
33
import type { Handler } from "./types";
4+
import cache from "memory-cache";
45

56
export const get: Handler = (ctx: Context) => async (req, res) => {
67
const { id } = req.params;
8+
let snapshot;
79

8-
const snapshot =
9-
id === "latest"
10-
? await getLatestSnapshot(ctx.db)
11-
: await ctx.db("snapshots").where({ id }).first();
10+
const cached = cache.get(id);
11+
12+
if (cached !== null) {
13+
snapshot = cached;
14+
} else {
15+
snapshot =
16+
id === "latest"
17+
? await getLatestSnapshot(ctx.db)
18+
: await ctx.db("snapshots").where({ id }).first();
19+
20+
cache.put(id, snapshot, 120000, () => {
21+
// purge after 2 minutes
22+
cache.clear();
23+
});
24+
}
1225

1326
res.json({
1427
data: snapshot,

yarn.lock

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2042,6 +2042,11 @@ [email protected]:
20422042
resolved "https://registry.yarnpkg.com/media-typer/-/media-typer-0.3.0.tgz#8710d7af0aa626f8fffa1ce00168545263255748"
20432043
integrity sha1-hxDXrwqmJvj/+hzgAWhUUmMlV0g=
20442044

2045+
memory-cache@^0.2.0:
2046+
version "0.2.0"
2047+
resolved "https://registry.yarnpkg.com/memory-cache/-/memory-cache-0.2.0.tgz#7890b01d52c00c8ebc9d533e1f8eb17e3034871a"
2048+
integrity sha1-eJCwHVLADI68nVM+H46xfjA0hxo=
2049+
20452050
20462051
version "1.0.1"
20472052
resolved "https://registry.yarnpkg.com/merge-descriptors/-/merge-descriptors-1.0.1.tgz#b00aaa556dd8b44568150ec9d1b953f3f90cbb61"

0 commit comments

Comments
 (0)