Skip to content

Instantly share code, notes, and snippets.

@Philmod
Created March 31, 2017 17:24
Show Gist options
  • Save Philmod/5963d7d674da34fb6dcce69e29ee39b4 to your computer and use it in GitHub Desktop.
Save Philmod/5963d7d674da34fb6dcce69e29ee39b4 to your computer and use it in GitHub Desktop.
A GCFunction to write data from PubSub to Datastore.
const datastore = require('google-cloud').datastore;
const _PROJECT_ID = 'my-project';
var datastoreClient = datastore({
projectId: _PROJECT_ID
});
exports.subscribe = function subscribe(event, callback) {
const pubsubMessage = event.data;
const deviceId = pubsubMessage.attributes.deviceId;
const deviceRegistryId = pubsubMessage.attributes.deviceRegistryId;
let data;
try {
data = JSON.parse(Buffer.from(pubsubMessage.data, 'base64').toString());
} catch(e) {
console.error(e);
return callback(e);
}
const obj = {
timestamp: data.timestamp,
device_id: deviceId,
key: data.key,
value: data.value
};
datastoreClient.save({
key: datastoreClient.key(deviceRegistryId),
data: obj
}, function(err) {
if (err) {
console.log('datastore err : ', err);
callback(err);
} else {
console.log('Saved to datastore');
callback();
}
});
};
@narala558
Copy link

Hi, sir, may I know how to give the values of the Kind in the streaming data to push into the datastore

package.json file how can I create for this

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment