-
-
Notifications
You must be signed in to change notification settings - Fork 374
/
biblio-db.js
284 lines (282 loc) · 7.94 KB
/
biblio-db.js
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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
/**
* Module core/biblio-db
*
* Wraps IndexedDB, allowing the storage of references and aliases on the
* client.
*
* It's a standalone module that can be imported into other modules.
*
* It exports { biblioDB }
*
*/
/*globals IDBKeyRange, DOMException, console */
import { pub } from "core/pubsubhub";
const ALLOWED_TYPES = new Set(["alias", "reference"]);
// Database initialization, tracked by "readyPromise"
const readyPromise = new Promise((resolve, reject) => {
let request;
try {
request = window.indexedDB.open("respec-biblio", 1);
} catch (err) {
return reject(err);
}
request.onerror = () => {
reject(new DOMException(request.error.message, request.error.name));
};
request.onsuccess = () => {
resolve(request.result);
};
request.onupgradeneeded = function() {
const db = request.result;
Array
.from(db.objectStoreNames)
.map(
storeName => db.deleteObjectStore(storeName)
);
const promisesToCreateSchema = [
new Promise((resolve, reject) => {
try {
const store = db.createObjectStore("alias", { keyPath: "id" });
store.createIndex("aliasOf", "aliasOf", { unique: false });
store.transaction.oncomplete = resolve;
} catch (err) {
reject(err);
}
}),
new Promise((resolve, reject) => {
try {
db
.createObjectStore("reference", { keyPath: "id" })
.transaction
.oncomplete = resolve;
} catch (err) {
reject(err);
}
}),
];
Promise
.all(promisesToCreateSchema)
.catch(reject);
};
});
export const biblioDB = {
get ready() {
return readyPromise;
},
/**
* Finds either a reference or an alias.
* If it's an alias, it resolves it.
*
* @param {String} id The reference or alias to look for.
* @return {Object?} The reference or null.
*/
async find(id) {
if (await this.isAlias(id)) {
id = await this.resolveAlias(id);
}
return this.get("reference", id);
},
/**
* Checks if the database has an id for a given type.
*
* @param {String} type One of the ALLOWED_TYPES.
* @param {String} id The reference to find.
* @return {Boolean} True if it has it, false otherwise.
*/
async has(type, id) {
if (!ALLOWED_TYPES.has(type)) {
throw new TypeError("Invalid type: " + type);
}
if (!id) {
throw new TypeError("id is required");
}
const db = await this.ready;
return new Promise((resolve, reject) => {
var objectStore = db
.transaction([type], "readonly")
.objectStore(type);
var range = IDBKeyRange.only(id);
var request = objectStore.openCursor(range);
request.onsuccess = () => {
resolve(!!request.result);
};
request.onerror = () => {
reject(new DOMException(request.error.message, request.error.name));
};
});
},
/**
* Checks if a given id is an alias.
*
* @param {String} id The reference to check.
* @return {Promise<Boolean>} Resolves with true if found.
*/
async isAlias(id) {
if (!id) {
throw new TypeError("id is required");
}
const db = await this.ready;
return new Promise((resolve, reject) => {
var objectStore = db
.transaction(["alias"], "readonly")
.objectStore("alias");
var range = IDBKeyRange.only(id);
var request = objectStore.openCursor(range);
request.onsuccess = () => {
resolve(!!request.result);
};
request.onerror = () => {
reject(new DOMException(request.error.message, request.error.name));
};
});
},
/**
* Resolves an alias to its corresponding reference id.
*
* @param {String} id The id of the alias to look up.
* @return {Promise<String>} The id of the resolved reference.
*/
async resolveAlias(id) {
if (!id) {
throw new TypeError("id is required");
}
const db = await this.ready;
return new Promise((resolve, reject) => {
var objectStore = db
.transaction("alias", "readonly")
.objectStore("alias");
var range = IDBKeyRange.only(id);
var request = objectStore.openCursor(range);
request.onsuccess = () => {
if (request.result === null) {
return resolve(null);
}
resolve(request.result.value.aliasOf);
};
request.onerror = () => {
reject(new DOMException(request.error.message, request.error.name));
};
});
},
/**
* Get a reference or alias out of the database.
*
* @param {String} type The type as per ALLOWED_TYPES.
* @param {[type]} id The id for what to look up.
* @return {Promise<Object?>} Resolves with the retrieved object, or null.
*/
async get(type, id) {
if (!ALLOWED_TYPES.has(type)) {
throw new TypeError("Invalid type: " + type);
}
if (!id) {
throw new TypeError("id is required");
}
const db = await this.ready;
return new Promise((resolve, reject) => {
var objectStore = db
.transaction([type], "readonly")
.objectStore(type);
var range = IDBKeyRange.only(id);
var request = objectStore.openCursor(range);
request.onsuccess = () => {
if (request.result === null) {
return resolve(null);
}
resolve(request.result.value);
};
request.onerror = () => {
reject(new DOMException(request.error.message, request.error.name));
};
});
},
/**
* Adds references and aliases to database. This is usually the data from
* Specref's output (parsed JSON).
*
* @param {Object} data An object that contains references and aliases.
*/
async addAll(data) {
if (!data) {
return;
}
const aliasesAndRefs = {
alias: new Set(),
reference: new Set(),
};
Object
.keys(data)
.filter(key => {
if (typeof data[key] === "string") {
let msg = "Legacy SpecRef entries are not supported: [[" + key + "]]. ";
msg += "Please update it at https://github.com/tobie/specref/";
pub("error", msg);
return false;
}
return true;
})
.map(
id => Object.assign({ id }, data[id])
)
.reduce((collector, obj) => {
if (obj.aliasOf) {
collector.alias.add(obj);
} else {
collector.reference.add(obj);
}
return collector;
}, aliasesAndRefs);
const promisesToAdd = Object
.keys(aliasesAndRefs)
.map(type => {
return Array
.from(aliasesAndRefs[type])
.map(
details => this.add(type, details)
);
})
.reduce(
(collector, promises) => collector.concat(promises), []
);
await Promise.all(promisesToAdd);
},
/**
* Adds a reference or alias to the database.
*
* @param {String} type The type as per ALLOWED_TYPES.
* @param {String} details The object to store.
*/
async add(type, details) {
if (!ALLOWED_TYPES.has(type)) {
throw new TypeError("Invalid type: " + type);
}
if (typeof details !== "object") {
throw new TypeError("details should be an object");
}
if (type === "alias" && !details.hasOwnProperty("aliasOf")) {
throw new TypeError("Invalid alias object.");
}
const db = await this.ready;
const isInDB = await this.has(type, details.id);
return new Promise((resolve, reject) => {
const store = db
.transaction([type], "readwrite")
.objectStore(type);
// update or add, depending of already having it in db
var request = isInDB ? store.put(details) : store.add(details);
request.onsuccess = resolve;
request.onerror = () => {
reject(new DOMException(request.error.message, request.error.name));
};
});
},
/**
* Closes the underlying database.
*
* @return {Promise} Resolves after database closes.
*/
async close() {
const db = await this.ready;
db.close();
},
};