Mailspring/packages/nylas-message-processor/index.js
Juan Tejada ed749e0f51 Add sync worker error handling
- Handles sync errors in a single place. For now, if error is not a
socket error, will treat as a permanent error, save the error to the
account object, and prevent any other syncing until the error is cleared
from the account object
- Adds a NylasError class that can be extended and serialized. Adds it
to global namespace on all packages and replaces all uses of regular
Error
2016-06-27 16:03:38 -07:00

45 lines
1.4 KiB
JavaScript

const {DatabaseConnector, NylasError} = require(`nylas-core`)
const {processors} = require('./processors')
global.Promise = require('bluebird');
global.NylasError = NylasError;
// List of the attributes of Message that the processor should be allowed to change.
// The message may move between folders, get starred, etc. while it's being
// processed, and it shouldn't overwrite changes to those fields.
const MessageAttributes = ['body', 'processed']
const MessageProcessorVersion = 1;
function runPipeline({db, accountId, message}) {
return processors.reduce((prevPromise, processor) => (
prevPromise.then((msg) => processor({db, accountId, message: msg}))
), Promise.resolve(message))
}
function saveMessage(message) {
message.processed = MessageProcessorVersion;
return message.save({
fields: MessageAttributes,
});
}
function processMessage({messageId, accountId}) {
DatabaseConnector.forAccount(accountId)
.then((db) => {
const {Message} = db
Message.find({where: {id: messageId}}).then((message) =>
runPipeline({db, accountId, message})
.then((processedMessage) => saveMessage(processedMessage))
.catch((err) =>
console.error(`MessageProcessor Failed: ${err}`)
)
)
.catch((err) =>
console.error(`MessageProcessor: Couldn't find message id ${messageId} in accountId: ${accountId}: ${err}`)
)
})
}
module.exports = {
processMessage,
}