繁体   English   中英

如何使用从 FIrestore 读取的数据创建云 Function REST API 端点

[英]How to create Cloud Function REST API endpoints with the read data from FIrestore

我对 Cloud Functions 相当陌生。 我想做以下

  • 创建新文档时从 Firestore 读取字符串数据
  • 使用字符串创建 REST 端点,例如www.helloworld.com/\ <ReadStringData>

以下是我的代码

exports.createEndPoint = functions.firestore .document("test/{DocID}")
.onCreate((snap, context) =\> {
console.log("createEndPoint function triggered");
const newValue = snap.data();
console.log(newValue);

    const newEndPoint= newValue.endpoint;
    console.log(newEndPoint);
    
    return new Promise((resolve, reject) => {
      console.log(`/${newEndPoint}`); 
      app.get(`/${newEndPoint}`, (req, res) => {
        console.log("app.get function triggered"); 
        (async () => {
          try {
            console.log("app.get try block triggered"); 
            console.log(response);
            resolve();
          } catch (error) {
            console.log("app.get catch block triggered"); 
            console.log(error);
            reject(error);
          }
        })();
      });
    });

});

exports.app = functions.https.onRequest(app);

但是,问题是www.helloworld.com/newEndPoint从未创建过。 当我发送 GET 请求时,它超时了。

这是日志显示的内容。

日志

我尝试将 app.get 从 createEndPoint function 中取出。它没有用,因为 app.get 永远不会获取 newEndpoint。

let newEndPoint= "";

exports.createEndPoint = functions.firestore
.document("test/{DocID}")
.onCreate((snap, context) =\> {
console.log("createEndPoint function triggered");
const newValue = snap.data();
console.log(newValue);

    newEndPoint= newValue.endpoint;
    console.log(newEndPoint);

});

app.get(`/${newEndPoint}`, (req, res) =\> {
console.log("app.get function triggered");
try {
console.log("app.get try block triggered");
console.log(response);
return res.status(200).send();
} catch (error) {
console.log("app.get catch block triggered\`");
console.log(error);
return res.status(500).send(error);
}
})();
});

exports.app = functions.https.onRequest(app);

我想我的问题是如何桥接这两个功能。

你想做的事是不可能的。 您不能使用在另一个触发器中创建的数据动态创建 API 端点。 Express 应用程序的所有内容都需要在源代码的顶层定义,包括所有 URL 路径,因此它可以完全传递给functions.https.onRequest 其他触发器根本无法影响该端点——它们各自完全独立运行。

如果您想使用来自 Firestore 的数据更改端点的行为,则必须直接从端点代码查询 Firestore。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM