Я пытаюсь настроить функцию firebase, которая удаляет все вложенные коллекции документа при удалении документа. Через чтение документации я пришел к этому коду:
// The Cloud Functions for Firebase SDK to create Cloud Functions and setup triggers.
const functions = require('firebase-functions');
// // Create and Deploy Your First Cloud Functions
// // https://firebase.google.com/docs/functions/write-firebase-functions
//
// exports.helloWorld = functions.https.onRequest((request, response) => {
// response.send("Hello from Firebase!");
// });
exports.DeleteColletionFunction = functions.firestore
.document('exampleCollection/{exampleID}')
.onDelete((snap, context) => {
// Get an object representing the document prior to deletion
// e.g. {'name': 'Marie', 'age': 66}
const deletedValue = snap.data();
deleteCollection()
});
function deleteCollection(db, collectionPath, batchSize) {
var collectionRef = db.collection(collectionPath);
var query = collectionRef.orderBy('__name__').limit(batchSize);
return new Promise((resolve, reject) => {
deleteQueryBatch(db, query, batchSize, resolve, reject);
});
}
function deleteQueryBatch(db, query, batchSize, resolve, reject) {
query.get()
.then((snapshot) => {
// When there are no documents left, we are done
if (snapshot.size == 0) {
return 0;
}
// Delete documents in a batch
var batch = db.batch();
snapshot.docs.forEach((doc) => {
batch.delete(doc.ref);
});
return batch.commit().then(() => {
return snapshot.size;
});
}).then((numDeleted) => {
if (numDeleted === 0) {
resolve();
return;
}
// Recurse on the next process tick, to avoid
// exploding the stack.
process.nextTick(() => {
deleteQueryBatch(db, query, batchSize, resolve, reject);
});
})
.catch(reject);
}
Я никогда раньше не работал с облачными функциями и поэтому не уверен, что мне делать дальше. Я вижу, что для использования функции удаления коллекции необходимо передать базу данных, collectionPath и batchSize. Какие значения будут правильными для передачи в этом случае?
Должен ли я использовать эту строку кода для получения базы данных пожарного магазина?
const database = admin.firestore();
Я также получаю некоторые ошибки при копировании этой функции из документации:
Ожидается '===' и вместо этого видит '=='
[eslint] Избегайте вложенных обещаний. (Обещание / нет вложенности)
(параметр) снимок: любой
[eslint] Каждое then () должно возвращать значение или throw (обещание / всегда возвращаемый)
(параметр) разрешение: любой
Вот скриншот, чтобы увидеть расположение ошибок:
Спасибо за вашу помощь!
UPDATE:
Я изменил некоторые вещи (добавив обещание):
// The Cloud Functions for Firebase SDK to create Cloud Functions and setup triggers.
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
// // Create and Deploy Your First Cloud Functions
// // https://firebase.google.com/docs/functions/write-firebase-functions
//
// exports.helloWorld = functions.https.onRequest((request, response) => {
// response.send("Hello from Firebase!");
// });
exports.DeleteColletionFunction = functions.firestore
.document('exampleCollection/{exampleID}')
.onDelete((snap, context) => {
// Get an object representing the document prior to deletion
// e.g. {'name': 'Marie', 'age': 66}
const deletedValue = snap.data();
const exampleID = context.params.exampleID;
const BATCH_SIZE = 500;
const database = admin.firestore();
const commentsRef = database.collection('exampleCollection').doc(exampleID).collection("comments");
commentsRef.doc('main').delete();
const exampleRef = database.collection('exampleCollection').doc(exampleID).collection("exampleSubCollection");
const deleteExamples = deleteCollection(database, exampleRef, BATCH_SIZE)
return Promise.all([deleteExamples]);
});
/**
* Delete a collection, in batches of batchSize. Note that this does
* not recursively delete subcollections of documents in the collection
*/
function deleteCollection (db, collectionRef, batchSize) {
var query = collectionRef.orderBy('__name__').limit(batchSize)
return new Promise(function (resolve, reject) {
deleteQueryBatch(db, query, batchSize, resolve, reject)
})
}
function deleteQueryBatch (db, query, batchSize, resolve, reject) {
query.get()
.then((snapshot) => {
// When there are no documents left, we are done
if (snapshot.size === 0) {
return 0
}
// Delete documents in a batch
var batch = db.batch()
snapshot.docs.forEach(function (doc) {
batch.delete(doc.ref)
})
return batch.commit().then(function () {
return snapshot.size
})
}).then(function (numDeleted) {
if (numDeleted <= batchSize) {
resolve()
return
}
else {
// Recurse on the next process tick, to avoid
// exploding the stack.
return process.nextTick(function () {
deleteQueryBatch(db, query, batchSize, resolve, reject)
})
}
})
.catch(reject)
}
Теперь я получаю ошибки в консоли Firebase:
ReferenceError: exampleID не определен
at exports.DeleteColletionFunction.functions.firestore.document.onDelete (/user_code/index.js:26:66)
на объекте. (/User_code/node_modules/firebase-functions/lib/cloud-functions.js:112:27)
на следующем (родном)
в /user_code/node_modules/firebase-functions/lib/cloud-functions.js:28:71
в __awaiter (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:24:12)
в cloudFunction (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:82:36)
по адресу /var/tmp/worker/worker.js:728:24
at process._tickDomainCallback (internal / process / next_tick.js: 135: 7)
Спасибо за вашу помощь!