-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
100 lines (87 loc) · 2.46 KB
/
index.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
/* eslint-disable no-redeclare */
import { Platform } from 'react-native'
import sensitiveInfo, { SensitiveInfoEntry } from 'react-native-sensitive-info'
export default function (options = {} as sensitiveInfo.RNSensitiveInfoOptions) {
// react-native-sensitive-info returns different a different structure on iOS
// than it does on Android.
//
// iOS:
// [
// [
// { service: 'app', key: 'foo', value: 'bar' },
// { service: 'app', key: 'baz', value: 'quux' }
// ]
// ]
//
// Android:
// {
// foo: 'bar',
// baz: 'quux'
// }
//
// See https://github.com/mCodex/react-native-sensitive-info/issues/8
//
// `extractKeys` adapts for the different structure to return the list of
// keys.
const extractKeys = Platform.select({
android: Object.keys,
ios: (items: Array<Array<SensitiveInfoEntry>>) =>
items[0].map((item) => item.key)
})
function noop(_: null, result: string[]): void;
function noop(_: null, result: string | null): void;
function noop(error: unknown): void;
function noop () {
return null
}
return {
async getItem (key: string, callback = noop) {
try {
// getItem() returns `null` on Android and `undefined` on iOS;
// explicitly return `null` here as `undefined` causes an exception
// upstream.
let result: string | null = await sensitiveInfo.getItem(key, options)
if (typeof result === 'undefined') {
result = null
}
callback(null, result)
return result
} catch (error) {
callback(error)
throw error
}
},
async setItem (key: string, value: string, callback = noop) {
try {
await sensitiveInfo.setItem(key, value, options)
callback(null)
} catch (error) {
callback(error)
throw error
}
},
async removeItem (key: string, callback = noop) {
try {
await sensitiveInfo.deleteItem(key, options)
callback(null)
} catch (error) {
callback(error)
throw error
}
},
async getAllKeys (callback = noop) {
try {
const values = await sensitiveInfo.getAllItems(options)
if (typeof extractKeys === 'undefined') {
throw new Error('Platform not supported')
}
const result = extractKeys(values)
callback(null, result)
return result
} catch (error) {
callback(error)
throw error
}
}
}
}