Last active
March 27, 2023 10:06
-
-
Save dcdunkan/17a263fcb147740758017d55dc80f18c to your computer and use it in GitHub Desktop.
Tiny https://deta.sh base client.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export class Base { | |
private rootUrl: string; | |
constructor(private projectKey: string, baseName: string) { | |
const projectId = projectKey.split("_")[0]; | |
this.rootUrl = `https://database.deta.sh/v1/${projectId}/${baseName}`; | |
} | |
async request(query: string, payload?: unknown) { | |
const [method, ...pathname] = query.split(" "); | |
const response = await fetch(`${this.rootUrl}${pathname.join(" ")}`, { | |
method, | |
...(payload ? { body: JSON.stringify(payload) } : {}), | |
headers: { | |
"X-API-Key": this.projectKey, | |
"Content-Type": "application/json", | |
}, | |
}); | |
return await response.json(); | |
} | |
get(key: string) { | |
return this.request(`GET /items/${key}`); | |
} | |
put(key: string, value: unknown) { | |
return this.request("PUT /items", { | |
items: [{ key: encodeURIComponent(key), value }], | |
}); | |
} | |
update(key: string, value: unknown) { | |
return this.request(`PATCH /items/${key}`, { set: { value } }); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment