3
votes

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
what is firestore_tools and where do you get it from?Leonardo Rignanese
@LeonardoRignanese you can get the package from, there is also a nice description of the use cases ;-) npmjs.com/package/firestore-toolsvolna
The important thing is its a node module so the import will not work in the node version that default FF function setup. So you will have to require it const firestore_tools = require('firebase-tools');volna
Thanks, I suggest you tu update the solution above (:Leonardo Rignanese
Done, hope it helped you :-)volna

1 Answers

2
votes

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.