-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathcache.ts
54 lines (50 loc) · 1.42 KB
/
cache.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
import types from "./cache.extern";
import {
CacheGet,
CacheClient,
Configurations,
CredentialProvider,
CacheSet,
} from "@gomomento/sdk";
let cacheClients: Record<string, CacheClient> = {};
async function createCacheClient(token: string) {
if (!cacheClients[token]) {
cacheClients[token] = await CacheClient.create({
configuration: Configurations.Lambda.latest(),
credentialProvider: CredentialProvider.fromString(token),
defaultTtlSeconds: 60, // won't be used
});
}
}
export const _get: types["_get"] = async (token, cacheName, key) => {
await createCacheClient(token);
const getResponse = await cacheClients[token].get(cacheName, key);
if (getResponse instanceof CacheGet.Hit) {
return getResponse.valueString();
} else if (getResponse instanceof CacheGet.Miss) {
return undefined;
} else if (getResponse instanceof CacheGet.Error) {
throw getResponse.innerException();
} else {
throw new Error("Unexpected response type");
}
};
export const _set: types["_set"] = async (
token,
cacheName,
key,
value,
ttl
) => {
await createCacheClient(token);
const setResponse = await cacheClients[token].set(cacheName, key, value, {
ttl,
});
if (setResponse instanceof CacheSet.Success) {
return;
} else if (setResponse instanceof CacheSet.Error) {
throw setResponse.innerException();
} else {
throw new Error("Unexpected response type");
}
};