@converse/skeletor 0.0.7 → 0.0.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/storage.js~ DELETED
@@ -1,269 +0,0 @@
1
- /**
2
- * IndexedDB, localStorage and sessionStorage adapter
3
- */
4
- import * as memoryDriver from 'localforage-driver-memory';
5
- import cloneDeep from 'lodash-es/cloneDeep.js';
6
- import isString from 'lodash-es/isString.js';
7
- import localForage from "localforage/src/localforage";
8
- import mergebounce from 'mergebounce';
9
- import sessionStorageWrapper from "./drivers/sessionStorage.js";
10
- import { extendPrototype as extendPrototypeWithSetItems } from 'localforage-setitems';
11
- import { extendPrototype as extendPrototypeWithGetItems } from 'localforage-getitems';
12
-
13
- const IN_MEMORY = memoryDriver._driver
14
- localForage.defineDriver(memoryDriver);
15
- extendPrototypeWithSetItems(localForage);
16
- extendPrototypeWithGetItems(localForage);
17
-
18
- function S4() {
19
- // Generate four random hex digits.
20
- return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
21
- }
22
-
23
- function guid() {
24
- // Generate a pseudo-GUID by concatenating random hexadecimal.
25
- return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
26
- }
27
-
28
-
29
- class Storage {
30
-
31
- constructor (id, type, batchedWrites=false) {
32
- if (type === 'local' && !window.localStorage ) {
33
- throw new Error("Skeletor.storage: Environment does not support localStorage.");
34
- } else if (type === 'session' && !window.sessionStorage ) {
35
- throw new Error("Skeletor.storage: Environment does not support sessionStorage.");
36
- }
37
- if (isString(type)) {
38
- this.storeInitialized = this.initStore(type, batchedWrites);
39
- } else {
40
- this.store = type;
41
- if (batchedWrites) {
42
- this.store.debouncedSetItems = mergebounce(
43
- items => this.store.setItems(items),
44
- 50,
45
- {'promise': true}
46
- );
47
- }
48
- this.storeInitialized = Promise.resolve();
49
- }
50
- this.name = id;
51
- }
52
-
53
- async initStore (type, batchedWrites) {
54
- if (type === 'session') {
55
- localForage.setDriver(sessionStorageWrapper._driver);
56
- } else if (type === 'local') {
57
- await localForage.config({'driver': localForage.LOCALSTORAGE});
58
- } else if (type === 'in_memory') {
59
- localForage.config({'driver': IN_MEMORY});
60
- } else if (type !== 'indexed') {
61
- throw new Error("Skeletor.storage: No storage type was specified");
62
- }
63
- this.store = localForage;
64
- if (batchedWrites) {
65
- this.store.debouncedSetItems = mergebounce(
66
- items => this.store.setItems(items),
67
- 50,
68
- {'promise': true}
69
- );
70
- }
71
- }
72
-
73
- flush () {
74
- return this.store.debouncedSetItems?.flush();
75
- }
76
-
77
- async clear () {
78
- await this.store.removeItem(this.name).catch(e => console.error(e));
79
- const re = new RegExp(`^${this.name}-`);
80
- const keys = await this.store.keys();
81
- const removed_keys = keys.filter(k => re.test(k));
82
- await Promise.all(removed_keys.map(k => this.store.removeItem(k).catch(e => console.error(e))));
83
- }
84
-
85
- sync () {
86
- const that = this;
87
-
88
- async function localSync (method, model, options) {
89
- let resp, errorMessage, promise, new_attributes;
90
-
91
- // We get the collection (and if necessary the model attribute.
92
- // Waiting for storeInitialized will cause another iteration of
93
- // the event loop, after which the collection reference will
94
- // be removed from the model.
95
- const collection = model.collection;
96
- if (['patch', 'update'].includes(method)) {
97
- new_attributes = cloneDeep(model.attributes);
98
- }
99
- await that.storeInitialized;
100
- try {
101
- const original_attributes = model.attributes;
102
- switch (method) {
103
- case "read":
104
- if (model.id !== undefined) {
105
- resp = await that.find(model);
106
- } else {
107
- resp = await that.findAll();
108
- }
109
- break;
110
- case "create":
111
- resp = await that.create(model, options);
112
- break;
113
- case 'patch':
114
- case "update":
115
- if (options.wait) {
116
- // When `wait` is set to true, Skeletor waits until
117
- // confirmation of storage before setting the values on
118
- // the model.
119
- // However, the new attributes needs to be sent, so it
120
- // sets them manually on the model and then removes
121
- // them after calling `sync`.
122
- // Because our `sync` method is asynchronous and we
123
- // wait for `storeInitialized`, the attributes are
124
- // already restored once we get here, so we need to do
125
- // the attributes dance again.
126
- model.attributes = new_attributes;
127
- }
128
- promise = that.update(model, options);
129
- if (options.wait) {
130
- model.attributes = original_attributes;
131
- }
132
- resp = await promise;
133
- break;
134
- case "delete":
135
- resp = await that.destroy(model, collection);
136
- break;
137
- }
138
- } catch (error) {
139
- if (error.code === 22 && that.getStorageSize() === 0) {
140
- errorMessage = "Private browsing is unsupported";
141
- } else {
142
- errorMessage = error.message;
143
- }
144
- }
145
-
146
- if (resp) {
147
- if (options && options.success) {
148
- // When storing, we don't pass back the response (which is
149
- // the set attributes returned from localforage because
150
- // Skeletor sets them again on the model and due to the async
151
- // nature of localforage it can cause stale attributes to be
152
- // set on a model after it's been updated in the meantime.
153
- const data = (method === "read") ? resp : null;
154
- options.success(data, options);
155
- }
156
- } else {
157
- errorMessage = errorMessage ? errorMessage : "Record Not Found";
158
- if (options && options.error) {
159
- options.error(errorMessage);
160
- }
161
- }
162
- }
163
- localSync.__name__ = 'localSync';
164
- return localSync;
165
- }
166
-
167
- removeCollectionReference (model, collection) {
168
- if (!collection) {
169
- return;
170
- }
171
- const ids = collection
172
- .filter(m => (m.id !== model.id))
173
- .map(m => this.getItemName(m.id));
174
-
175
- return this.store.setItem(this.name, ids);
176
- }
177
-
178
- addCollectionReference (model, collection) {
179
- if (!collection) {
180
- return;
181
- }
182
- const ids = collection.map(m => this.getItemName(m.id));
183
- const new_id = this.getItemName(model.id);
184
- if (!ids.includes(new_id)) {
185
- ids.push(new_id);
186
- }
187
- return this.store.setItem(this.name, ids);
188
- }
189
-
190
- getCollectionReferenceData (model) {
191
- if (!model.collection) {
192
- return {};
193
- }
194
- const ids = model.collection.map(m => this.getItemName(m.id));
195
- const new_id = this.getItemName(model.id);
196
- if (!ids.includes(new_id)) {
197
- ids.push(new_id);
198
- }
199
- const result = {};
200
- result[this.name] = ids;
201
- return result;
202
- }
203
-
204
- async save (model) {
205
- if (this.store.setItems) {
206
- const items = {}
207
- items[this.getItemName(model.id)] = model.toJSON();
208
- Object.assign(items, this.getCollectionReferenceData(model));
209
- return (this.store.debouncedSetItems) ?
210
- this.store.debouncedSetItems(items) :
211
- this.store.setItems(items);
212
- } else {
213
- const key = this.getItemName(model.id);
214
- const data = await this.store.setItem(key, model.toJSON());
215
- await this.addCollectionReference(model, model.collection);
216
- return data;
217
- }
218
- }
219
-
220
- create (model, options) {
221
- /* Add a model, giving it a (hopefully)-unique GUID, if it doesn't already
222
- * have an id of it's own.
223
- */
224
- if (!model.id) {
225
- model.id = guid();
226
- model.set(model.idAttribute, model.id, options);
227
- }
228
- return this.save(model);
229
- }
230
-
231
- update (model) {
232
- return this.save(model);
233
- }
234
-
235
- find (model) {
236
- return this.store.getItem(this.getItemName(model.id));
237
- }
238
-
239
- async findAll () {
240
- /* Return the array of all models currently in storage.
241
- */
242
- const keys = await this.store.getItem(this.name);
243
- if (keys?.length) {
244
- const items = await this.store.getItems(keys);
245
- debugger;
246
- return Object.values(items);
247
- }
248
- return [];
249
- }
250
-
251
- async destroy (model, collection) {
252
- await this.flush();
253
- await this.store.removeItem(this.getItemName(model.id));
254
- await this.removeCollectionReference(model, collection);
255
- return model;
256
- }
257
-
258
- getStorageSize () {
259
- return this.store.length;
260
- }
261
-
262
- getItemName (id) {
263
- return this.name+"-"+id;
264
- }
265
- }
266
-
267
- Storage.sessionStorageInitialized = localForage.defineDriver(sessionStorageWrapper);
268
- Storage.localForage = localForage;
269
- export default Storage;