PubsubQueue
A Google Cloud Pubsub client for node.js geared towards queues and jobs. Inspired by ceejbot/fivebeans
Installation
Node 8+ required
yarn add @splitmedialabs/pubsub-queue
Usage
Pre-requisite
- a GCP account and project
- a Pubsub Topic for the main jobs
- a Subscription for this topic
- a Pubsub topic for the failed jobs
- a JSON keyFilename with correct IAM permissions for PubSub
Publishing jobs
const PubsubQueue = require('@splitmedialabs/pubsub-queue');
const Pubsub = new PubsubQueue(
{
projectId: 'my-gcp-project-id',
keyFilename: '~/gcp.json',
},
{
topicName: 'worker-test',
buriedTopicName: 'worker-test-buried',
subscriptionName: 'test-sub',
}
);
Pubsub.Publisher.publish({
type: 'hello',
payload: {
hello: 'world! simple',
},
});
Pubsub.Publisher.publish({
type: 'hello-fail',
payload: {
hello: 'world delayed',
},
delayed: {
unit: 'seconds',
value: '10',
},
});
Pubsub.Publisher.publish('custom-topic-name', {
type: 'hello-fail',
payload: {
hello: 'world delayed',
},
delayed: new Date(new Date().getTime() + 10000).toISOString(),
});
Workers
module.exports = {
async work(payload) {
console.log('job-handler', { payload });
return;
},
};
module.exports = {
async work(payload) {
console.log('job-handler', { payload });
return 'put';
},
};
module.exports = {
retries: {
count: 5,
delay: 1000,
},
async work(payload) {
console.log('job-handler', { payload });
throw new Error('Fake Error!');
},
};
const PubsubQueue = require('@splitmedialabs/pubsub-queue');
const Pubsub = new PubsubQueue(
{
projectId: 'my-gcp-project-id',
keyFilename: '~/gcp.json',
},
{
topicName: 'worker-test',
buriedTopicName: 'worker-test-buried',
subscriptionName: 'test-sub',
}
);
const handlers = {
hello: require('./handlers/hello'),
'hello-repeat': require('./handlers/hello-repeat'),
'hello-fail': require('./handlers/hello-fail'),
};
Pubsub.Worker.start(handlers);
Attaching events handlers to workers
This is useful for statistics
const handlers = {};
Pubsub.Worker.on('job.reserved', data => console.log(data));
Pubsub.Worker.on('job.handled', data => console.log(data));
Pubsub.Worker.on('job.buried', data => console.log(data));
Pubsub.Worker.start(handlers);