Firebase 云功能:onRequest 和 onCall 之间的区别

问题描述 投票:0回答:3

浏览文档,我遇到:

...您可以通过 HTTP 请求或来自客户端的 调用直接调用函数。

~

来源

那里

(引用中的链接)提到了functions.https.onCall

但是在教程

here中,使用了另一个函数functions.https.onRequest

,那么我应该使用哪个函数,为什么?它们之间有什么区别/相似之处?

functions.https

的文档位于
这里

javascript firebase google-cloud-functions
3个回答
216
投票
这些的

官方文档确实很有帮助,但从业余爱好者的角度来看,所描述的差异一开始很令人困惑。

  • 这两种类型在部署时都分配有唯一的 HTTPS 端点 URL,并且可以使用 https 客户端直接访问。

  • 但是,它们

    应该被称为的方式有一个重要的区别。

    • onCall
      :来自客户的
      firebase.functions()
      
      
    • onRequest
      :通过标准 https 客户端(例如 JS 中的 
      fetch()
       API)
通话中

  • 可以直接从客户端应用程序调用(这也是主要目的)。

    functions.httpsCallable('getUser')({uid}) .then(r => console.log(r.data.email))
    
    
  • 它是通过用户提供的

    data

    automagiccontext
    实现的。

    export const getUser = functions.https.onCall((data, context) => { if (!context.auth) return {status: 'error', code: 401, message: 'Not signed in'} return new Promise((resolve, reject) => { // find a user by data.uid and return the result resolve(user) }) })
    
    
  • context

    自动
    包含有关请求的元数据,例如uid
    token

  • 输入

    data

    response
     对象会自动(反)序列化。

按要求

  • Firebase onRequest 文档

  • 主要用作 Express API 端点。

  • 它是用express

    Request

    Response
    对象实现的。

    export const getUser = functions.https.onRequest((req, res) => { // verify user from req.headers.authorization etc. res.status(401).send('Authentication required.') // if authorized res.setHeader('Content-Type', 'application/json') res.send(JSON.stringify(user)) })
    
    
  • 取决于用户提供的授权标头。

  • 您负责输入和响应数据。

在此处阅读更多内容

新的 Firebase Cloud Functions https.onCall 触发器更好吗?


17
投票
客户端的

onCallonRequest之间的主要区别在于它们从客户端调用的方式。 当您使用 onCall 定义函数时,例如

exports.addMessage = functions.https.onCall((data, context) => { // ... return ... });
您可以使用 firebase 函数客户端 SDK 在客户端调用它,例如

// on the client side, you need to import functions client lib // then you invoke it like this: const addMessage = firebase.functions().httpsCallable('addMessage'); addMessage({ text: messageText }) .then((result) => { // Read result of the Cloud Function. });
有关 onCall 的更多信息:

https://firebase.google.com/docs/functions/callable

但是如果您使用

onRequest 定义函数,例如

exports.addMesssage = functions.https.onRequest((req, res) { //... res.send(...); }
您可以使用普通的 JS fetch API 调用它(无需在客户端代码上导入 firebase 函数客户端库),例如

fetch('<your cloud function endpoint>/addMessage').then(...)
这是您在决定如何在服务器上定义函数时需要考虑的巨大差异。

有关 onRequest 的更多信息:

https://firebase.google.com/docs/functions/http-events


0
投票
我遇到的一个警告是,

data

中的
functions.https.onCall
参数实际上是原始请求。要访问有效负载,我们必须访问输入的 
data
 字段。

示例

客户端将有效负载发送到云函数:

const callFunction = httpsCallable(functions, 'addMessage'); const result = await callFunction({payload: 'payload'});
在云函数中访问payload:

exports.addMessage = functions.https.onCall((rawRequest, context) => { const payload = rawRequest.data.payload; return ... });
我在文档中找不到此内容,如果我遗漏了某些内容,请告诉我。

© www.soinside.com 2019 - 2024. All rights reserved.