【问题标题】:Make context available in Google Cloud function triggered by Storage在由 Storage 触发的 Google Cloud 函数中提供上下文
【发布时间】:2021-01-01 05:52:26
【问题描述】:

我正在 Google Cloud Function 中尝试此代码,由节点 10 的 Cloud Storage 触发。

我不确定如何使上下文可用。 Event: ${context.eventId}

我试过了:module.exports.getDevices(context) = getDevices;

我试过了:module.exports.getDevices = getDevices(context);

async function getDevices() {
    console.log(`  Event: ${context.eventId}`);
    const cloudRegion = '....';
    const projectId = '.....';
    const registryId = '.....';
    const iot = require('@google-cloud/iot');
    const iotClient = new iot.v1.DeviceManagerClient({});

    const parentName = iotClient.registryPath(projectId, cloudRegion, registryId);

    try {
      const responses = await iotClient.listDevices({parent: parentName});
  
      const devices = responses[0];     

      if (devices.length > 0) {
    console.log('Current devices in registry:');
      } else {
        console.log('No devices in registry.');
      }

      for (let i = 0; i < devices.length; i++) {
        const device = devices[i];
        console.log(`Device ${i}: `, device);
    }
        } catch (err) {
          console.error('Could not list devices', err);
        }

}

module.exports.getDevices = getDevices;

另外,这可行,但我想要和前一个一样的异步功能:

exports.helloGCS = (file, context) => {
  console.log(`  Event: ${context.eventId}`);
};

【问题讨论】:

    标签: javascript node.js google-cloud-platform google-cloud-functions


    【解决方案1】:

    如果你想要一个异步函数,只需声明它:

    exports.helloGCS = async (file, context) => {
      console.log(`  Event: ${context.eventId}`);
    };
    

    如果你想让它调用一个命名函数:

    async function getDevices(file, context) {
      console.log(`  Event: ${context.eventId}`);
    }
    
    exports.helloGCS = getDevices;
    

    【讨论】:

    • 完美,更好的方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-15
    • 1970-01-01
    • 2023-03-23
    相关资源
    最近更新 更多