-
Notifications
You must be signed in to change notification settings - Fork 5
/
database.js
455 lines (399 loc) · 12.2 KB
/
database.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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
/* @flow */
import Path from 'path';
import FS from 'fs';
import google from 'googleapis';
import set from 'object-set';
import type {
GoogleCredential,
Collections,
Collection,
Document,
FirestoreTestCase,
FirestoreMockFunction,
FirestoreAuth,
TestSummary
} from './types';
import Batch, { type BatchOperation } from './batch';
class Database {
credential: GoogleCredential;
collections: Collections;
rules: string;
client: ?google.firebaserules;
constructor({
data,
credential,
rules
}: {
data?: Collections,
credential: GoogleCredential,
rules?: string
}) {
this.credential = credential;
this.collections = data || {};
this.rules = rules || '';
}
/*
* Replace the mock data.
*/
setData(data: Collections) {
this.collections = data;
}
/*
* Update the rules.
*/
setRules(rules: string) {
this.rules = rules;
}
/*
* Read the rules from a file.
*/
setRulesFromFile(rulesFile: string) {
const content = FS.readFileSync(rulesFile, 'utf8');
this.setRules(content);
}
/*
* Get all documents in a collection.
*/
getCollection(collectionPath: string): Collection {
const collectionName = Path.basename(collectionPath);
const docPath = Path.dirname(collectionPath);
if (docPath == '.') {
const { collections } = this;
return collections[collectionName] || [];
}
const doc = this.getDocument(docPath);
if (doc) {
const { collections } = doc;
return collections[collectionName] || [];
}
return [];
}
/*
* Get the value of a document (fields and collection).
*/
getDocument(docPath: string): ?Document {
const docId = Path.basename(docPath);
const collectionPath = Path.dirname(docPath);
const collection = this.getCollection(collectionPath);
return collection.find(doc => doc.key == docId);
}
/*
* Test if a document exists in the local database.
*/
hasDocument(docPath: string): boolean {
return !!this.getDocument(docPath);
}
/*
* List all documents in the database.
*/
getDocuments(
collections: Collections = this.collections,
parentPath: string = ''
): { path: string, doc: Document }[] {
return Object.keys(collections).reduce((result, collectionName) => {
const collectionPath = Path.join(parentPath, collectionName);
const docs = collections[collectionName].reduce((_docs, doc) => {
const docPath = Path.join(collectionPath, doc.key);
const children = this.getDocuments(doc.collections, docPath);
return [
{
path: docPath,
doc
}
]
.concat(_docs)
.concat(children);
}, []);
return result.concat(docs);
}, []);
}
/*
* Authorize the API client.
*/
async authorize(): Promise<void> {
const { credential } = this;
if (this.client) {
return;
}
const jwtClient = new google.auth.JWT(
credential.client_email,
null,
credential.private_key,
['https://www.googleapis.com/auth/firebase'], // an array of auth scopes
null
);
await new Promise((resolve, reject) => {
jwtClient.authorize((error, tokens) => {
if (error) {
reject(error);
} else {
this.client = google.firebaserules({
version: 'v1',
auth: jwtClient
});
resolve();
}
});
});
}
/*
* Test an assertion against the current rules and dataset.
*/
async testRules(testCases: FirestoreTestCase[]): Promise<TestSummary> {
return new Promise((resolve, reject) => {
const params = {
name: `projects/${this.credential.project_id}`,
resource: {
source: {
files: [
{
name: 'firestore.rules',
content: this.rules
}
]
},
testSuite: {
testCases
}
}
};
if (!this.client) {
throw new Error(
'API client not authorized yet, call database.authorize() first'
);
}
this.client.projects.test(params, (error, json) => {
if (error) {
reject(error);
} else {
// There are some syntax error in the rules
if (json.issues) {
const message = json.issues
.map(
issue =>
`Line ${
issue.sourcePosition.line
}, column ${issue.sourcePosition.column}: ${
issue.description
}`
)
.join('\n\n');
throw new Error(message);
}
const { testResults } = json;
let success = true;
const tests = testResults.map((result, i) => {
success = result.state == 'SUCCESS' && success;
return {
case: testCases[i],
result
};
});
resolve({
success,
tests
});
}
});
});
}
/*
* Utilities for assertions.
*/
async canGet(auth: FirestoreAuth, path: string): Promise<TestSummary> {
return this.testRules([this.createGetTest(true, auth, path)]);
}
async cannotGet(auth: FirestoreAuth, path: string): Promise<TestSummary> {
return this.testRules([this.createGetTest(false, auth, path)]);
}
async canCommit(
auth: FirestoreAuth,
batch: BatchOperation[]
): Promise<TestSummary> {
return this.testRules(this.createCommitTest(true, auth, batch));
}
async cannotCommit(
auth: FirestoreAuth,
batch: BatchOperation[]
): Promise<TestSummary> {
return this.testRules(this.createCommitTest(false, auth, batch));
}
async canSet(
auth: FirestoreAuth,
path: string,
data: Object
): Promise<TestSummary> {
return this.canCommit(auth, [Batch.set(path, data)]);
}
async cannotSet(
auth: FirestoreAuth,
path: string,
data: Object
): Promise<TestSummary> {
return this.cannotCommit(auth, [Batch.set(path, data)]);
}
async canUpdate(
auth: FirestoreAuth,
path: string,
data: Object
): Promise<TestSummary> {
return this.canCommit(auth, [Batch.update(path, data)]);
}
async cannotUpdate(
auth: FirestoreAuth,
path: string,
data: Object
): Promise<TestSummary> {
return this.cannotCommit(auth, [Batch.update(path, data)]);
}
/*
* Factories for tests
*/
createGetTest(
allow: boolean,
auth: FirestoreAuth,
path: string
): FirestoreTestCase {
const functionMocks = this.createMockFunctions();
const doc = this.getDocument(path);
const request = {
auth,
path: createDocumentPath(path),
method: 'get'
};
return {
expectation: allow ? 'ALLOW' : 'DENY',
request,
resource: { data: doc ? doc.fields : null },
functionMocks
};
}
/*
* Create a test for a commit with multiple updates.
*/
createCommitTest(
allow: boolean,
auth: FirestoreAuth,
batch: BatchOperation[]
): FirestoreTestCase[] {
const expectation = allow ? 'ALLOW' : 'DENY';
const baseFunctionMocks = this.createMockFunctions();
const afterFunctionMocks = this.createBatchAfterFunctionMocks(batch);
const functionMocks = [...baseFunctionMocks, ...afterFunctionMocks];
return batch.map(operation => {
const doc = this.getDocument(operation.document);
let method = operation.method;
if (operation.method == 'set') {
method = doc ? 'update' : 'create';
}
const request = {
auth,
path: createDocumentPath(operation.document),
method,
resource: operation.data
? {
data: operation.data
}
: null
};
const resource = {
data: doc ? doc.fields : null
};
return {
expectation,
request,
resource,
functionMocks
};
});
}
/*
* Create the mocks for the API to represent the dataset.
*/
createMockFunctions(): FirestoreMockFunction[] {
const documents = this.getDocuments();
const defaults = [
{
function: 'get',
args: [{ anyValue: {} }],
result: {
value: null
}
},
{
function: 'getAfter',
args: [{ anyValue: {} }],
result: {
value: null
}
},
{
function: 'exists',
args: [{ anyValue: {} }],
result: {
value: false
}
}
];
const docMocks = documents.reduce(
(functions, { path, doc }) =>
functions.concat([
createFunctionMock(
'get',
createDocumentPath(path),
doc ? { data: doc.fields } : null
),
createFunctionMock(
'exists',
createDocumentPath(path),
!!doc
)
]),
[]
);
return defaults.concat(docMocks);
}
/*
* Create the mock for the getAfter functions.
*/
createBatchAfterFunctionMocks(
batch: BatchOperation[]
): FirestoreMockFunction[] {
return batch.map(operation => {
const doc = this.getDocument(operation.document);
let after = doc ? doc.fields : null;
if (operation.method == 'set') {
after = operation.data;
} else if (operation.method == 'delete') {
after = null;
} else if (operation.method == 'update') {
after = after || {};
Object.keys(operation.data).forEach(key => {
set(after, key, operation.data[key]);
});
}
return createFunctionMock(
'getAfter',
createDocumentPath(operation.document),
after ? { data: after } : null
);
});
}
}
function createDocumentPath(path: string): string {
return `/databases/(default)/documents/${path}`;
}
function createFunctionMock(
functionName: string,
arg: string,
value: any
): FirestoreMockFunction {
return {
function: functionName,
args: [{ exact_value: arg }],
result: {
value
}
};
}
export default Database;