|
|
@ -1,10 +1,10 @@ |
|
|
|
import { sleep } from '../utils/eventLoop'; |
|
|
|
import { sleep } from '../utils/eventLoop'; |
|
|
|
import { StringifiableValue, createSerializer } from '../utils/serializer'; |
|
|
|
import { type StringifiableValue, createSerializer } from '../utils/serializer'; |
|
|
|
import { ClearableKeyValueStorage } from './types'; |
|
|
|
import type { ClearableKeyValueStorage } from './types'; |
|
|
|
|
|
|
|
|
|
|
|
export const createKeyValueStorage = <TValue extends StringifiableValue>( |
|
|
|
export const createKeyValueStorage = <TValue extends StringifiableValue>( |
|
|
|
latencyMs: number, |
|
|
|
latencyMs: number, |
|
|
|
) => { |
|
|
|
): ClearableKeyValueStorage<string, TValue> => { |
|
|
|
const withSimulatedLatency = async <TResult>( |
|
|
|
const withSimulatedLatency = async <TResult>( |
|
|
|
f: () => Promise<TResult>, |
|
|
|
f: () => Promise<TResult>, |
|
|
|
): Promise<TResult> => { |
|
|
|
): Promise<TResult> => { |
|
|
@ -17,7 +17,7 @@ export const createKeyValueStorage = <TValue extends StringifiableValue>( |
|
|
|
const serializer = createSerializer<TValue>(); |
|
|
|
const serializer = createSerializer<TValue>(); |
|
|
|
const storage = new Map<string, string>(); |
|
|
|
const storage = new Map<string, string>(); |
|
|
|
return { |
|
|
|
return { |
|
|
|
get: (key: string) => |
|
|
|
get: (key) => |
|
|
|
withSimulatedLatency(() => |
|
|
|
withSimulatedLatency(() => |
|
|
|
Promise.resolve( |
|
|
|
Promise.resolve( |
|
|
|
storage.has(key) |
|
|
|
storage.has(key) |
|
|
@ -32,7 +32,7 @@ export const createKeyValueStorage = <TValue extends StringifiableValue>( |
|
|
|
}, |
|
|
|
}, |
|
|
|
), |
|
|
|
), |
|
|
|
), |
|
|
|
), |
|
|
|
set: (key: string, value: TValue) => |
|
|
|
set: (key, value) => |
|
|
|
withSimulatedLatency(() => |
|
|
|
withSimulatedLatency(() => |
|
|
|
Promise.resolve( |
|
|
|
Promise.resolve( |
|
|
|
void storage.set(key, serializer.stringify(value)), |
|
|
|
void storage.set(key, serializer.stringify(value)), |
|
|
@ -41,5 +41,5 @@ export const createKeyValueStorage = <TValue extends StringifiableValue>( |
|
|
|
clear: () => |
|
|
|
clear: () => |
|
|
|
// eslint-disable-next-line @typescript-eslint/no-confusing-void-expression
|
|
|
|
// eslint-disable-next-line @typescript-eslint/no-confusing-void-expression
|
|
|
|
withSimulatedLatency(() => Promise.resolve(storage.clear())), |
|
|
|
withSimulatedLatency(() => Promise.resolve(storage.clear())), |
|
|
|
} as ClearableKeyValueStorage<string, TValue>; |
|
|
|
}; |
|
|
|
}; |
|
|
|
}; |
|
|
|