How to delete document collection and all nested data from auth.user.onDelete trigger

Viewed 637

Currently, the logic for deleting user data is the following:

import * as admin from 'firebase-admin';
import * as functions from 'firebase-functions';

const firestore_tools = require('firebase-tools');

admin.initializeApp();

const Auth = admin.auth();
const UsersCollection = admin.firestore().collection(`users`);

exports.deleteUserDocuments = functions.auth.user().onDelete((user) => {
  const userID = user.uid;

  UsersCollection.doc(userID)
      .delete({})
      .catch(error => {
        return error
      });
});

But since the user document record contains nested collections that contain other documents and collections they are still preserved due to the fact: When you delete a document, Cloud Firestore does not automatically delete the documents within its sub-collections

I've researched a bit and found a documentation on how to create a callable function: https://firebase.google.com/docs/firestore/solutions/delete-collections

But I wonder is it possible to have this logic instead executed from the auth.user.onDelete trigger?

Update with the Solution

const firestore_tools = require('firebase-tools');

exports.deleteUserDocuments = functions.auth.user().onDelete((user) => {
    const userID = user.uid;
    const project = process.env.GCLOUD_PROJECT;
    const token = functions.config().ci_token;
    const path = `/users/${userID}`;

    console.log(`User ${userID} has requested to delete path ${path}`);

    return firestore_tools.firestore
        .delete(path, {
            project,
            token,
            recursive: true,
            yes: true,
        })
        .then(() => {
            console.log(`User data with ${userID} was deleted`);
        })
});
1 Answers

You can run whatever code you want in whatever trigger you want. The type of the trigger doesn't have any bearing on the type of code you can run.

Related