-
-
Save nathanclevenger/29ec5d5949a37ff6bd3416d38309d0e5 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; |
Try not to have a good time... This is supposed to be educational.
― Charles Schulz
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@repo-do are you getting notified?