Implementing worker app
Install with npm
npm install modusign-worker
const { Worker } = require('modusign-worker');
const subscriberName = 'bbcSqsConsumer';
const option = {};
const worker = new Worker({ subscriberName: '', option });
// message parser must be included as middleware
const parseMessage = (message) => {
const { Subject: subejct, Body: body } = JSON.parse(message);
return {
subject,
body,
};
}
const middlewareOne = async (context) => {
// process context #1
return context;
}
const jobNumberOne = async (context) => {
// do job #1
}
const jobNumberTwo = async (context) => {
// do job #2
}
worker.setParser(parseMessage);
worker.use(middlewareOne);
worker.register('job.number.one', jobNumberOne);
worker.register('job.number.two', jobNumberTwo);
- choose subscriber and create option object
const { Worker } = require('modusign-worker');
const subscriberName = 'bbcSqsConsumer';
const option = {};
Reference supporting subscribers below which string you can assign
subscriberName
option
must contain properties fit subscriber. Reference subscriber's own document.
- create worker instance
const worker = new Worker({ subscriberName: '', option });
Add message parser you want to process.
The parser get message
and must return context
which contains subject
and so on.
- implement parser
const messageParser = (message) => {
const { Subject: subejct, Body: body, MessageId: messageId, MD5OfBody: md5OfBody } = JSON.parse(message);
const context = {
messageId,
md5OfBody
subject,
body,
};
return context;
}
subject
is required and must be a string. Job handlers find the job it should handle usingsubject
. (like routing path)
- set parser on your worker
worker.setParser(messageParser);
Worker support web-framework style middlewares
Add functions that process all context before pass job handlers
Middlewares get and return context
(if it should be replaced)
- implement middlewares
const middleware = (context) => {
// process context
return context
}
When middleware returns
context
, whole context will be replaced.
- use middlewares
worker.use(middleware);
Job handlers can be implemented like controllers
Add handlers that contains your business logics.
Handlers get whole context
, and are excuted following subject
- implement handler
const jobHandler = async (context) => {
// business logic
};
- register handler
worker.register('subject', jobHandler);
Define how you handle error
- implement handler
const errorHandler = async (error) => {
// process error
}
- set error handler
worker.setErrorHandler(errorHandler);
- sqs-consumer
Polling amazon sqs.
const worker = new Worker({ subscriberName: 'bbcSqsConsumer', option });
option: sqs-consumer document do not define
option.handleMessage
.