This repository has been archived by the owner on Sep 19, 2023. It is now read-only.
/
wrapStorage.ts
67 lines (57 loc) · 1.68 KB
/
wrapStorage.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import { Effect } from '@typed/effects'
import { Future } from '@typed/future'
import { noOp } from '@typed/lambda'
import { Maybe } from '@typed/maybe'
import { AsyncStorage } from './AsyncStorage'
// Lift synchronous storage into AsyncStorage
export function wrapStorage(storage: Storage): AsyncStorage<string> {
return {
getKeys: () =>
Effect.fromEnv(
tryCatch(() => {
const items: string[] = []
for (let i = 0; i < storage.length; ++i) {
const key = storage.key(i)
if (key !== null) {
items.push(key)
}
}
return items
}),
),
getItems: () =>
Effect.fromEnv(
tryCatch((): readonly string[] => {
const items: string[] = []
for (let i = 0; i < storage.length; ++i) {
const key = storage.key(i)
if (key !== null) {
items.push(storage.getItem(key)!)
}
}
return items
}),
),
getItem: (key) => Effect.fromEnv(tryCatch(() => Maybe.of(storage.getItem(key)))),
setItem: (key, value) => Effect.fromEnv(tryCatch(() => (storage.setItem(key, value), value))),
removeItem: (key) =>
Effect.fromEnv(
tryCatch(() => {
const item = Maybe.of(storage.getItem(key))
storage.removeItem(key)
return item
}),
),
clear: () => Effect.fromEnv(tryCatch(() => (storage.clear(), true))),
dispose: noOp,
}
}
function tryCatch<A>(fn: () => A): Future<unknown, Error, A> {
return Future.create((reject, resolve) => {
try {
return resolve(fn())
} catch (error) {
return reject(error)
}
})
}