rudeshark.net/src/models/messaging-message.ts

76 lines
1.7 KiB
TypeScript
Raw Normal View History

2017-06-12 19:12:30 +02:00
import * as mongo from 'mongodb';
import * as deepcopy from 'deepcopy';
2018-02-02 00:06:01 +01:00
import { pack as packUser } from './user';
import { pack as packFile } from './drive-file';
2018-03-29 13:32:18 +02:00
import db from '../db/mongodb';
2018-10-16 04:38:09 +02:00
import isObjectId from '../misc/is-objectid';
import { length } from 'stringz';
2017-01-17 01:12:33 +01:00
2018-03-29 07:48:47 +02:00
const MessagingMessage = db.get<IMessagingMessage>('messagingMessages');
MessagingMessage.createIndex('userId');
MessagingMessage.createIndex('recipientId');
2018-02-02 00:06:01 +01:00
export default MessagingMessage;
2017-03-03 00:24:48 +01:00
2017-06-12 19:12:30 +02:00
export interface IMessagingMessage {
_id: mongo.ObjectID;
2018-03-29 07:48:47 +02:00
createdAt: Date;
2018-02-02 00:21:30 +01:00
text: string;
2018-03-29 07:48:47 +02:00
userId: mongo.ObjectID;
recipientId: mongo.ObjectID;
isRead: boolean;
fileId: mongo.ObjectID;
2017-06-12 19:12:30 +02:00
}
2017-03-03 00:24:48 +01:00
export function isValidText(text: string): boolean {
return length(text.trim()) <= 1000 && text.trim() != '';
2017-03-03 00:24:48 +01:00
}
2018-02-02 00:06:01 +01:00
/**
* Pack a messaging message for API response
*/
export const pack = (
message: any,
me?: any,
options?: {
populateRecipient: boolean
}
) => new Promise<any>(async (resolve, reject) => {
const opts = options || {
populateRecipient: true
};
let _message: any;
// Populate the message if 'message' is ID
2018-10-16 04:38:09 +02:00
if (isObjectId(message)) {
2018-02-02 00:06:01 +01:00
_message = await MessagingMessage.findOne({
_id: message
});
} else if (typeof message === 'string') {
_message = await MessagingMessage.findOne({
_id: new mongo.ObjectID(message)
});
} else {
_message = deepcopy(message);
}
// Rename _id to id
_message.id = _message._id;
delete _message._id;
// Populate user
2018-03-29 07:48:47 +02:00
_message.user = await packUser(_message.userId, me);
2018-02-02 00:06:01 +01:00
2018-03-29 07:48:47 +02:00
if (_message.fileId) {
2018-02-02 00:06:01 +01:00
// Populate file
2018-03-29 07:48:47 +02:00
_message.file = await packFile(_message.fileId);
2018-02-02 00:06:01 +01:00
}
if (opts.populateRecipient) {
// Populate recipient
2018-03-29 07:48:47 +02:00
_message.recipient = await packUser(_message.recipientId, me);
2018-02-02 00:06:01 +01:00
}
resolve(_message);
});