Scheduling GCE with Cloud Pub/Sub(Node.js 8) Part 2

2019-10-03

This is a continuation of previous article about the error with nodejs 8 according to the official reference.

An error occur the following way with nodejs8.

I wrote how to automatically start and stop Compute Engine instances with nodejs 8 while logging errors.

How to work Cloud Pub/Sub with Nodejs8

The following is the script that occurred no callback function error.

const Buffer = require('safe-buffer').Buffer;
const Compute = require('@google-cloud/compute');
const compute = new Compute();

exports.stopInstancePubSub = (event) => {
  try {
    const payload = _validatePayload(
      JSON.parse(Buffer.from(event.data, 'base64').toString())
    );
    compute
      .zone(payload.zone)
      .vm(payload.instance)
      .stop()
      .then(data => {
        // Operation pending.
        const operation = data[0];
        return operation.promise();
      })
      .then(() => {
        // Operation complete. Instance successfully stopped.
        const message = 'Successfully stopped instance ' + payload.instance;
        console.log(message);
      })
      .catch(err => {
        console.log(err);
      });
  } catch (err) {
    console.log(err);
  }
  return 0;
};

function _validatePayload(payload) {
  if (!payload.zone) {
    throw new Error(`Attribute 'zone' missing from payload`);
  } else if (!payload.instance) {
    throw new Error(`Attribute 'instance' missing from payload`);
  }
  return payload;
}

It is a number of minor changes. It has been removed a second argument callback function and callback at the end of function.
“return 0;" at the end of function may not be good way. And It should set “return 1;" at the error catch point.

We can schedule GCE instances with Nodejs 8 Cloud Pub/Sub thanks to the above code without occurring errors that caused by official documents.