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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
import moment from "npm:moment";
import { createClient } from "npm:@supabase/supabase-js";
class CacheService {
_supabase;
constructor() {
this._supabase = createClient(
Deno.env.get("SUPABASE_URL"),
Deno.env.get("SUPABASE_ANON_KEY")
);
}
async setCacheDataByKey(key: string, value: any, expireAt?: Date) {
const { data } = await this._supabase
.from("cache")
.select("*")
.eq("key", key);
if (!data) return;
const [cacheEntry] = data;
if (!cacheEntry) {
const { data: created, error } = await this._supabase
.from("cache")
.insert([
{
key,
...(expireAt ? { expireAt } : {}),
data: value,
},
])
.select();
if (!created) return;
return created[0];
}
const { data: updated, error } = await this._supabase
.from("cache")
.upsert([
{
id: data[0].id,
key,
...(expireAt ? { expireAt } : {}),
data: value,
},
])
.select();
console.log({ error });
if (!updated) return;
return updated[0];
}
async getCacheDataByKey(key: string) {
const { data } = await this._supabase
.from("cache")
.select("*")
.eq("key", key);
if (!data) {
return;
}
const [cacheEntry] = data;
if (cacheEntry && moment(cacheEntry.expireAt).unix() <= moment().unix()) {
await this._supabase.from("cache").delete().eq("id", cacheEntry.id);
return;
}
return cacheEntry?.data;
}
async clearExpired() {
const { data } = await this._supabase
.from("cache")
.select("*")
.lte("expireAt", moment().format());
if (!data) {
return;
}
// eslint-disable-next-line @typescript-eslint/prefer-for-of
for (let index = 0; index < data.length; index++) {
const cacheEntry = data[index];
await this._supabase.from("cache").delete().eq("id", cacheEntry.id);
}
}
}
export default CacheService;
Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
Comments
Nobody has commented on this val yet: be the first!
July 30, 2024