-
Notifications
You must be signed in to change notification settings - Fork 62
Expand file tree
/
Copy pathfirestore.ts
More file actions
305 lines (283 loc) · 8.58 KB
/
firestore.ts
File metadata and controls
305 lines (283 loc) · 8.58 KB
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
// The MIT License (MIT)
//
// Copyright (c) 2018 Firebase
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import { Change } from 'firebase-functions/v1';
import { firestore, app } from 'firebase-admin';
import { has, get, isEmpty, isPlainObject, mapValues } from 'lodash';
import { inspect } from 'util';
import { testApp } from '../app';
import * as http from 'http';
import {
DocumentSnapshot,
QueryDocumentSnapshot,
} from 'firebase-admin/firestore';
function dateToTimestampProto(
timeString?: string
): { seconds: number; nanos: number } | undefined {
if (typeof timeString === 'undefined') {
return;
}
const date = new Date(timeString);
const seconds = Math.floor(date.getTime() / 1000);
let nanos = 0;
if (timeString.length > 20) {
const nanoString = timeString.substring(20, timeString.length - 1);
const trailingZeroes = 9 - nanoString.length;
nanos = parseInt(nanoString, 10) * Math.pow(10, trailingZeroes);
}
return { seconds, nanos };
}
/** Optional parameters for creating a DocumentSnapshot. */
export interface DocumentSnapshotOptions {
/** ISO timestamp string for the snapshot was read, default is current time. */
readTime?: string;
/** ISO timestamp string for the snapshot was created, default is current time. */
createTime?: string;
/** ISO timestamp string for the snapshot was last updated, default is current time. */
updateTime?: string;
/** The Firebase app that the Firestore database belongs to. You do not need to supply
* this parameter if you supplied Firebase config values when initializing firebase-functions-test.
*/
firebaseApp?: app.App;
}
/** Create a DocumentSnapshot. */
export function makeDocumentSnapshot(
/** Key-value pairs representing data in the document, pass in `{}` to mock the snapshot of
* a document that doesn't exist.
*/
data: { [key: string]: any },
/** Full path of the reference (e.g. 'users/alovelace') */
refPath: string,
options?: DocumentSnapshotOptions
) {
let firestoreService;
let project;
if (has(options, 'app')) {
firestoreService = firestore(options.firebaseApp);
project = get(options, 'app.options.projectId');
} else {
firestoreService = firestore(testApp().getApp());
project = process.env.GCLOUD_PROJECT;
}
const resource = `projects/${project}/databases/(default)/documents/${refPath}`;
const proto = isEmpty(data)
? resource
: {
fields: objectToValueProto(data),
createTime: dateToTimestampProto(
get(options, 'createTime', new Date().toISOString())
),
updateTime: dateToTimestampProto(
get(options, 'updateTime', new Date().toISOString())
),
name: resource,
};
const readTimeProto = dateToTimestampProto(
get(options, 'readTime') || new Date().toISOString()
);
return firestoreService.snapshot_(proto, readTimeProto, 'json');
}
/** Fetch an example document snapshot already populated with data. Can be passed into a wrapped
* Firestore onCreate or onDelete function.
*/
export function exampleDocumentSnapshot(): firestore.DocumentSnapshot {
return makeDocumentSnapshot(
{
aString: 'foo',
anObject: {
a: 'bar',
b: 'faz',
},
aNumber: 7,
},
'records/1234'
);
}
/** Fetch an example Change object of document snapshots already populated with data.
* Can be passed into a wrapped Firestore onUpdate or onWrite function.
*/
export function exampleDocumentSnapshotChange(): Change<
firestore.DocumentSnapshot
> {
return Change.fromObjects(
makeDocumentSnapshot(
{
anObject: {
a: 'bar',
},
aNumber: 7,
},
'records/1234'
),
makeDocumentSnapshot(
{
aString: 'foo',
anObject: {
a: 'qux',
b: 'faz',
},
aNumber: 7,
},
'records/1234'
)
);
}
/** @internal */
export function objectToValueProto(data: object) {
const encodeHelper = (val) => {
if (typeof val === 'string') {
return {
stringValue: val,
};
}
if (typeof val === 'boolean') {
return {
booleanValue: val,
};
}
if (typeof val === 'number') {
if (val % 1 === 0) {
return {
integerValue: val,
};
}
return {
doubleValue: val,
};
}
if (val instanceof Date) {
return {
timestampValue: val.toISOString(),
};
}
if (val instanceof Array) {
let encodedElements = [];
for (const elem of val) {
const enc = encodeHelper(elem);
if (enc) {
encodedElements.push(enc);
}
}
return {
arrayValue: {
values: encodedElements,
},
};
}
if (val === null) {
// TODO: Look this up. This is a google.protobuf.NulLValue,
// and everything in google.protobuf has a customized JSON encoder.
// OTOH, Firestore's generated .d.ts files don't take this into
// account and have the default proto layout.
return {
nullValue: 'NULL_VALUE',
};
}
if (val instanceof Buffer || val instanceof Uint8Array) {
return {
bytesValue: val,
};
}
if (val instanceof firestore.DocumentReference) {
const projectId: string = get(val, '_referencePath.projectId');
const database: string = get(val, '_referencePath.databaseId');
const referenceValue: string = [
'projects',
projectId,
'databases',
database,
val.path,
].join('/');
return { referenceValue };
}
if (val instanceof firestore.Timestamp) {
return {
timestampValue: val.toDate().toISOString(),
};
}
if (val instanceof firestore.GeoPoint) {
return {
geoPointValue: {
latitude: val.latitude,
longitude: val.longitude,
},
};
}
if (isPlainObject(val)) {
return {
mapValue: {
fields: objectToValueProto(val),
},
};
}
throw new Error(
'Cannot encode ' +
val +
'to a Firestore Value.' +
` Local testing does not yet support objects of type ${val?.constructor?.name}.`
);
};
return mapValues(data, encodeHelper);
}
const FIRESTORE_ADDRESS_ENVS = [
'FIRESTORE_EMULATOR_HOST',
'FIREBASE_FIRESTORE_EMULATOR_ADDRESS',
];
/** Clears all data in firestore. Works only in offline mode.
*/
export function clearFirestoreData(options: { projectId: string } | string) {
const FIRESTORE_ADDRESS = FIRESTORE_ADDRESS_ENVS.reduce(
(addr, name) => process.env[name] || addr,
'localhost:8080'
);
return new Promise((resolve, reject) => {
let projectId;
if (typeof options === 'string') {
projectId = options;
} else if (typeof options === 'object' && has(options, 'projectId')) {
projectId = options.projectId;
} else {
throw new Error('projectId not specified');
}
const config = {
method: 'DELETE',
hostname: FIRESTORE_ADDRESS.split(':')[0],
port: FIRESTORE_ADDRESS.split(':')[1],
path: `/emulator/v1/projects/${projectId}/databases/(default)/documents`,
};
const req = http.request(config, (res) => {
if (res.statusCode !== 200) {
reject(new Error(`statusCode: ${res.statusCode}`));
}
res.on('data', () => {});
res.on('end', resolve);
});
req.on('error', (error) => {
reject(error);
});
const postData = JSON.stringify({
database: `projects/${projectId}/databases/(default)`,
});
req.setHeader('Content-Length', postData.length);
req.write(postData);
req.end();
});
}