3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Cloud Functionsのnodejs6をnodejs8に移行するとき、バックグラウンド関数を使っているときは引数を修正する

Last updated at Posted at 2019-05-25

背景

以前よりアナウンスがありましたが、Cloud Functionsのnode.js6が非推奨となり、2019/4/1以降はnode.js8か10に移行する必要があります。

2019/4/1以前に作っていたnode.js6のCloud Functionsが動かなくなっていたので、node.js8に移行したのですが、その時にトリガーをStorage/PubSubにしていたFunctionsを修正するのに意外と時間が掛かったのでここに残します。

動かなかった時のエラーとしてStorageをトリガーとしていたFunctionsでは「ReferenceError: context is not defined」、PubSubをトリガーとしていたFunctionsでは「TypeError: First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.」が出力されました。

対応

結論ですが、以下のページに書いていることが全てでした。
Cloud Functions を新しい Node.js に移行する

バックグラウンド関数のシグネチャが変更されているため、トリガーにStorageやPubSubを指定している場合は引数に修正が必要になります。
いずれも「(event, callback)」→「(data, context, callback)」に変更します。

トリガーがStorageのときの例

nodejs6
exports.sample = (event, callback) => {
  const file = event.data;
  const stringName = file.name;
  callback();
}
nodejs8
exports.sample = (data, context, callback) => {
  const stringName = data.name;
  callback();
}

トリガーがPubSubの時の例

nodejs6
exports.sample = (event, callback) => {
  const pubsubMessage = event.data;
  const Buffer = require('safe-buffer').Buffer;
  const textPayload = JSON.parse(Buffer.from(pubsubMessage.data, 'base64').toString());
  callback();
}
nodejs8
exports.executeQuery = (data, context, callback) => {
  const pubsubMessage = data;
  const Buffer = require('safe-buffer').Buffer;
  const textPayload = JSON.parse(Buffer.from(pubsubMessage.data, 'base64').toString());
  callback();
}
3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?