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

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

通过文档,我遇到了:

...您可以直接使用HTTP请求或来自客户端调用来调用函数.

来源

那里(引用中的链接)是一个提及functions.https.onCall.

但是在这里的教程中,使用了另一个函数functions.https.onRequest,我应该使用哪个函数?为什么?它们之间有什么区别/相似之处?

文档functions.https在这里.

Qwe*_*rty 39

这些官方文档确实很有帮助,但从业余人士的角度来看,所描述的差异最初令人困惑.

  • 这两种类型在部署时都会分配一个唯一的HTTPS端点URL,并且可以直接访问.

随传随到

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

    functions.httpsCallable('getUser')({uid})
      .then(r => console.log(r.data.email))
    
    Run Code Online (Sandbox Code Playgroud)
  • 它由用户提供data自动化实现 context.

    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)
      })
    })
    
    Run Code Online (Sandbox Code Playgroud)
  • context自动的包含元数据有关请求如uidtoken.
  • 输入dataresponse对象自动(反)序列化.

根据要求

  • 主要用作Express API端点.
  • 它用express RequestResponseobjects实现.

    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))
    })
    
    Run Code Online (Sandbox Code Playgroud)
  • 取决于用户提供的授权标头.
  • 您负责输入和响应数据.

阅读更多内容新的Firebase云功能https.onCall触发器更好吗?

  • 如何调用 onRequest 函数?或者 onCall 函数是唯一可以从客户端调用的函数? (2认同)
  • onRequest 创建一个标准 API 端点,您将使用客户端代码通常使用的任何方法。与它们交互的 HTTP 请求。onCall 创建一个可调用对象。一旦您习惯了它们,编写 onCall 就更省力了,但您不具备您可能习惯的所有灵活性。 (2认同)

R..*_*... 15

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

exports.addMessage = functions.https.onCall((data, context) => {
  // ...
  return ...
});
Run Code Online (Sandbox Code Playgroud)

您可以使用 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.        
  });
Run Code Online (Sandbox Code Playgroud)

onCall 的更多信息:https ://firebase.google.com/docs/functions/callable

但是如果你使用onRequest定义你的函数,例如

exports.addMesssage = functions.https.onRequest((req, res) { 
  //...   
  res.send(...); 
}
Run Code Online (Sandbox Code Playgroud)

您可以使用普通的 JS fetch API 调用它(无需在客户端代码上导入 firebase 函数客户端库)例如

fetch('<your cloud function endpoint>/addMessage').then(...)
Run Code Online (Sandbox Code Playgroud)

这是您在决定如何在服务器上定义函数时需要考虑的巨大差异。

onRequest 的更多信息: https: //firebase.google.com/docs/functions/http-events