Last active
April 25, 2023 10:02
-
-
Save dcdunkan/36b6329408f3a2a91881fa29c8e08c30 to your computer and use it in GitHub Desktop.
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 interface GistOptions { | |
token: string; | |
gistId: string; | |
fileName: string; | |
} | |
const API_ROOT = "https://api.github.com"; | |
export class GistKV { | |
constructor(private options: GistOptions) {} | |
async #request(query: string, params?: unknown) { | |
const [method, path] = query.split(" ", 2); | |
const response = await fetch(`${API_ROOT}${path}`, { | |
method, | |
headers: { | |
"Accept": "application/vnd.github+json", | |
"Authorization": `Bearer ${this.options.token}`, | |
"X-GitHub-Api-Version": "2022-11-28", | |
}, | |
...(params ? { body: JSON.stringify(params) } : {}), | |
}); | |
if (!response.ok) { | |
console.error(response); | |
throw new Error("Request failed"); | |
} | |
return await response.json(); | |
} | |
async getAll<T = Record<string, unknown>>() { | |
const response = await this.#request(`GET /gists/${this.options.gistId}`); | |
return JSON.parse(response.files[this.options.fileName].content) as T; | |
} | |
async #writeFile(content: unknown) { | |
await this.#request(`POST /gists/${this.options.gistId}`, { | |
files: { | |
[this.options.fileName]: { | |
content: JSON.stringify(content, undefined, 2), | |
}, | |
}, | |
}); | |
} | |
async get<T>(keys: string[]) { | |
const store = await this.getAll(); | |
return keys.map((key) => store[key] as T); | |
} | |
async set(key: string, value: unknown) { | |
const store = await this.getAll(); | |
await this.#writeFile({ ...store, [key]: value }); | |
return true; | |
} | |
async delete(key: string) { | |
const { [key]: _, ...rest } = await this.getAll() | |
await this.#writeFile(rest); | |
return true; | |
} | |
async has(key: string) { | |
return (await this.getAll())[key] !== undefined; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment