-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
Copy pathAsyncStorageAdapter.ts
270 lines (218 loc) · 6.72 KB
/
AsyncStorageAdapter.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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
import {
ModelInstanceMetadata,
ModelPredicate,
OpType,
PaginationInput,
PersistentModel,
PersistentModelConstructor,
PredicatesGroup,
QueryOne,
} from '../../types';
import {
DEFAULT_PRIMARY_KEY_VALUE_SEPARATOR,
getIndexKeys,
getStorename,
inMemoryPagination,
keysEqual,
traverseModel,
validatePredicate,
} from '../../util';
import AsyncStorageDatabase from './AsyncStorageDatabase';
import { StorageAdapterBase } from './StorageAdapterBase';
export class AsyncStorageAdapter extends StorageAdapterBase {
protected db!: AsyncStorageDatabase;
protected async preSetUpChecks() {
// no-ops for AsyncStorageAdapter
}
protected async preOpCheck() {
// no-ops for AsyncStorageAdapter
}
/**
* Open AsyncStorage database
* Create new DB if one doesn't exist
*
* Called by `StorageAdapterBase.setUp()`
*
* @returns AsyncStorageDatabase instance
*/
protected async initDb(): Promise<AsyncStorageDatabase> {
const db = new AsyncStorageDatabase();
await db.init();
return db;
}
async clear(): Promise<void> {
await this.db.clear();
this.db = undefined!;
this.initPromise = undefined!;
}
async batchSave<T extends PersistentModel>(
modelConstructor: PersistentModelConstructor<any>,
items: ModelInstanceMetadata[],
): Promise<[T, OpType][]> {
if (items.length === 0) {
return [];
}
const modelName = modelConstructor.name;
const namespaceName = this.namespaceResolver(modelConstructor);
const storeName = getStorename(namespaceName, modelName);
const keys = getIndexKeys(this.schema.namespaces[namespaceName], modelName);
const batch: ModelInstanceMetadata[] = [];
for (const item of items) {
const model = this.modelInstanceCreator(modelConstructor, item);
const connectedModels = traverseModel(
modelName,
model,
this.schema.namespaces[namespaceName],
this.modelInstanceCreator,
this.getModelConstructorByModelName,
);
const keyValuesPath = this.getIndexKeyValuesPath(model);
const { instance } = connectedModels.find(
({ instance: connectedModelInstance }) => {
const instanceKeyValuesPath = this.getIndexKeyValuesPath(
connectedModelInstance,
);
return keysEqual([instanceKeyValuesPath], [keyValuesPath]);
},
)!;
batch.push(instance);
}
return this.db.batchSave(storeName, batch, keys);
}
protected async _get<T>(storeName: string, keyArr: string[]): Promise<T> {
const itemKeyValuesPath: string = keyArr.join(
DEFAULT_PRIMARY_KEY_VALUE_SEPARATOR,
);
return (await this.db.get(itemKeyValuesPath, storeName)) as T;
}
async save<T extends PersistentModel>(
model: T,
condition?: ModelPredicate<T>,
): Promise<[T, OpType.INSERT | OpType.UPDATE][]> {
const { storeName, connectionStoreNames, modelKeyValues } =
this.saveMetadata(model);
const fromDB = await this._get(storeName, modelKeyValues);
this.validateSaveCondition(condition, fromDB);
const result: [T, OpType.INSERT | OpType.UPDATE][] = [];
for await (const resItem of connectionStoreNames) {
const { storeName: storeNameForRestItem, item, instance, keys } = resItem;
const itemKeyValues: string[] = keys.map(key => item[key]);
const fromDBForRestItem = (await this._get(
storeNameForRestItem,
itemKeyValues,
)) as T;
const opType: OpType = fromDBForRestItem ? OpType.UPDATE : OpType.INSERT;
if (
keysEqual(itemKeyValues, modelKeyValues) ||
opType === OpType.INSERT
) {
await this.db.save(
item,
storeNameForRestItem,
keys,
itemKeyValues.join(DEFAULT_PRIMARY_KEY_VALUE_SEPARATOR),
);
result.push([instance, opType]);
}
}
return result;
}
async query<T extends PersistentModel>(
modelConstructor: PersistentModelConstructor<T>,
predicate?: ModelPredicate<T>,
pagination?: PaginationInput<T>,
): Promise<T[]> {
const {
storeName,
namespaceName,
queryByKey,
predicates,
hasSort,
hasPagination,
} = this.queryMetadata(modelConstructor, predicate, pagination);
const records: T[] = (await (async () => {
if (queryByKey) {
const keyValues = queryByKey.join(DEFAULT_PRIMARY_KEY_VALUE_SEPARATOR);
const record = await this.getByKey(storeName, keyValues);
return record ? [record] : [];
}
if (predicates) {
const filtered = await this.filterOnPredicate(storeName, predicates);
return this.inMemoryPagination(filtered, pagination);
}
if (hasSort || hasPagination) {
const all = await this.getAll(storeName);
return this.inMemoryPagination(all, pagination);
}
return this.getAll(storeName);
})()) as T[];
return this.load(namespaceName, modelConstructor.name, records);
}
private async getByKey<T extends PersistentModel>(
storeName: string,
keyValuePath: string,
): Promise<T> {
return (await this.db.get(keyValuePath, storeName)) as T;
}
private async getAll<T extends PersistentModel>(
storeName: string,
): Promise<T[]> {
return this.db.getAll(storeName);
}
private async filterOnPredicate<T extends PersistentModel>(
storeName: string,
predicates: PredicatesGroup<T>,
) {
const { predicates: predicateObjs, type } = predicates;
const all = (await this.getAll(storeName)) as T[];
const filtered = predicateObjs
? all.filter(m => validatePredicate(m, type, predicateObjs))
: all;
return filtered;
}
private inMemoryPagination<T extends PersistentModel>(
records: T[],
pagination?: PaginationInput<T>,
): T[] {
return inMemoryPagination(records, pagination);
}
async queryOne<T extends PersistentModel>(
modelConstructor: PersistentModelConstructor<T>,
firstOrLast: QueryOne = QueryOne.FIRST,
): Promise<T | undefined> {
const storeName = this.getStorenameForModel(modelConstructor);
const result = (await this.db.getOne(firstOrLast, storeName)) as T;
return result && this.modelInstanceCreator(modelConstructor, result);
}
protected async deleteItem<T extends PersistentModel>(
deleteQueue?: { storeName: string; items: T[] | IDBValidKey[] }[],
) {
for await (const deleteItem of deleteQueue!) {
const { storeName, items } = deleteItem;
for await (const item of items) {
if (item) {
if (typeof item === 'object') {
const keyValuesPath: string = this.getIndexKeyValuesPath(item as T);
await this.db.delete(keyValuesPath, storeName);
}
}
}
}
}
// #region platform-specific helper methods
/**
* Retrieves concatenated primary key values from a model
*
* @param model
* @returns
*/
private getIndexKeyValuesPath<T extends PersistentModel>(model: T): string {
return this.getIndexKeyValuesFromModel(model).join(
DEFAULT_PRIMARY_KEY_VALUE_SEPARATOR,
);
}
// #endregion
}
export default new AsyncStorageAdapter();