-
Notifications
You must be signed in to change notification settings - Fork 23
/
adapter.ts
60 lines (52 loc) · 1.39 KB
/
adapter.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
import { StorageAdapter } from './deps.deno.ts';
export interface BaseConfig {
baseName: string;
projectKey: string;
}
type Method = 'GET' | 'PUT' | 'DELETE';
export class DetaAdapter<T> implements StorageAdapter<T> {
private readonly project: BaseConfig;
private readonly rootUrl: string;
constructor(project: BaseConfig) {
this.project = project;
const projectId = project.projectKey.split('_')[0];
this.rootUrl =
`https://database.deta.sh/v1/${projectId}/${project.baseName}/items`;
}
private async request(
method: Method,
key: string,
body?: { items: T[] },
) {
const apiUrl = `${this.rootUrl}${key}`;
return await fetch(apiUrl, {
method: method,
body: JSON.stringify(body),
headers: new Headers({
'X-API-Key': this.project.projectKey,
'Content-Type': 'application/json',
}),
});
}
async read(key: string) {
key = `/${encodeURIComponent(key)}`;
const res = await this.request('GET', key);
if (!res.ok) return undefined;
return await res.json();
}
async write(
key: string,
value: T,
) {
return await (await this.request('PUT', '', {
items: [{
key: encodeURIComponent(key),
...value,
}],
})).json();
}
async delete(key: string) {
key = `/${encodeURIComponent(key)}`;
return await (await this.request('DELETE', key)).json();
}
}