Skip to content

Commit 493f274

Browse files
committed
refactor: issues with handler_from_process
1 parent bc7594e commit 493f274

File tree

3 files changed

+55
-25
lines changed

3 files changed

+55
-25
lines changed

jest.setup.js

+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
// stub out console.debug globally
2+
3+
global.console.debug = jest.fn();

src/distributed-tasks/firestore_backfill/handler_from_process.ts

+49-24
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ import { FirestoreBackfillOptions } from "./types";
88
export const handlerFromProcess =
99
(process: Process, options: FirestoreBackfillOptions) =>
1010
async (chunk: string[]) => {
11-
// get documents from firestore
11+
// Get documents from Firestore
1212
const docs = await getValidDocs(process, chunk, options);
1313

1414
if (docs.length === 0) {
@@ -19,8 +19,16 @@ export const handlerFromProcess =
1919
functions.logger.info(`Handling ${docs.length} documents`);
2020

2121
if (docs.length === 1) {
22-
// TODO: get rid of ! assertion
23-
const result = await process.processFn(docs[0].data()!);
22+
const data = docs[0].data();
23+
24+
if (!data) {
25+
functions.logger.error(
26+
`Document ${docs[0].ref.path} does not have any data`
27+
);
28+
return { success: 0 };
29+
}
30+
31+
const result = await process.processFn(data);
2432

2533
try {
2634
await admin
@@ -41,33 +49,50 @@ export const handlerFromProcess =
4149
}
4250

4351
const batches = chunkArray(docs, 50);
52+
let successCount = 0;
4453

4554
const results = await Promise.all(
4655
batches.map(async (batch) => {
47-
// TODO: get rid of ! assertion
48-
return process.batchProcess(batch.map((doc) => doc.data()!));
56+
const batchData = batch
57+
.map((doc) => {
58+
const data = doc.data();
59+
if (!data) {
60+
functions.logger.warn(`Document ${doc.ref.path} has no data`);
61+
return null;
62+
}
63+
return data;
64+
})
65+
.filter((data) => data !== null);
66+
67+
return process.batchProcess(batchData);
4968
})
5069
);
5170

5271
const toWrite = results.flat();
5372
const writer = admin.firestore().batch();
5473

5574
for (let i = 0; i < toWrite.length; i++) {
56-
writer.update(
57-
admin.firestore().collection(options.collectionName).doc(docs[i].id),
58-
{
59-
...toWrite[0],
60-
[`status.${process.id}.state`]: "BACKFILLED",
61-
[`status.${process.id}.completeTime`]:
62-
admin.firestore.FieldValue.serverTimestamp(),
63-
}
64-
);
75+
try {
76+
writer.update(
77+
admin.firestore().collection(options.collectionName).doc(docs[i].id),
78+
{
79+
...toWrite[i],
80+
[`status.${process.id}.state`]: "BACKFILLED",
81+
[`status.${process.id}.completeTime`]:
82+
admin.firestore.FieldValue.serverTimestamp(),
83+
}
84+
);
85+
successCount++;
86+
} catch (e) {
87+
functions.logger.error(`Failed to update document ${docs[i].id}: ${e}`);
88+
}
6589
}
90+
6691
await writer.commit();
6792

6893
functions.logger.info(`Completed processing ${docs.length} documents`);
6994

70-
return { success: docs.length };
95+
return { success: successCount };
7196
};
7297

7398
export async function getValidDocs(
@@ -78,24 +103,24 @@ export async function getValidDocs(
78103
const documents: DocumentSnapshot[] = [];
79104

80105
await admin.firestore().runTransaction(async (transaction) => {
81-
const refs = documentIds.map((id: string) =>
106+
const refs = documentIds.map((id) =>
82107
admin.firestore().collection(options.collectionName).doc(id)
83108
);
84-
//@ts-ignore
85-
const docs = await transaction.getAll<DocumentData>(...refs);
109+
const docs = await transaction.getAll(...refs);
86110

87111
for (const doc of docs) {
88112
const data = doc.data();
89-
if (!process.shouldBackfill || !process.shouldBackfill(data)) {
113+
if (!data) {
114+
functions.logger.warn(`Document ${doc.ref.path} has no data`);
115+
} else if (!process.shouldBackfill || !process.shouldBackfill(data)) {
90116
functions.logger.warn(
91117
`Document ${doc.ref.path} is not valid for ${process.id} process`
92118
);
93119
} else if (
94-
// TODO: add a param for backfill strategy
95-
data["status"] &&
96-
data["status"][process.id] &&
97-
data["status"][process.id]["state"] &&
98-
data["status"][process.id].state !== "BACKFILLED"
120+
data.status &&
121+
data.status[process.id] &&
122+
data.status[process.id].state &&
123+
data.status[process.id].state !== "BACKFILLED"
99124
) {
100125
functions.logger.warn(
101126
`Document ${doc.ref.path} is not in the correct state to be backfilled`

src/firestore-onwrite-processor/index.test.ts

+3-1
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,9 @@ type WrappedFirebaseFunction = WrappedFunction<
2727
Change<firestore.DocumentSnapshot | undefined>
2828
>;
2929

30-
const firestoreObserver = jest.fn(() => {});
30+
const firestoreObserver = jest.fn((x) => {
31+
console.debug("firestoreObserver", x);
32+
});
3133
let collectionName: string;
3234

3335
const processFn = ({ input }: Record<string, FirestoreField>) => {

0 commit comments

Comments
 (0)