Mailspring/packages/nylas-api/routes/messages.js

83 lines
2.1 KiB
JavaScript
Raw Normal View History

2016-06-23 05:17:45 +08:00
const Joi = require('joi');
const Serialization = require('../serialization');
2016-06-23 05:17:45 +08:00
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})
2016-06-26 13:19:05 +08:00
.then((rawMessage) => reply(rawMessage))
}
return reply(Serialization.jsonStringify(message));
})
.catch((error) => {
console.log('Error fetching message: ', error)
reply(error)
})
})
},
})
2016-06-23 05:17:45 +08:00
};