Firebase 云函数:onRequest 和 onCall 之间的区别 [英] Firebase Cloud Functions: Difference between onRequest and onCall
问题描述
通过文档,我遇到了:
...您可以直接使用 HTTP 请求或来自客户端的调用调用函数一>.
...you can call functions directly with an HTTP request or a call from the client.
~ 来源
那里(引用中的链接)提到了functions.https.onCall
.
但是在教程这里中,另一个函数functions.https.onRequest
使用了,那么我应该使用哪一个,为什么?它们之间有什么区别/相似之处?
But in the tutorial here, another function functions.https.onRequest
is used, so which one should I use and why? What is the difference/similarity between them?
functions.https
的文档是 这里.
推荐答案
官方文档 因为这些确实很有帮助,但从业余爱好者的角度来看,所描述的差异起初令人困惑.
The official documentation for those is really helpful, but from the view of an amateur, the described differences were confusing at first.
- 两种类型在部署时都分配有唯一的 HTTPS 端点 URL,可以直接访问.
- Both types, when deployed, are assigned with a unique HTTPS endpoint URL and can be accessed directly.
可以直接从客户端应用调用(这也是主要目的).
Can be invoked (and this is also the main purpose) directly from the client app.
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
自动包含元数据 关于uid
和token
等请求.data
和 response
对象会自动(反)序列化.
context
automagically contains metadata about the request such as uid
and token
.data
and response
objects are automatically (de)serialized.- 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 触发器是否更好?
这篇关于Firebase 云函数:onRequest 和 onCall 之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!