Add category filtering to threads api endpoint

This commit is contained in:
Halla Moore 2016-06-28 15:01:41 -07:00
parent 5077b3f027
commit 0f64b6e58e
5 changed files with 41 additions and 11 deletions

View file

@ -11,14 +11,15 @@ module.exports = (server) => {
tags: ['threads'],
validate: {
query: {
id: Joi.number().integer().min(0),
subject: Joi.string(),
unread: Joi.boolean(),
starred: Joi.boolean(),
startedBefore: Joi.date().timestamp(),
startedAfter: Joi.date().timestamp(),
lastMessageBefore: Joi.date().timestamp(),
lastMessageAfter: Joi.date().timestamp(),
'id': Joi.number().integer().min(0),
'subject': Joi.string(),
'unread': Joi.boolean(),
'starred': Joi.boolean(),
'startedBefore': Joi.date().timestamp(),
'startedAfter': Joi.date().timestamp(),
'lastMessageBefore': Joi.date().timestamp(),
'lastMessageAfter': Joi.date().timestamp(),
'in': Joi.string().allow(Joi.number()),
},
},
response: {
@ -29,9 +30,10 @@ module.exports = (server) => {
},
handler: (request, reply) => {
request.getAccountDatabase().then((db) => {
const {Thread} = db;
const {Thread, Category} = db;
const query = request.query;
const where = {};
const include = [];
if (query.id) {
where.id = query.id;
@ -76,8 +78,21 @@ module.exports = (server) => {
}
}
// Association queries
if (query.in) {
include.push({
model: Category,
where: { $or: [
{ id: query.in },
{ name: query.in },
{ role: query.in },
]},
});
}
Thread.findAll({
where: where,
include: include,
limit: 50,
}).then((threads) => {
reply(Serialization.jsonStringify(threads));

View file

@ -7,8 +7,9 @@ module.exports = (sequelize, Sequelize) => {
syncState: JSONType('syncState'),
}, {
classMethods: {
associate: ({Message}) => {
associate: ({Message, Thread, ThreadCategory}) => {
Category.hasMany(Message)
Category.belongsToMany(Thread, {through: ThreadCategory})
},
},
instanceMethods: {

View file

@ -0,0 +1,7 @@
module.exports = (sequelize, Sequelize) => {
const ThreadCategory = sequelize.define('ThreadCategory', {
role: Sequelize.STRING,
});
return ThreadCategory;
};

View file

@ -10,7 +10,8 @@ module.exports = (sequelize, Sequelize) => {
lastMessageReceivedTimestamp: Sequelize.DATE,
}, {
classMethods: {
associate: ({Message}) => {
associate: ({Category, Message, ThreadCategory}) => {
Thread.belongsToMany(Category, {through: ThreadCategory})
Thread.hasMany(Message, {as: 'messages'})
},
},

View file

@ -170,6 +170,12 @@ function updateThreadProperties({db, thread, message}) {
})
thread.lastMessageTimestamp = message.date;
thread.hasCategory(message.CategoryId).then((hasCategory) => {
if (!hasCategory) {
thread.addCategory(message.CategoryId)
}
});
if (message.unread) {
thread.unreadCount++;
}