Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase: How to run 'HTTPS callable functions' locally using Cloud Functions shell?

I couldn't find a solution for this use case in Firebase official guides.

  • They are HTTPS callable functions
  • Want to run Functions locally using Cloud Functions shell to test
  • Functions save received data to Firestore
  • The 'auth' context information is also needed

My code as below. Thanks in advance.


Function :

exports.myFunction = functions.https.onCall((data, context) => {
  const id = context.auth.uid;
  const message = data.message;

  admin.firestore()...
  // Do something with Firestore //
});

Client call :

const message = { message: 'Hello.' };

firebase.functions().httpsCallable('myFunction')(message)
  .then(result => {
    // Do something //
  })
  .catch(error => {
    // Error handler //
  });
like image 614
Peter Park Avatar asked Apr 30 '18 14:04

Peter Park


People also ask

What is the difference between onCall http callable and onRequest HTTP request functions?

onRequest creates a standard API endpoint, and you'll use whatever methods your client-side code normally uses to make. HTTP requests to interact with them. onCall creates a callable. Once you get used to them, onCall is less effort to write, but you don't have all the flexibility you might be used to.

Can you run Firebase locally?

The Firebase Local Emulator Suite is a set of advanced tools for developers looking to build and test apps locally using Cloud Firestore, Realtime Database, Cloud Storage, Authentication, Cloud Functions, Pub/Sub, Firebase Hosting and Firebase Extensions.


1 Answers

There is an api exactly for this use case, see here.

I used it in javascript(Client side) as follows -

button.addEventListener('click',()=>{
//use locally deployed function
firebase.functions().useFunctionsEmulator('http://localhost:5001');
//get function reference
const sayHello = firebase.functions().httpsCallable('sayHello');
sayHello().then(result=>{
    console.log(result.data);
}) 
})

where sayHello() is the callable firebase function.

When the client is an android emulator/device. Use 10.0.2.2 in place of localhost.

Also the code for flutter would be like so -

CloudFunctions.instance.useFunctionsEmulator(origin: 'http://10.0.2.2:5000')
    .getHttpsCallable(functionName: 'sayHello')
like image 196
Mohit Mittal Avatar answered Oct 29 '22 16:10

Mohit Mittal