使用可調用雲函數刪除數據

該頁面介紹如何使用可呼叫的雲端函數刪除資料。部署此功能後,您可以直接從行動應用程式或網站呼叫它以遞歸刪除文件和集合。例如,您可以使用此解決方案為選定的使用者提供刪除整個集合的能力。

有關刪除集合的其他方法,請參閱刪除資料

解決方案:使用可調用的雲端函數刪除數據

由於以下原因,從資源有限的行動應用程式中刪除整個集合可能很難實施:

  • 沒有原子刪除集合的操作。
  • 刪除文件不會刪除其子集合中的文件。
  • 如果您的文件具有動態子集合,則可能很難知道要刪除給定路徑的哪些資料。
  • 刪除超過 500 個文件的集合需要多次批次寫入作業或數百次單次刪除。
  • 在許多應用程式中,授予最終使用者刪除整個集合的權限是不合適的。

幸運的是,您可以編寫可呼叫的雲端函數來運行整個集合或集合樹的安全且高效能的刪除。下面的雲端函數實作了一個可呼叫函數,這意味著它可以像本地函數一樣直接從您的行動應用程式或網站呼叫。

若要部署該功能並嘗試演示,請參閱範例程式碼

雲端功能

下面的雲函數刪除一個集合及其所有後代。

您可以利用 Firebase 命令列介面 (CLI) 中的firestore:delete指令,而不是為 Cloud Function 實作自己的遞歸刪除邏輯。您可以使用firebase-tools套件將 Firebase CLI 的任何功能匯入到 Node.js 應用程式中。

Firebase CLI 使用 Cloud Firestore REST API 尋找指定路徑下的所有文件並單獨刪除它們。此實作不需要了解應用程式的特定資料層次結構,甚至會尋找並刪除不再具有父級的「孤立」文件。

Node.js

/**
 * Initiate a recursive delete of documents at a given path.
 * 
 * The calling user must be authenticated and have the custom "admin" attribute
 * set to true on the auth token.
 * 
 * This delete is NOT an atomic operation and it's possible
 * that it may fail after only deleting some documents.
 * 
 * @param {string} data.path the document or collection path to delete.
 */
exports.recursiveDelete = functions
  .runWith({
    timeoutSeconds: 540,
    memory: '2GB'
  })
  .https.onCall(async (data, context) => {
    // Only allow admin users to execute this function.
    if (!(context.auth && context.auth.token && context.auth.token.admin)) {
      throw new functions.https.HttpsError(
        'permission-denied',
        'Must be an administrative user to initiate delete.'
      );
    }

    const path = data.path;
    console.log(
      `User ${context.auth.uid} has requested to delete path ${path}`
    );

    // Run a recursive delete on the given document or collection path.
    // The 'token' must be set in the functions config, and can be generated
    // at the command line by running 'firebase login:ci'.
    await firebase_tools.firestore
      .delete(path, {
        project: process.env.GCLOUD_PROJECT,
        recursive: true,
        force: true,
        token: functions.config().fb.token
      });

    return {
      path: path 
    };
  });

客戶端調用

若要呼叫函數,請從 Firebase SDK 取得對該函數的參考並傳遞所需的參數:

網路
/**
 * Call the 'recursiveDelete' callable function with a path to initiate
 * a server-side delete.
 */
function deleteAtPath(path) {
    var deleteFn = firebase.functions().httpsCallable('recursiveDelete');
    deleteFn({ path: path })
        .then(function(result) {
            logMessage('Delete success: ' + JSON.stringify(result));
        })
        .catch(function(err) {
            logMessage('Delete failed, see console,');
            console.warn(err);
        });
}
迅速
注意:此產品不適用於 watchOS 和 App Clip 目標。
    // Snippet not yet written
    
Objective-C
注意:此產品不適用於 watchOS 和 App Clip 目標。
    // Snippet not yet written
    

Kotlin+KTX

/**
 * Call the 'recursiveDelete' callable function with a path to initiate
 * a server-side delete.
 */
fun deleteAtPath(path: String) {
    val deleteFn = Firebase.functions.getHttpsCallable("recursiveDelete")
    deleteFn.call(hashMapOf("path" to path))
        .addOnSuccessListener {
            // Delete Success
            // ...
        }
        .addOnFailureListener {
            // Delete Failed
            // ...
        }
}

Java

/**
 * Call the 'recursiveDelete' callable function with a path to initiate
 * a server-side delete.
 */
public void deleteAtPath(String path) {
    Map<String, Object> data = new HashMap<>();
    data.put("path", path);

    HttpsCallableReference deleteFn =
            FirebaseFunctions.getInstance().getHttpsCallable("recursiveDelete");
    deleteFn.call(data)
            .addOnSuccessListener(new OnSuccessListener<HttpsCallableResult>() {
                @Override
                public void onSuccess(HttpsCallableResult httpsCallableResult) {
                    // Delete Success
                    // ...
                }
            })
            .addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    // Delete failed
                    // ...
                }
            });
}

透過使用可呼叫雲端函數的客戶端SDK,將使用者的身份驗證狀態和path參數無縫傳遞到遠端函數。當函數完成時,客戶端將收到包含結果或異常的回呼。若要了解如何從 Android、Apple 或其他平台呼叫雲端函數,請閱讀文件

限制

上面顯示的解決方案演示了從可呼叫函數中刪除集合,但您應該注意以下限制:

  • 一致性- 上面的程式碼一次刪除一個文件。如果您在正在進行刪除操作時進行查詢,您的結果可能會反映部分完成的狀態,其中僅刪除了一些目標文件。也不能保證刪除操作會統一成功或失敗,因此請準備好處理部分刪除的情況。
  • 超時- 上述函數配置為在逾時之前最多運行 540 秒。刪除程式碼在最好的情況下每秒可以刪除4000個文件。如果您需要刪除超過 2,000,000 個文檔,您應該考慮在您自己的伺服器上執行該操作,以免逾時。有關如何從您自己的伺服器刪除集合的範例,請參閱刪除集合