Created
August 29, 2022 12:20
-
-
Save huw/561ab79e281d40e1723ddb67be83da7e to your computer and use it in GitHub Desktop.
Typed Durable Object Storage
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
import type { Jsonify } from "type-fest"; | |
// Define new storage types here and below and the storage below will automatically use them. | |
// prettier-ignore | |
type TypedDurableObjectStorageValue<Key extends string> = Jsonify< | |
| Key extends "simple" ? boolean : never | |
| Key extends "complex" ? { age: number } | { name: string } : never | |
| Key extends `template:type:known` ? number : never | |
| Key extends `template:type:${string}` ? string | number : never | |
>; | |
type TypedDurableObjectStorageKey<Key extends string = string> = TypedDurableObjectStorageValue<Key> extends never | |
? Key | |
: never; | |
interface TypedDurableObjectStorageCommon { | |
get: <Key extends TypedDurableObjectStorageKey>( | |
key: Key, | |
options?: DurableObjectGetOptions | |
) => Promise<TypedDurableObjectStorageValue<Key> | undefined>; | |
list: <Prefix extends string = string>( | |
options?: Omit<DurableObjectListOptions, "prefix"> & { prefix?: Prefix } | |
) => Promise<Map<string, TypedDurableObjectStorageValue<`${Prefix}${string}`>>>; | |
put: (<Key extends TypedDurableObjectStorageKey>( | |
key: Key, | |
value: TypedDurableObjectStorageValue<Key>, | |
options?: DurableObjectPutOptions | |
) => Promise<void>) & | |
(<Key extends TypedDurableObjectStorageKey>( | |
entries: { [key in Key]: TypedDurableObjectStorageValue<Key> }, | |
options?: DurableObjectPutOptions | |
) => Promise<void>); | |
delete: (<Key extends keyof TypedDurableObjectStorageKey>( | |
key: Key, | |
options?: DurableObjectPutOptions | |
) => Promise<boolean>) & | |
((keys: TypedDurableObjectStorageKey[], options?: DurableObjectPutOptions) => Promise<number>); | |
getAlarm: DurableObjectStorage["getAlarm"]; | |
setAlarm: DurableObjectStorage["setAlarm"]; | |
deleteAlarm: DurableObjectStorage["deleteAlarm"]; | |
} | |
interface TypedDurableObjectTransaction extends TypedDurableObjectStorageCommon { | |
rollback: DurableObjectTransaction["rollback"]; | |
} | |
interface TypedDurableObjectStorage extends TypedDurableObjectStorageCommon { | |
transaction: <T>(closure: (txn: TypedDurableObjectTransaction) => Promise<T>) => Promise<T>; | |
deleteAll: DurableObjectStorage["deleteAll"]; | |
} | |
export default TypedDurableObjectStorage; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
get(keys:)
is unimplemented—I’ll update this if someone figures it out. I didn’t use it in my codebase so wasn’t too bothered.