Add unread query to threads route

This commit is contained in:
Halla Moore 2016-06-24 16:14:04 -07:00
parent 18ad15937f
commit bc5a4ecf3c
3 changed files with 28 additions and 4 deletions

View file

@ -10,7 +10,8 @@ module.exports = (server) => {
notes: 'Notes go here',
tags: ['threads'],
validate: {
params: {
query: {
unread: Joi.boolean().allow(''),
},
},
response: {
@ -22,9 +23,19 @@ module.exports = (server) => {
handler: (request, reply) => {
request.getAccountDatabase().then((db) => {
const {Thread} = db;
Thread.findAll({limit: 50}).then((threads) => {
reply(Serialization.jsonStringify(threads));
})
// the unread value will be '' if the url was just '/threads?unread'
if (request.query.unread || request.query.unread === '') {
Thread.findAll({
where: {unreadCount: {gt: 0}},
limit: 50,
}).then((threads) => {
reply(Serialization.jsonStringify(threads));
})
} else {
Thread.findAll({limit: 50}).then((threads) => {
reply(Serialization.jsonStringify(threads));
})
}
})
},
});

View file

@ -3,6 +3,7 @@ module.exports = (sequelize, Sequelize) => {
threadId: Sequelize.STRING,
subject: Sequelize.STRING,
cleanedSubject: Sequelize.STRING,
unreadCount: Sequelize.INTEGER,
}, {
classMethods: {
associate: ({Message}) => {

View file

@ -127,6 +127,7 @@ function matchThread({db, accountId, message}) {
return Thread.create({
subject: message.subject,
cleanedSubject: cleanSubject(message.subject),
unreadCount: 0,
})
})
})
@ -140,6 +141,7 @@ function matchThread({db, accountId, message}) {
return Thread.create({
subject: message.subject,
cleanedSubject: cleanSubject(message.subject),
unreadCount: 0,
})
})
}
@ -154,12 +156,22 @@ function addMessageToThread({db, accountId, message}) {
.then((thread) => (thread))
}
function updateThreadProperties({thread, message}) {
// Update the thread's unread count
if (message.unread) {
thread.unreadCount++;
thread.save();
}
}
function processMessage({message, accountId}) {
return DatabaseConnector.forAccount(accountId)
.then((db) => addMessageToThread({db, accountId, message}))
.then((thread) => {
thread.addMessage(message)
message.setThread(thread)
updateThreadProperties({thread, message})
return message
})
}