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
import PubsubQueue from '@splitmedialabs/pubsub-queue';
const Pubsub = new PubsubQueue(
{
projectId: 'my-gcp-project-id',
keyFilename: '~/gcp.json',
},
{
topicName: 'worker-test',
subscriptionName: 'test-sub',
buriedTopicName: 'worker-test-buried',
}
);
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
export default {
async work(payload) {
console.log('job-handler', { payload });
return;
},
};
export default {
async work(payload) {
console.log('job-handler', { payload });
return 'put';
},
};
export default {
retries: {
count: 5,
delay: 1000,
},
async work(payload) {
console.log('job-handler', { payload });
throw new Error('Fake Error!');
},
};
import PubsubQueue from '@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);