firebase服务:从本地服务的应用中,调用本地服务的功能

Qwe*_*rty 8 firebase google-cloud-functions

如何在本地正确模拟云功能,以使其具有在Firebase服务器上调用时的所有数据?(例如context.auth

我正在为我的项目提供服务firebase serve,它可以正常运行http://localhost:5000/,但是,我的云函数正在从中调用https://us-central1-<my-app>.cloudfunctions.net/getUser。(该功能甚至没有部署。)

为避免XY问题,我尝试调试函数,但从firebase shell调用该函数会导致context.auth未定义,与从中通过邮递员调用时相同http://localhost:5000/<my-app>/us-central1/getUser

这是我的./functions/src/index.ts档案

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'}
    }
  })
})
Run Code Online (Sandbox Code Playgroud)

文件 ./firebase.functions.ts

import { functions } from '~/firebase'
export const getUser = functions.httpsCallable('getUser')
Run Code Online (Sandbox Code Playgroud)

消费者 ./src/pages/AdminPanel/index.tsx

import { getUser } from '~/firebase.functions'
//...
getUser({myDataX: 'asd'}).then(response => console.debug('response', response))
Run Code Online (Sandbox Code Playgroud)

Jer*_*yal 7

更新 - 2021 年 4 月

截至 2021 年 4 月,方法useFunctionsEmulator已被弃用。建议改用方法useEmulator(host, port)


原帖:

默认情况下,firebase serve将查询发送到 CLOUD 函数而不是 localhost,但可以将其更改为指向 localhost。

@gregbkr 在此github线程中找到了解决方法。

您基本上是在 html head 中的 firebase 初始化脚本 (firebase/init.js) 之后添加它。

<script>
   firebase.functions().useFunctionsEmulator("http://localhost:5001");
</script>
Run Code Online (Sandbox Code Playgroud)

确保在部署到 SERVER 时删除它


Dou*_*son 5

当前不支持对像这样的可调用函数进行本地测试。团队正在为您指定一种可调用函数的URL端点,以便您可以将其重定向到其他位置进行测试。