Skip to content

Instantly share code, notes, and snippets.

@ClementGautier
Last active January 8, 2019 12:24
Show Gist options
  • Save ClementGautier/7ab592330cb746fa50a82e09e76107c5 to your computer and use it in GitHub Desktop.
Save ClementGautier/7ab592330cb746fa50a82e09e76107c5 to your computer and use it in GitHub Desktop.
Simple publish / subscribe Google Cloud Functions
{
"name": "nodejs-functions-pubsub",
"version": "0.0.1",
"dependencies": {
"@google-cloud/pubsub": "0.22.2",
"@google-cloud/logging": "^4.2.0"
}
}
'use strict';
const {PubSub} = require('@google-cloud/pubsub');
const {Logging} = require('@google-cloud/logging');
const pubsub = new PubSub();
const logging = new Logging();
exports.publish = (req, res) => {
const random = Math.random();
// Uncomment for custom logging
const log = logging.log("my-log");
const entry = log.entry({resource: {
type: 'global',
labels: {
project_id: process.env.GCLOUD_PROJECT,
}
}}, 'Hello World');
log.write(entry);
console.log(`Wrote a log`);
const message = JSON.stringify({
message: random.toString(36).substring(2, 15),
});
console.log('Publishing message "'+message+'" to topic');
return pubsub
.topic('projects/toto-228009/topics/example')
.publisher()
.publish(Buffer.from(message))
.then(() => res.status(200).send('Message published.'))
.catch(err => {
console.error(err);
res.status(500).send(err);
return Promise.reject(err);
});
};
'use strict';
exports.subscribe = (event, callback) => {
console.log(JSON.parse(Buffer.from(event.data, 'base64').toString()));
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment