async function processWrite()

in firestore-send-email/functions/lib/index.js [244:287]


async function processWrite(change) {
    if (!change.after.exists) {
        return null;
    }
    if (!change.before.exists && change.after.exists) {
        return processCreate(change.after);
    }
    const payload = change.after.data();
    if (!payload.delivery) {
        logs.missingDeliveryField(change.after.ref);
        return null;
    }
    switch (payload.delivery.state) {
        case "SUCCESS":
        case "ERROR":
            return null;
        case "PROCESSING":
            if (payload.delivery.leaseExpireTime.toMillis() < Date.now()) {
                // Wrapping in transaction to allow for automatic retries (#48)
                return admin.firestore().runTransaction((transaction) => {
                    transaction.update(change.after.ref, {
                        "delivery.state": "ERROR",
                        // Keeping error to avoid any breaking changes in the next minor update.
                        // Error to be removed for the next major release.
                        error: "Message processing lease expired.",
                        "delivery.error": "Message processing lease expired.",
                    });
                    return Promise.resolve();
                });
            }
            return null;
        case "PENDING":
        case "RETRY":
            // Wrapping in transaction to allow for automatic retries (#48)
            await admin.firestore().runTransaction((transaction) => {
                transaction.update(change.after.ref, {
                    "delivery.state": "PROCESSING",
                    "delivery.leaseExpireTime": admin.firestore.Timestamp.fromMillis(Date.now() + 60000),
                });
                return Promise.resolve();
            });
            return deliver(payload, change.after.ref);
    }
}