Skip to content

Instantly share code, notes, and snippets.

@dcdunkan
Last active March 27, 2023 10:06
Show Gist options
  • Save dcdunkan/17a263fcb147740758017d55dc80f18c to your computer and use it in GitHub Desktop.
Save dcdunkan/17a263fcb147740758017d55dc80f18c to your computer and use it in GitHub Desktop.
Tiny https://deta.sh base client.
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