使用可呼叫的 Cloud 函式刪除資料

本頁面說明如何使用可呼叫的 Cloud 函式 刪除資料。部署這個函式後 您可以直接從行動應用程式或網站呼叫 以遞迴方式刪除文件和集合。舉例來說,您可以使用 這項解決方案可讓特定使用者刪除整個集合。

如要瞭解其他刪除集合的方式,請參閱「刪除資料」。

解決方案:使用可呼叫的 Cloud 函式刪除資料

難以從資源有限的行動應用程式中刪除整個集合 導入 的原因如下:

  • 沒有任何作業會以不可分割的形式刪除集合。
  • 刪除文件並不會刪除其子集合中的文件。
  • 如果您的文件含有動態子集合,可能會難以判斷 要刪除的資料。
  • 如要刪除 500 份文件的集合,必須建立多份文件 批次寫入作業或數百個單一刪除。
  • 許多應用程式不適合讓使用者刪除, 整個集合。

幸好,您可以編寫可呼叫的 Cloud 函式 ,安全地刪除整個集合或集合樹狀圖。下列 Cloud 函式實作可呼叫函式 表示可以從你的行動應用程式或網站直接呼叫 與本機函式搭配使用

如要部署函式並試用,請參閱程式碼範例

Cloud 函式

下方的 Cloud 函式會刪除集合及其所有子系。

您不必為 Cloud 函式實作自己的遞迴刪除邏輯, 您可以使用firestore:delete Firebase 指令列介面 (CLI)。您可以匯入 使用 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 取得該函式的參照 並傳送必要參數:

Web
/**
 * 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);
        });
}
Swift
注意:這項產品不適用於 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 執行可呼叫的 Cloud 函式,就能驗證使用者的服務 狀態,且 path 參數會順暢地傳遞至遠端函式。 當函式執行完成後,用戶端會收到 或例外狀況。如要瞭解如何從以下項目呼叫 Cloud 函式: Android、Apple 或其他平台:請參閱說明文件

限制

上述解決方案示範如何從可呼叫的集合中刪除集合 函式,但請注意下列限制:

  • 一致性 - 上述程式碼會一次刪除一個文件。如果發生以下情況: 如果有執行中的刪除作業,您的結果可能會反映 也就是只刪除部分指定文件的部分完整狀態。 而且不保證刪除作業成功,或 因此請準備好處理部分刪除的情況。
  • 逾時 - 上述函式已設為最多執行 540 個 逾時。刪除代碼可以刪除 4000 錯誤 在理想情況下,每秒提交的文件數量如果您需要刪除超過 2,000,000 份文件,您應考慮自行執行這些作業 這樣就不會逾時。以下舉例說明 如要從自己的伺服器收集集合,請參閱刪除集合一文。