Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

157
Visualizações
Call Firebase Function in javascript

I have a Cloud Function deployed to Firebase, and my iOS and Android apps use it fine, all works good. Below is the function deployed.

const admin = require('firebase-admin');
const firebase_tools = require('firebase-tools');
const functions = require('firebase-functions');

admin.initializeApp();


exports.deleteUser = functions
  .runWith({
    timeoutSeconds: 540,
    memory: '2GB'
  })
  .https.onCall((data, context) => {

  const userId = context.auth.uid;
  var promises = [];

  // DELETE DATA
  var paths = ['users/' + userId, 'messages/' + userId, 'chat/' + userId, 'like/' + userId];

  paths.forEach((path) => {
    promises.push(
      recursiveDelete(path).then(  () => {
          return 'success';
        }
      ).catch( (error) => {
        console.log('Error deleting user data: ', error);
      })
    );
  });

  // DELETE FILES
  const bucket = admin.storage().bucket();
  var image_paths = ["avatar/" + userId, "avatar2/" + userId, "avatar3/" + userId];
  image_paths.forEach((path) => {
    promises.push(
      bucket.file(path).delete().then(  () => {
            return 'success';
          }
         ).catch( (error) => {
          console.log('Error deleting user data: ', error);
        })
      );
    });

  // DELETE USER
  promises.push(
    admin.auth().deleteUser(userId)
    .then( () => {
      console.log('Successfully deleted user');
      return true;
    })
    .catch((error) => {
      console.log('Error deleting user:', error);
    })
  );

  return Promise.all(promises).then(() => {
    return true;
  }).catch(er => {
      console.error('...', er);
  });
});




function recursiveDelete(path, context) {
    return firebase_tools.firestore
    .delete(path, {
      project: process.env.GCLOUD_PROJECT,
      recursive: true,
      yes: true,
      token: functions.config().fb.token
    })
    .then(() => {

      return {
        path: path
      }
    }).catch( (error) => {
      console.log('error: ', error);
      return error;
    });
  }
  // [END recursive_delete_function]

How can I execute this script with a button in javascript? A standard .js file locally? I also need to be able to pass in a userId manually.

In my react native app I call it like:

const deleteUser = async () => {
        functions().httpsCallable('deleteUser')()
        signOut();
    } 

But in my javascript file (nothing to do with my react native app), I need to pass in a userId and call that same function to delete the user.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

There are a number of ways to go about executing a cloud function within your client side application.

Depending on how you have the function setup, you can either pass in a parameter or data via the body in the request.

For example, using express (similar to other frameworks):


// fetch(‘api.com/user/foo’, {method: ‘DELETE’} )
app.delete(‘/user/:uid’, (req, res) => {
  const uid = req.params.uid;

  // execute function
})

// fetch(‘api.com/user’, {method: ‘DELETE’, body: { uid: foo } } )
app.delete(‘/user’, (req, res) => {
  const uid = req.body.uid;

  // execute function
})

// fetch(‘api.com/user?uid=foo’, {method: ‘DELETE’} )
app.delete(‘/user’, (req, res) => {
  const uid = req.query.uid;

  // execute function
})

Full Example:

<button onclick=“deleteUser(uid)”>Delete Me</button>

<script>

function deleteUser(uid) {
  fetch(`api.com/user/${uid}`, { method: ‘DELETE’});

  // rest of function
}

</script>

about 4 years ago · Juan Pablo Isaza Relatório

0

Was able to call my firebase function with the following:

userId was accessible like so const { userId } = data; from my function script

async function deleteAccount(userId) {
  const deleteUser = firebase.functions().httpsCallable("deleteUser");
  deleteUser({ userId }).then((result) => {
    console.log(result.data);
  });
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda