My Google Cloud Tutorial

FYI, instead of using the app engine, I got the Cloud Function working with:

index.js:

/**
 * Triggered from a message on a Cloud Pub/Sub topic.
 *
 * @param {!Object} event The Cloud Functions event.
 * @param {!Function} The callback function.
 */

// These environment variables are set automatically on Google App Engine
var Datastore = require('@google-cloud/datastore');

// Instantiate a datastore client
var datastore = Datastore();

exports.storeEvent = (event, callback) => {

  // The Cloud Pub/Sub Message object.
  const message = event.data;
  
  console.log('message', message);
  
  // Datastore
  var key = datastore.key('ParticleEvent');

  // You can uncomment some of the other things if you want to store them in the database
  // {"data":"{\"temperature\":67.46,\"humidity\":45.00,\"thermistor\":68.29,\"bpm\":0}","ttl":60,"published_at":"2018-04-20T01:50:15.572Z","coreid":"2a0045001447363333343437","name":"fermenter-log"}
  var obj = {
    // gc_pub_sub_id: message.id,
    // device_id: message.attributes.device_id,
    // event: message.attributes.event,
    published_at: message.attributes.published_at
  }

  // decode data
  var data = JSON.parse(Buffer.from(message.data, 'base64').toString());
  
  
  // Copy the data in message.data, the Particle event data, as top-level 
  // elements in obj. This breaks the data out into separate columns.
  for (var prop in data) {
    if (data.hasOwnProperty(prop)) {
      obj[prop] = data[prop];
    }
  }

  datastore.save({
    key: key,
    data: obj
  }, function(err) {
    if(err) {
      console.log('There was an error storing the event', err);
    }
    console.log('stored in datastore', obj);
  });

  // Don't forget to call the callback.
  callback();
};

package.json:

{
  "name": "sample-pubsub",
  "version": "0.0.1",
  "dependencies": {
    "@google-cloud/datastore": "^0.1.1",
    "@google-cloud/pubsub": "^0.1.1",
    "express": "^4.13.4"
  }
}

When I wrote the tutorial cloud functions were in limited alpha. I’d probably use Google cloud functions instead now, as well, unless you already needed to run other things continuously.

I updated my Google Cloud Tutorial to use Google Cloud Functions which make the process much easier. I added two new examples:

  • Write to Google Cloud Datastore using Cloud Functions
  • Write to Google Sheets using Cloud Functions

The second one is neat because unlike using IFTTT you can manipulate the published events using Javascript (node.js) before writing to the spreadsheet so it’s completely customizable.

3 Likes