Reputation: 32048
How can I properly simulate a cloud function locally so that it has all data as when being invoked on firebase servers? (e.g. the
context.auth
)
I am serving my project with firebase serve
, it runs ok on http://localhost:5000/
, however, my cloud functions are being called from https://us-central1-<my-app>.cloudfunctions.net/getUser
. (The function is not even deployed.)
To avoid XY problem, I am trying to debug my function, but calling it from firebase shell results in context.auth
being undefined, same when calling via postman from http://localhost:5000/<my-app>/us-central1/getUser
.
This is my ./functions/src/index.ts
file
import * as functions from 'firebase-functions'
import admin from 'firebase-admin'
import { inspect } from 'util'
admin.initializeApp()
export const getUser = functions.https.onCall((data, context) => {
console.debug('== getUser called =========================================')
console.log('getUser', inspect(data), inspect(context.auth))
return admin.database().ref('userRights/admin').child(context.auth.uid).once('value', snapshot => {
console.log(snapshot.val())
if (snapshot.val() === true) {
return 'OK'
// return {status: 'OK'}
} else {
return 'NOK'
// return {status: 'error', code: 401, message: 'Unauthorized'}
}
})
})
file ./firebase.functions.ts
import { functions } from '~/firebase'
export const getUser = functions.httpsCallable('getUser')
Consumer ./src/pages/AdminPanel/index.tsx
import { getUser } from '~/firebase.functions'
//...
getUser({myDataX: 'asd'}).then(response => console.debug('response', response))
Upvotes: 12
Views: 2671
Reputation: 901
That worked for me, thank you @GorvGoyl!
script src="/__/firebase/init.js?useEmulator=true"></script
Upvotes: 0
Reputation: 49620
UPDATE - April/2021
As of April/2021, method useFunctionsEmulator
has been deprecated. It is suggested to use method useEmulator(host, port)
instead.
Original post:
By default, firebase serve
sends queries to CLOUD function instead of localhost, but it is possible to change it to to point to localhost.
@gregbkr found a workaround for that at this github thread.
You basically add this after firebase initialization script (firebase/init.js) in html head.
<script>
firebase.functions().useFunctionsEmulator("http://localhost:5001");
</script>
Make sure to REMOVE it when deploying to SERVER
Upvotes: 8
Reputation: 71
Just found a workaround. using fiddlers AutoResponder to redirect the function call to the local served function.
step 1
copy the target url of the function from the client
step 2
copy the local served function url
step 3
active the auto respoder and use the following rules (the second rule is also importent to allow all outher requests
Upvotes: 0
Reputation: 317828
There is currently no support for local testing of callable functions like this. The team is working on a way for you to specify the URL endpoint of a callable function so that you can redirect it to a different location for testing.
Upvotes: 5