forked from lucacasonato/deno_httpcache
-
Notifications
You must be signed in to change notification settings - Fork 0
/
redis.ts
36 lines (35 loc) · 1.02 KB
/
redis.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
import { connect, parseURL } from "https://deno.land/x/[email protected]/mod.ts";
import {
decode,
encode,
} from "https://deno.land/[email protected]/encoding/base64.ts";
import { Cache } from "./mod.ts";
export { Cache };
export async function redisCache(
databaseUrl: string,
prefix = "",
): Promise<Cache> {
const conn = await connect(parseURL(databaseUrl));
return new Cache({
async get(url) {
const bulk = await conn.get(prefix + url);
if (!bulk) return undefined;
const [policyBase64, bodyBase64] = bulk.split("\n");
const policy = JSON.parse(atob(policyBase64));
const body = decode(bodyBase64);
return { policy, body };
},
async set(url, resp) {
const policyBase64 = btoa(JSON.stringify(resp.policy));
const bodyBase64 = encode(resp.body);
// TODO(lucacasonato): add ttl
await conn.set(prefix + url, `${policyBase64}\n${bodyBase64}`);
},
async delete(url) {
await conn.del(prefix + url);
},
close() {
conn.close();
},
});
}