【问题标题】:How to setup caching for specific headers in Firebase Cloud Functions?如何为 Firebase Cloud Functions 中的特定标头设置缓存?
【发布时间】:2020-05-23 17:52:38
【问题描述】:

我不确定这是否可能。我正在向外部 api 发出请求,并且在来自我的应用程序的每个请求中,我将用户的查询传递到 Cloud Function (Typescript) 中的自定义 'query' 标头中。 ⤵

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

    // : Reads request query data from user
    const query = request.headers.query;

...

我尝试设置缓存,以便在每个查询中单独缓存结果,但它似乎不起作用。 ~

(缓存确实可以在没有设置不同标头的情况下工作,但它只缓存第一个搜索结果)
(所有请求都以GET 发送)

这是将 'query' 标头设置为缓存的可变规则的块(用 Typescript 编写)。 ⤵

...

    return await admin.auth().verifyIdToken(tokenId) // : Authenticates response
        .then(() => {

            // : Set cache-control
            console.log(request.headers);
            response.set('Vary', 'Accept-Encoding, query');
            response.set("Cache-Control", "public, s-maxage=600");
            response.set("Access-Control-Allow-Origin", "*");
            response.set("Access-Control-Allow-Methods", "GET");

            // : Grab API search data
            axio.get(urlAssembler).then(APIData => {
                response.status(200).send(APIData.data);
            }).catch(error => console.log(error));

        })
        .catch((err) => response.status(401).send(err));

...

我在 Cloud Functions w/ Firebase 而不是 Cloud Functions with Firebase Hosting 上进行了此设置。我想知道那里是否有区别,但似乎没有。

在我的firebase.json 中,我注意到它是为 Cloud Functions 而不是为 Firebase 托管设置的。也许我需要将其设置为 Firebase Hosting 来为那里的标头定义缓存控制?

这是我的 firebase.json ⤵

{
  "functions": {
    "predeploy": [
      "npm --prefix \"$RESOURCE_DIR\" run lint",
      "npm --prefix \"$RESOURCE_DIR\" run build"
    ]
  }
}

【问题讨论】:

    标签: firebase google-cloud-functions firebase-hosting


    【解决方案1】:

    我就此联系了 Firebase 支持,帮助我的人说需要使用 Firebase 托管,以便根据上述标头进行缓存。

    我还没有测试过,所以一旦我测试过,我会更新这个答案以确认它有效。

    有一篇文章是由 Firebase 支持帮助我的个人向我推荐的,关于如何cache within a Cloud Function,但我不相信这会使用 CDN。

    【讨论】:

    • 我没有得到 Firebase Hosting 需要使用部分。我已经部署了托管以及功能,但仍然无法正常工作:/如果你有一个工作示例,我可以得到一个工作示例吗?
    • 嗨,安娜,我还没有尝试过。据我了解,如果您正确设置了托管和功能,那么您应该能够根据您指定的请求标头确定缓存行为 --> firebase.google.com/docs/hosting/manage-cache
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-23
    • 2019-01-14
    • 2017-11-29
    • 1970-01-01
    • 1970-01-01
    • 2017-11-28
    • 1970-01-01
    相关资源
    最近更新 更多