【问题标题】:How to stop Firebase Functions from executing local functions once per every Cloud Function?如何阻止 Firebase 函数在每个 Cloud Functions 中执行一次本地函数?
【发布时间】:2019-04-26 22:27:55
【问题描述】:

所以,我正在使用 spotify API 进行搜索。在本地,我使用 tsc 和 node 测试了我的代码;一切都按预期进行。

但是,当我部署我的 index.ts 时,日志会显示一些奇怪的行为。

在文件的顶部,我有以下内容:

 //Load libraries
const functions      = require('firebase-functions');
const admin          = require('firebase-admin');
const firebase       = require("firebase");
const stripe         = require('stripe')(functions.config().stripe.token)
const SpotifyWebApi    = require('spotify-web-api-node');

//Initialize app
const APP = { 
  apiKey: "my-API-Key",  
  authDomain: "My domain auth",
  databaseURL: "my databse url",
  storageBucket: "my bucket",
  messagingSenderId: "my messenger ID"
}

//The Client Credential Flow for Spotify API
const spotifyApi = new SpotifyWebApi({
    clientId: 'My cliend ID',
    clientSecret: 'My-secret-Key'
});

// Retrieve an access token for Spotify.
spotifyApi.clientCredentialsGrant().then(function (data) {
    console.log('All data Spotify API: ' + data.body )
    console.log('The access token expires in ' + data.body['expires_in']);
    console.log('The access token is ' + data.body['access_token']);
    // Save the access token so that it's used in future calls
    spotifyApi.setAccessToken(data.body['access_token']);
}, function (err) {
    console.log('Something went wrong when retrieving an access token', err);
})

firebase.initializeApp(APP);
admin.initializeApp(APP)

问题是日志表明我的 index.js 文件中的每个 Firebase-Cloud 函数运行一次 spotify 访问令牌函数。我收到了十几个令牌,每个都显示在日志中,由我的一个 firebase-cloud 函数调用。

当我上传整个 index.ts 时,如何告诉 Firebase 函数只运行一次此代码?当我上传单个函数时不运行它;这也很有用。

谢谢。

【问题讨论】:

    标签: javascript typescript firebase google-cloud-functions


    【解决方案1】:

    index.js 的顶级代码在 Cloud Functions 实例化的每个容器中运行,以确保正确初始化容器以运行您的函数。由于 Cloud Functions 可能会实例化多个容器,因此代码可能会运行多次。

    无法控制 Cloud Functions 实例化的容器数量。如果您不希望代码在每个容器中运行,请不要将其设置为 index.js 中的顶级代码。

    例如,您可以在调用函数时按需创建 Spotify 凭据。这可确保凭据仅在实际调用您的函数的容器上,尽管这确实意味着在容器中首次调用您的函数将需要获取 Spotify 凭据,因此需要更长的时间才能完成。

    【讨论】:

    • 这很有启发性。是否有一种简单的编程方式可以说“仅在包含此特定功能的容器上运行此高级代码”?我可以用条件来破解它,但是如果有一个漂亮的 Firebase 解决方案,我想知道它;另外,如果没有,请求一个(一个简单的解决方案)是否合理?
    • 不,没有办法配置它。这就是为什么你必须从每个需要它的函数按需初始化它。
    • 请考虑在不久的将来添加这样的东西。维护跨许多独立环境同步的不同 API 的令牌状态是一件痛苦的事。
    • 我建议你file a feature request
    • 完成。 (^_^) [^_^]
    猜你喜欢
    • 2018-10-10
    • 1970-01-01
    • 2023-04-10
    • 1970-01-01
    • 2021-04-22
    • 2019-09-17
    • 1970-01-01
    • 2022-12-19
    • 1970-01-01
    相关资源
    最近更新 更多