-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.ts
64 lines (55 loc) · 1.62 KB
/
server.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
52
53
54
55
56
57
58
59
60
61
62
63
64
import { Application, Router } from "https://deno.land/x/oak/mod.ts";
import { oakCors } from "https://deno.land/x/cors/mod.ts";
import { getPost } from "./nostr.ts";
import LRU from "https://deno.land/x/[email protected]/mod.ts";
const lru = new LRU<string>(100);
const app = new Application();
const router = new Router();
router.get("/", async (ctx) => {
const requestUrl = new URL(ctx.request.url);
const pubkey = requestUrl.searchParams.get("pubkey");
const id = requestUrl.searchParams.get("id");
if (!pubkey || !id) {
ctx.response.body = "{}";
return;
}
const url = pubkey + ":" + id;
const cache = lru.get(url);
if (cache) {
// try check if event is outdated in async
// todo find a more efficiency way
try {
getPost(pubkey, id).then(post => {
if(post){
const cacheEvent = JSON.parse(cache);
if(post.created_at > cacheEvent.created_at){
console.debug('article is outdated! update cache!');
lru.set(url, JSON.stringify(post));
}
}
})
} catch (error) {
//ignore error
}
console.log("return cache");
ctx.response.body = JSON.parse(cache);
} else {
try {
const post = await getPost(pubkey, id);
if(post){
const json = JSON.stringify(post);
lru.set(url, json);
ctx.response.body = json;
}
} catch (error) {
console.error(error);
}
return;
}
});
app.use(oakCors()); // Add CORS middleware
app.use(router.routes());
app.use(router.allowedMethods());
const port = 8000;
console.log(`Listening on http://localhost:${port}`);
await app.listen({ port });