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

时间:2018-06-27 15:22:47

标签: firebase google-cloud-functions

浏览文档时,我遇到了

  

...您可以直接通过HTTP请求或call from the client调用函数。

     

source

(引号中的链接)是关于functions.https.onCall的提及。

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

functions.https的文档为here

1 个答案:

答案 0 :(得分:20)

official documentation确实有用,但是从业余爱好者的角度来看,所描述的差异起初令人困惑。

  • 两种类型,在部署时均分配有唯一的HTTPS终结点URL,并且可以直接访问。

onCall

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

    functions.httpsCallable('getUser')({uid})
      .then(r => console.log(r.data.email))
    
  • 它由用户提供的data automagic 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)
      })
    })
    
  • context自动contains metadata处理诸如uidtoken之类的请求。
  • 输入的dataresponse对象会自动(反)序列化。

onRequest

  • Firebase onRequest Docs
  • 主要用作Express API端点。
  • 它由明确的RequestResponse对象实现。

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

在这里Is the new Firebase Cloud Functions https.onCall trigger better?

了解更多