Last active
January 8, 2019 12:24
-
-
Save ClementGautier/7ab592330cb746fa50a82e09e76107c5 to your computer and use it in GitHub Desktop.
Simple publish / subscribe Google Cloud Functions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"name": "nodejs-functions-pubsub", | |
"version": "0.0.1", | |
"dependencies": { | |
"@google-cloud/pubsub": "0.22.2", | |
"@google-cloud/logging": "^4.2.0" | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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); | |
}); | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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