首页 > 解决方案 > 使用请求参数从 Cloud Function 内部运行查询

问题描述

我在使用请求参数从 Cloud Functions 运行查询以构建查询表单 HTTP 调用时遇到问题。过去,我从云函数中运行查询很好,没有错误。当我尝试使用从请求中获得的参数运行查询时,出现了我的问题。

当我在函数中硬编码文档的位置时,它工作正常,但是当我尝试构建查询时,它返回状态代码 200。我还记录了构建的查询,它正在注销正确的内容,但没有数据正在被退回。它仅在文档路径被硬编码时返回数据。请参阅下面的代码。

Query looks like this
https://us-central1-<project-id>.cloudfunctions.net/getData/CollectionName/DocumentName

export const getData = functions.https.onRequest((request, response) => {

    const params = request.url.split("/");
    console.log("the params 0 "+params[0]);
    console.log("the params 1 "+params[1]);
    console.log("the params 2 "+params[2]);

    //Build up the document path
    const theQuery = "\'"+params[1]+"\/"+params[2]+"\'";
    console.log("the query "+theQuery); <-- logs out right result in the form 'Collection/Document'

    //Fetch the document
    const promise = admin.firestore().doc("\'"+params[1]+"\/"+params[2]+"\'").get() <---- This doesnt work, building the query

    //const promise = admin.firestore().doc('collectionName/DocID').get() <---- This hard coded and it works 

    promise.then(snapshot => {
        const data = snapshot.data()
        response.send(data)

    }).catch(error => {
        console.log(error)
        response.status(500).send(error);
    })

});

我尝试使用不同的方法并为数据字段命名,如下所示

Query looks like this
https://us-central1-<project-id>.cloudfunctions.net/getData?CollectionName=CName&DocumentID=Dname


export const getData = functions.https.onRequest((request, response) => {
     const collectName = request.query.CollectionName;

    const DocId = request.query.DocumentName;

    //Build up the document path
    const theQuery = "'"+collectName+"\/"+collectName+"'";
    console.log("the query "+theQuery); <---Logs out correct result

    //Fetch the document
    const promise = admin.firestore().doc(theQuery).get() <-- Building the query does not work

//const promise = admin.firestore().doc('collectionName/DocID').get() <---- This hard coded and it works 

    promise.then(snapshot => {
        const data = snapshot.data()
        response.send(data)

    }).catch(error => {
        console.log(error)
        response.status(500).send(error);
    })

});

在这两种情况下,当从 URL 构建请求时,它不会返回任何数据,也不会返回任何错误。而且我确信我试图获取的文档存在于数据库中。我错过了什么吗?

标签: javascriptfirebasegoogle-cloud-firestoregoogle-cloud-functions

解决方案


试试request.path。然后你可以获取路径组件,例如request.path.split("/")[1]

使用Express时的语法request.query是有效的。这在一些文档中被引用,但没有明确表示需要 Express。这很令人困惑。

要正确处理动态输入,您可能会更幸运地使用 Express 并创建路由和处理程序。这个Firebase 页面有一些使用它的项目的链接。

在 Firebase 上使用 Express 进行演练设置。


推荐阅读