Add /messages/<id> enpoint + support for raw message/rfc822

- When message/rfc822 is requested, fetch ray message from IMAP
connection
This commit is contained in:
Juan Tejada 2016-06-25 11:24:49 -07:00
parent 69e87cbf49
commit caaef8d5b5
2 changed files with 65 additions and 0 deletions

View file

@ -1,6 +1,7 @@
const Joi = require('joi');
const Serialization = require('../serialization');
module.exports = (server) => {
server.route({
method: 'GET',
@ -33,4 +34,46 @@ module.exports = (server) => {
})
},
});
server.route({
method: 'GET',
path: '/messages/{id}',
config: {
description: 'Returns message for specified id.',
notes: 'Notes go here',
tags: ['messages'],
validate: {
params: {
id: Joi.string(),
},
},
response: {
schema: Joi.alternatives().try(
Serialization.jsonSchema('Message'),
Joi.string()
),
},
},
handler: (request, reply) => {
request.getAccountDatabase()
.then((db) => {
const {headers: {accept}} = request
const {params: {id}} = request
const account = request.auth.credentials
const query = db.Message.findOne({where: {id}})
if (accept === 'message/rfc822') {
query.then((message) => {
message.fetchRaw({account, db})
.then((raw) => reply(raw))
.catch((error) => console.log(error))
})
} else {
query.then((message) => {
reply(Serialization.jsonStringify(message));
})
}
})
},
})
};

View file

@ -1,6 +1,8 @@
const crypto = require('crypto');
const IMAPConnection = require('../../imap-connection')
const {JSONType, JSONARRAYType} = require('../../database-types');
module.exports = (sequelize, Sequelize) => {
const Message = sequelize.define('Message', {
rawBody: Sequelize.STRING,
@ -37,6 +39,26 @@ module.exports = (sequelize, Sequelize) => {
},
},
instanceMethods: {
fetchRaw({account, db}) {
return this.getCategory()
.then((category) => {
const settings = Object.assign({}, account.connectionSettings, account.decryptedCredentials())
const conn = new IMAPConnection(db, settings)
return conn.connect()
.then(() => conn.openBox(category.name))
.then(() => {
return new Promise((resolve) => {
conn.fetchMessages([this.CategoryUID], (attributes, headers, body) => {
resolve(`${headers}${body}`)
})
})
})
.then((raw) => {
conn.end()
return raw
})
})
},
toJSON: function toJSON() {
return {
id: this.id,