-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmod.ts
639 lines (602 loc) · 19.2 KB
/
mod.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
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
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
// deno-lint-ignore-file no-explicit-any
import * as googleAuth from "google-auth-library";
/**
* Enum representing the available Firestore query operators
*/
export enum FirestoreOperator {
LESS_THAN = "LESS_THAN",
LESS_THAN_OR_EQUAL = "LESS_THAN_OR_EQUAL",
GREATER_THAN = "GREATER_THAN",
GREATER_THAN_OR_EQUAL = "GREATER_THAN_OR_EQUAL",
EQUAL = "EQUAL",
NOT_EQUAL = "NOT_EQUAL",
ARRAY_CONTAINS = "ARRAY_CONTAINS",
IN = "IN",
ARRAY_CONTAINS_ANY = "ARRAY_CONTAINS_ANY",
NOT_IN = "NOT_IN",
IS_NAN = "IS_NAN",
IS_NULL = "IS_NULL",
IS_NOT_NAN = "IS_NOT_NAN",
IS_NOT_NULL = "IS_NOT_NULL",
}
/**
* Firestore Admin Client for interacting with Google Cloud Firestore in Deno.
*
* Handles authentication via service account credentials and provides methods for CRUD operations.
* Requires FIREBASE_SERVICE_ACCOUNT environment variable to be set with service account JSON.
*
* @example
* ```ts
* const firestore = new FirestoreAdminClient();
* ```
*/
export class FirestoreAdminClient {
private FIREBASE_SERVICE_ACCOUNT: any;
private GCP_PROJECT_NAME: string;
private AUTH_SCOPES: string[];
private firestoreBaseUrl: string;
private jwtClient: googleAuth.JWT;
private accessToken: string | null | undefined;
private tokenExpiry: number;
constructor() {
const serviceAccountJson = Deno.env.get("FIREBASE_SERVICE_ACCOUNT");
if (!serviceAccountJson) {
throw new Error(
"FIREBASE_SERVICE_ACCOUNT environment variable is not set",
);
}
this.FIREBASE_SERVICE_ACCOUNT = JSON.parse(serviceAccountJson);
this.GCP_PROJECT_NAME = this.FIREBASE_SERVICE_ACCOUNT.project_id;
this.AUTH_SCOPES = ["https://www.googleapis.com/auth/cloud-platform"];
this.firestoreBaseUrl =
`https://content-firestore.googleapis.com/v1/projects/${this.GCP_PROJECT_NAME}/databases/(default)/documents`;
this.jwtClient = new googleAuth.JWT(
this.FIREBASE_SERVICE_ACCOUNT.client_email,
undefined,
this.FIREBASE_SERVICE_ACCOUNT.private_key,
this.AUTH_SCOPES,
undefined,
);
this.accessToken = null;
this.tokenExpiry = 0;
}
/**
* Refreshes the access token if expired or not present
* @private
* @see https://firebase.google.com/docs/projects/provisioning/configure-oauth#auth
*/
private async refreshAccessToken(): Promise<void> {
const now = Date.now();
if (!this.accessToken || now >= this.tokenExpiry) {
const tokens = await this.jwtClient.authorize();
this.accessToken = tokens.access_token;
this.tokenExpiry = now + (tokens.expiry_date || 3600) * 1000; // Default to 1 hour if expiry_date is not provided by Google
}
}
/**
* Gets authorization headers for API requests
* @private
* @returns Headers object with authorization token
*/
private async getHeaders(): Promise<Record<string, string>> {
await this.refreshAccessToken();
return {
"accept": "*/*",
"authorization": `Bearer ${this.accessToken}`,
"sec-fetch-dest": "empty",
"sec-fetch-mode": "cors",
"sec-fetch-site": "same-origin",
"sec-gpc": "1",
};
}
/**
* Creates a new document in Firestore
* @param path - The path to the collection where document will be created
* @param data - The document data to create
* @returns The created document data with _id and _path fields
* @example
* ```ts
* const document = await firestore.createDocument("my-collection", {
* name: "John Doe",
* });
* ```
*/
async createDocument(path: string, data: object): Promise<any> {
const body = this.jsonToDocument(data);
const headers = await this.getHeaders();
const response = await fetch(`${this.firestoreBaseUrl}/${path}`, {
"headers": headers,
"body": JSON.stringify(body),
"method": "POST",
});
const responseData: any = await response.json();
if (responseData?.error) {
this.errorHandler(responseData.error, "createDocument");
}
const jsonDocument = this.documentToJson(responseData.fields);
return {
_id: responseData.name.split(`/`).pop(),
_path: responseData.name.split("documents/")[1],
...jsonDocument,
};
}
/**
* Lists all documents in a collection
* @param path - The path to the collection
* @returns Array of document IDs in the collection
* @example
* ```ts
* const documents = await firestore.listDocumentsInCollection("my-collection");
* ```
*/
async listDocumentsInCollection(path: string): Promise<string[]> {
const headers = await this.getHeaders();
const response = await fetch(`${this.firestoreBaseUrl}/${path}`, {
"headers": headers,
"body": null,
"method": "GET",
});
const data: any = await response.json();
if (data?.error) this.errorHandler(data.error, "listDocumentsInCollection");
data.documents =
data.documents?.map((doc: any) => doc.name.split(`${path}/`).pop()) ?? [];
return data.documents;
}
/**
* Fetches a single document by path
* @param path - The full path to the document
* @returns The document data
* @example
* ```ts
* const document = await firestore.getDocument("my-collection/my-document");
* ```
*/
async getDocument(path: string): Promise<any> {
const headers = await this.getHeaders();
const response = await fetch(`${this.firestoreBaseUrl}/${path}`, {
"headers": headers,
"body": null,
"method": "GET",
});
const data: any = await response.json();
if (data?.error) this.errorHandler(data.error, "getDocument");
// console.log(this.documentToJson(data.fields));
return this.documentToJson(data.fields);
}
/**
* Fetches all documents in a collection with optional query parameters
* @param path - The path to the collection
* @param options - Query options including filters, ordering, limits and offsets
* @returns Array of document data
* @example
* ```ts
* // Simple case:
* const documents = await firestore.getDocumentsInCollection("my-collection");
*
* // More complex cases:
*
* // Import the FirestoreOperator enum
* import { FirestoreOperator } from "@koiztech/firestore-admin";
*
* // use some filters:
* const documents = await firestore.getDocumentsInCollection("my-collection", {
* where: {
* filters: [
* ["name", FirestoreOperator.EQUAL, "John Doe"],
* ],
* },
* });
*
* // use filters, sorting and limiting:
* const documents = await firestore.getDocumentsInCollection("my-collection", {
* where: {
* filters: [
* ["name", FirestoreOperator.EQUAL, "Ivan Petrov"],
* ["age", FirestoreOperator.GREATER_THAN, 20],
* ["address.city", FirestoreOperator.EQUAL, "Moscow"], // example of a nested field
* ],
* },
* orderBy: [{ field: "createdAt", direction: "DESCENDING" }], // you can sort the results
* limit: 3, // you can limit the number of results
* });
* ```
*/
async getDocumentsInCollection(path: string, options?: {
where?: {
filters: [string, FirestoreOperator, any][];
operator?: "AND" | "OR";
};
orderBy?: { field: string; direction?: "ASCENDING" | "DESCENDING" }[];
limit?: number;
offset?: number;
}): Promise<any> {
const headers = await this.getHeaders();
if (options) {
const structuredQuery: any = {
from: [{ collectionId: path, allDescendants: false }],
};
if (options.where) {
structuredQuery.where = {
compositeFilter: {
op: "AND",
filters: options.where.filters.map(([field, op, value]) => {
if (field === "documentId") {
if (!Array.isArray(value)) {
value = [value];
}
// For documentId filters, we need to construct the full document path
const fullPaths = value.map((id: string) => {
// If ID is already a full path, use it directly
if (id.includes("projects/")) return id;
// Otherwise construct the full path
return `projects/${this.GCP_PROJECT_NAME}/databases/(default)/documents/${path}/${id}`;
});
return {
fieldFilter: {
field: { fieldPath: "__name__" },
op: FirestoreOperator.IN, // Filtering by document ID(s) requires IN operator
value: {
arrayValue: {
values: fullPaths.map((p: any) => ({
referenceValue: p,
})),
},
},
},
};
}
return {
fieldFilter: {
field: { fieldPath: field },
op,
value: this.encodeValue(value),
},
};
}),
},
};
}
if (options.orderBy) {
structuredQuery.orderBy = options.orderBy.map((
{ field, direction = "ASCENDING" },
) => ({
field: { fieldPath: field },
direction,
}));
}
if (options.limit !== undefined) {
structuredQuery.limit = { value: options.limit };
}
if (options.offset !== undefined) {
structuredQuery.offset = options.offset;
}
const response = await fetch(
`${this.firestoreBaseUrl}:runQuery`,
{
headers,
method: "POST",
body: JSON.stringify({ structuredQuery }),
},
);
const data: any = await response.json();
if (data?.error || data?.[0]?.error) {
this.errorHandler(
data.error ?? data?.[0]?.error,
`${this.firestoreBaseUrl}/${path}:runQuery`,
);
// console.log({
// extendedDetails: data.error?.details ?? data?.[0]?.error?.details,
// });
return [];
}
// If the query yields no results, it will return: [ { readTime: string } ]
if (data.length == 1 && !data[0].document) {
return [];
}
return data.map((doc: any) => {
const docId = doc.document?.name.split(`/`).pop() ?? "unknown";
// console.log({ docId });
const documentFields = doc.document?.fields || {};
return { ...this.documentToJson(documentFields), _id: docId };
});
} else {
const response = await fetch(`${this.firestoreBaseUrl}/${path}`, {
headers,
method: "GET",
});
const data: any = await response.json();
if (data?.error) {
this.errorHandler(data.error, "listDocumentsInCollection");
}
return data.documents?.map((doc: any) => {
const docId = doc.name.split(`/`).pop() ?? "unknown";
const documentFields = doc.fields || {};
return { ...this.documentToJson(documentFields), _id: docId };
}) || [];
}
}
/**
* Gets documents from a collection group (i.e. a sub collection)
* @param collectionId - The ID of the collection group to query
* @param options - Query options including filters, ordering, and limits
* @returns Array of documents matching the query
* @example
* ```ts
* // e.g. `orders` is a sub collection of `customers/{customerId}`
* const documents = await firestore.getDocumentsInCollectionGroup('orders', {
* where: {
* filters: [
* ['createdAt', FirestoreOperator.GREATER_THAN, new Date('2024-01-01')]
* ]
* }
* })
* ```
*/
async getDocumentsInCollectionGroup(
collectionId: string,
options: {
where?: {
filters: [string, FirestoreOperator, any][];
};
orderBy?: { field: string; direction: "ASCENDING" | "DESCENDING" }[];
limit?: number;
} = {},
): Promise<any[]> {
const structuredQuery: any = {
from: [{
collectionId,
allDescendants: true,
}],
};
if (options.where?.filters) {
structuredQuery.where = {
compositeFilter: {
op: "AND",
filters: options.where.filters.map(([field, operator, value]) => ({
fieldFilter: {
field: { fieldPath: field },
op: operator,
value: this.jsonToDocument({ value })[`fields`][`value`],
},
})),
},
};
}
if (options.orderBy) {
structuredQuery.orderBy = options.orderBy.map(({ field, direction }) => ({
field: { fieldPath: field },
direction,
}));
}
if (options.limit) {
structuredQuery.limit = options.limit;
}
const headers = await this.getHeaders();
const response = await fetch(
`${this.firestoreBaseUrl}:runQuery`,
{
headers,
method: "POST",
body: JSON.stringify({ structuredQuery }),
},
);
const data: any = await response.json();
if (data?.error || data?.[0]?.error) {
this.errorHandler(
data.error ?? data?.[0]?.error,
`${this.firestoreBaseUrl}:runQuery`,
);
// console.log({
// extendedDetails: data.error?.details ?? data?.[0]?.error?.details,
// });
return [];
}
if (data.length == 1 && !data[0].document) {
return [];
}
return data.map((doc: any) => {
const docId = doc.document?.name.split("/").pop() ?? "unknown";
const documentFields = doc.document?.fields || {};
return {
...this.documentToJson(documentFields),
_id: docId,
_path: doc.document?.name?.split("documents/")[1],
};
});
}
/**
* Updates a document
* @param path - The path to the document
* @param data - The data to update
* @param updateFields - Optional array of field paths to update
* @returns The updated document data with _id and _path fields
* @example
* ```ts
* await firestore.updateDocument('my-collection/my-document', {
* name: 'John Doe'
* })
*
* // ...or with specific update fields
*
* await firestore.updateDocument('my-collection/my-document', {
* name: 'John Doe',
* age: 30, // this field will not be updated
* address: {
* city: 'Dubai',
* country: 'United Arab Emirates' // this field will not be updated
* }
* }, ['name', 'address.city']) // you can use nested fields as well
* ```
*/
async updateDocument(
path: string,
data: any,
updateFields?: string[],
): Promise<any> {
const body = this.jsonToDocument(data);
let url = `${this.firestoreBaseUrl}/${path}`;
if (updateFields && updateFields.length > 0) {
url = url.concat(
`?updateMask.fieldPaths=${
updateFields.join("&updateMask.fieldPaths=")
}`,
);
}
// console.log("> Updating document:\n", url);
const headers = await this.getHeaders();
const response = await fetch(`${url}`, {
"headers": headers,
"body": JSON.stringify(body),
"method": "PATCH",
});
const responseData: any = await response.json();
if (responseData?.error) {
this.errorHandler(responseData.error, "updateDocument");
}
const jsonDocument = this.documentToJson(responseData.fields);
return {
_id: responseData.name.split(`/`).pop(),
_path: responseData.name.split("documents/")[1],
...jsonDocument,
};
}
/**
* Converts Firestore document format to JSON
* @private
* @param fields - The Firestore document fields
* @returns Plain JavaScript object
*/
private documentToJson(fields: any): any {
if (!fields) {
return {};
}
const result: any = {};
for (const f in fields) {
const key = f,
value = fields[f],
isDocumentType = [
"stringValue",
"booleanValue",
"doubleValue",
"integerValue",
"timestampValue",
"mapValue",
"arrayValue",
"nullValue",
].find((t) => t === key);
if (isDocumentType) {
const item = [
"stringValue",
"booleanValue",
"doubleValue",
"integerValue",
"timestampValue",
"nullValue",
]
.find((t) => t === key);
if (item) {
return value;
} else if ("mapValue" == key) {
return this.documentToJson(value.fields || {});
} else if ("arrayValue" == key) {
const list = value.values;
return !list ? list?.map((l: any) => this.documentToJson(l)) : [];
}
} else {
result[key] = this.documentToJson(value);
}
}
return result;
}
/**
* Encodes JavaScript values to Firestore value types
* @private
* @param value - The value to encode
* @returns Firestore value representation
*/
private encodeValue(value: any): any {
if (typeof value === "string") {
return { stringValue: value };
} else if (typeof value === "number") {
if (Number.isInteger(value)) {
return { integerValue: value };
} else {
return { doubleValue: value };
}
} else if (typeof value === "boolean") {
return { booleanValue: value };
} else if (value === null) {
return { nullValue: "NULL_VALUE" };
} else if (Array.isArray(value)) {
return { arrayValue: { values: value.map((v) => this.encodeValue(v)) } };
} else if (value instanceof Date) {
return { timestampValue: value.toJSON() };
} else {
throw new Error(`Unsupported value type: ${typeof value}`);
}
}
/**
* Converts JSON to Firestore document format
* @private
* @param json - Plain JavaScript object
* @returns Firestore document representation
*/
private jsonToDocument(json: any): { fields: any } {
const data: any = { fields: {} };
Object.keys(json).forEach((key) => {
let value = json[key];
let type;
if (typeof value === "string") {
type = "stringValue";
} else if (typeof value === "number") {
if (Number.isInteger(value)) {
type = "integerValue";
if (isNaN(value)) value = 0; // catch NaN
} else {
type = "doubleValue";
if (isNaN(value)) value = 0.00; // catch NaN
}
} else if (value instanceof Date) {
type = "timestampValue";
value = value.toJSON();
} else if (typeof value === "boolean") {
type = "booleanValue";
} else if (value === null || value === undefined) {
type = "nullValue";
} else if (Array.isArray(value)) {
type = "arrayValue";
value = {
values: value.map((v) => {
const val = this.jsonToDocument({ value: v }).fields.value;
return val;
}),
};
} else if (typeof value === "object") {
type = "mapValue";
value = { fields: this.jsonToDocument(value).fields };
} else {
throw new Error(`Unsupported type for value: ${value}`);
}
data.fields[key] = { [type]: value };
});
return data;
}
/**
* Handles errors from Firestore API calls
* @private
* @param error - The error object from Firestore
* @param call - The name of the function that encountered the error
*/
private errorHandler(error: any, call: any): void {
console.error(
"*-*".repeat(20),
"\ncall:",
call,
"\nerrorCode:",
error.code,
"\nerrorMessage:",
`${error.message}\n`,
"*-*".repeat(20),
);
}
}