浏览文档,我遇到:
那里...您可以通过 HTTP 请求或来自客户端的 调用直接调用函数。
~
(引用中的链接)提到了functions.https.onCall
。但是在教程
here中,使用了另一个函数functions.https.onRequest
,那么我应该使用哪个函数,为什么?它们之间有什么区别/相似之处?
functions.https
的文档位于这里。
官方文档确实很有帮助,但从业余爱好者的角度来看,所描述的差异一开始很令人困惑。
这两种类型在部署时都分配有唯一的 HTTPS 端点 URL,并且可以使用 https 客户端直接访问。
应该被称为的方式有一个重要的区别。
onCall
:来自客户的
firebase.functions()
onRequest
:通过标准 https 客户端(例如 JS 中的
fetch()
API)
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
对象会自动(反)序列化。
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))
})
onCall和onRequest之间的主要区别在于它们从客户端调用的方式。 当您使用 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 的更多信息:
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 ...
});
我在文档中找不到此内容,如果我遗漏了某些内容,请告诉我。