Skip to content

Instantly share code, notes, and snippets.

@Akiyamka
Last active March 12, 2025 12:12
Show Gist options
  • Save Akiyamka/4a3c4fcd75c4d78bcb1f145c4b903d0f to your computer and use it in GitHub Desktop.
Save Akiyamka/4a3c4fcd75c4d78bcb1f145c4b903d0f to your computer and use it in GitHub Desktop.
Minimalistic client for keyval.org
const key = await KeyVal.save('test');
const val = await KeyVal.get(key);
console.assert(val === 'test', 'Should return saved value');
await KeyVal.set('myKey', 'myVal');
const myVal = await KeyVal.get('myKey');
console.assert(myVal === 'myVal', 'Should return value for myKey');
const KeyVal = (({ ns, encode = btoa, decode = btoa }) => {
const URL = `https://api.keyval.org`;
const withNs = (key) => (ns ? `${ns}--${key}` : key);
return {
save: (val) =>
fetch(`${URL}/set/-/${val}`, { method: 'POST' })
.then((r) => r.json())
.then((data) => ({ __rawKey: data.key })),
set: (key, val) =>
fetch(`${URL}/set/${withNs(key)}/${encode(val)}`, { method: 'POST' })
.then((r) => r.json())
.then((data) => {
switch (data.status) {
case '-KEY-ALREADY-EXISTS-':
throw Error('Key already exists');
case '-KEY-DOESNT-EXISTS-':
throw Error('Key doesnt exists');
case 'SUCCESS':
return true;
default:
throw Error('Unknown Error');
}
}),
get: (key) =>
fetch(`${URL}/get/${typeof key === 'string' ? withNs(key) : key.__rawKey}`)
.then((r) => r.json())
.then((data) => decode(data.val)),
};
})({ ns: Date.now() });
type KeyValClientOptions<T> = {
ns?: string;
encode?: (payload: T) => string;
decode?: (payload: string) => T;
}
// @ts-ignore
const KeyVal = (<T>({ ns, encode = btoa, decode = btoa }: KeyValClientOptions<T>) => {
const URL = `https://api.keyval.org`;
const withNs = (key: string) => (ns ? `${ns}--${key}` : key);
return {
save: (val: T) =>
fetch(`${URL}/set/-/${val}`, { method: 'POST' })
.then((r) => r.json())
.then((data) => ({ __rawKey: data.key })),
set: (key: string, val: T) =>
fetch(`${URL}/set/${withNs(key)}/${encode(val)}`, { method: 'POST' })
.then((r) => r.json())
.then((data) => {
switch (data.status) {
case '-KEY-ALREADY-EXISTS-':
throw Error('Key already exists');
case '-KEY-DOESNT-EXISTS-':
throw Error('Key doesnt exists');
case 'SUCCESS':
return true;
default:
throw Error('Unknown Error');
}
}),
get: (key: string | { __rawKey: string }) =>
fetch(`${URL}/get/${typeof key === 'string' ? withNs(key) : key.__rawKey}`)
.then((r) => r.json())
.then((data) => decode(data.val)),
};
})({ ns: String(Date.now()) });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment