Open History to see the last commit
1/**
2 * Read, save, and remove one value by string id.
3 * `get` returns the value, or `null` when the id is absent.
4 */
5interface KeyedStore<Value> {
6 /** Returns the value for `id`, or `null` when `id` is absent. */
7 get: (id: string) => Promise<Value | null>
8 /** Saves `value` for `id`. A later save for the same `id` replaces it. */
9 set: (id: string, value: Value) => Promise<void>
10 /** Removes `id`. An absent `id` stays absent. */
11 delete: (id: string) => Promise<void>
12}
13
14/**
15 * Keeps one JSON value for each task id.
16 * `inMemoryTaskStore` keeps those values in one process.
17 * When the server runs on more than one instance, pass a store that you own.
18 */
19export type TaskStore<Value = unknown> = KeyedStore<Value>
20
21// Map.get adds undefined. The wrapper keeps a saved value, including null.
22function createInMemoryStore<Value = unknown>() {
23 const values = new Map<string, { value: Value }>()
24
25 return {
26 async get(id: string) {
27 const entry = values.get(id)
28 if (entry === undefined) return null
29 return entry.value
30 },
31 async set(id: string, value: Value) {
32 values.set(id, { value })
33 },
34 async delete(id: string) {
35 values.delete(id)
36 },
37 }
38}
39
40/**
41 * Creates a {@link TaskStore} that keeps values in memory.
42 * Each call has its own map. The map lives in this process only.
43 * A saved task stays in the map until `delete`, or until the process exits.
44 * A long-lived server passes its own store.
45 *
46 * ```ts
47 * const tasks = inMemoryTaskStore()
48 * await tasks.set('task-1', { status: 'working' })
49 * await tasks.get('task-1')
50 * ```
51 */
52export function inMemoryTaskStore() {
53 return createInMemoryStore()
54}