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;
}
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;