-
Notifications
You must be signed in to change notification settings - Fork 25
/
kvn.ts
83 lines (72 loc) · 2.09 KB
/
kvn.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import { getClient } from '@tauri-apps/api/http';
import type { HttpOptions } from '@tauri-apps/api/http';
import type { Category } from './mime';
// sent to Redis
export interface Key {
name: string;
syncd: string;
expires?: string;
metadata?: string;
lastupdate?: string;
mimetype?: Category;
value?: string;
}
// come via REST API
export interface KeyInfo {
name: string;
expiration?: number;
metadata?: Dict<any>;
}
interface KeyList {
success: boolean;
messages: string[];
errors: string[];
result: KeyInfo[];
result_info: {
count: number;
cursor: string;
}
}
async function send<T>(url: string, options: Partial<HttpOptions> = {}) {
const client = await getClient();
const method = options.method || 'GET';
options.headers = {
...options.headers,
Origin: 'https://github.com'
};
return client.request<T>({ ...options, url, method });
}
export async function * list(
accountid: string,
namespaceid: string,
token: string,
): AsyncGenerator<{ done: boolean; keys: KeyInfo[] }> {
let cursor = '', headers = { Authorization: `Bearer ${token}` };
// @see https://api.cloudflare.com/#workers-kv-namespace-list-a-namespace-s-keys
let endpoint = new URL(`https://api.cloudflare.com/client/v4/accounts/${accountid}/storage/kv/namespaces/${namespaceid}/keys?limit=1000`);
while (true) {
if (cursor) endpoint.searchParams.set('cursor', cursor);
let { data } = await send<KeyList>(endpoint.href, { headers });
if (data.success) {
cursor = data.result_info.cursor;
yield {
done: cursor.length === 0,
keys: data.result,
};
} else {
break;
}
}
}
export async function retrieve(
accountid: string,
namespaceid: string,
token: string,
key: string,
): Promise<string> {
let keyname = encodeURIComponent(key);
let headers = { Authorization: `Bearer ${token}` };
// @see https://api.cloudflare.com/#workers-kv-namespace-list-a-namespace-s-keys
let endpoint = `https://api.cloudflare.com/client/v4/accounts/${accountid}/storage/kv/namespaces/${namespaceid}/values/${keyname}`;
return send<string>(endpoint, { headers, responseType: 3 }).then(r => r.data); // "number[]"
}