mirror of
https://github.com/HabitRPG/habitica.git
synced 2025-12-15 05:37:22 +01:00
52 lines
1.2 KiB
JavaScript
52 lines
1.2 KiB
JavaScript
import { inboxModel as Inbox } from '../../models/message';
|
|
|
|
const PM_PER_PAGE = 10;
|
|
|
|
export async function getUserInbox (user, options = {asArray: true, page: 0}) {
|
|
if (typeof options.asArray === 'undefined') {
|
|
options.asArray = true;
|
|
}
|
|
|
|
let query = Inbox
|
|
.find({ownerId: user._id})
|
|
.sort({timestamp: -1});
|
|
|
|
if (typeof options.page !== 'undefined') {
|
|
query = query
|
|
.limit(PM_PER_PAGE)
|
|
.skip(PM_PER_PAGE * Number(options.page));
|
|
}
|
|
|
|
const messages = (await query.exec()).map(msg => msg.toJSON());
|
|
|
|
if (options.asArray) {
|
|
return messages;
|
|
} else {
|
|
const messagesObj = {};
|
|
messages.forEach(msg => messagesObj[msg._id] = msg);
|
|
|
|
return messagesObj;
|
|
}
|
|
}
|
|
|
|
export async function getUserInboxMessage (user, messageId) {
|
|
return Inbox.findOne({ownerId: user._id, _id: messageId}).exec();
|
|
}
|
|
|
|
export async function deleteMessage (user, messageId) {
|
|
const message = await Inbox.findOne({_id: messageId, ownerId: user._id }).exec();
|
|
if (!message) return false;
|
|
await Inbox.remove({_id: message._id, ownerId: user._id}).exec();
|
|
|
|
return true;
|
|
}
|
|
|
|
export async function clearPMs (user) {
|
|
user.inbox.newMessages = 0;
|
|
|
|
await Promise.all([
|
|
user.save(),
|
|
Inbox.remove({ownerId: user._id}).exec(),
|
|
]);
|
|
}
|