Mailspring/packages/nylas-api/routes/messages.js
Juan Tejada dd350a5081 Update IMAPConnection api + error handling fixes + misc
- `IMAPConnection::openBox` now returns a Promise that resolves to an
IMAPBox, and IMAPBox contains all of the `fetch` operations. This makes
the dependency between fetch operations and the currently open mailbox
explicit rather than implicit and by forcing the operations to be called on
a box instance and hopefully prevent errors. It will also throw an error
if the constraint is no longer satisfied.

- `fetch` operations now return an observable stream of messages (or Promise for single value),
while preserving the same logic of the original implementation. You can use `.toPromise()` on
the observable to get a Promise that resolves when the observable stream has
completely drained.

- Fixes error handling in a few places and renames some variables
2016-06-26 01:57:33 -07:00

83 lines
2.1 KiB
JavaScript

const Joi = require('joi');
const Serialization = require('../serialization');
module.exports = (server) => {
server.route({
method: 'GET',
path: '/messages',
config: {
description: 'Returns all your messages.',
notes: 'Notes go here',
tags: ['messages'],
validate: {
query: {
limit: Joi.number().integer().min(1).max(2000).default(100),
offset: Joi.number().integer().min(0).default(0),
},
},
response: {
schema: Joi.array().items(
Serialization.jsonSchema('Message')
),
},
},
handler: (request, reply) => {
request.getAccountDatabase().then((db) => {
const {Message} = db;
Message.findAll({
limit: request.query.limit,
offset: request.query.offset,
}).then((messages) => {
reply(Serialization.jsonStringify(messages));
})
})
},
});
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
db.Message.findOne({where: {id}})
.then((message) => {
if (!message) {
return reply.notFound(`Message ${id} not found`)
}
if (accept === 'message/rfc822') {
return message.fetchRaw({account, db})
.then((rawMessage) => reply(rawMessage))
}
return reply(Serialization.jsonStringify(message));
})
.catch((error) => {
console.log('Error fetching message: ', error)
reply(error)
})
})
},
})
};