2017-06-12 12:12:30 -05:00
|
|
|
import * as mongo from 'mongodb';
|
2018-02-01 17:06:01 -06:00
|
|
|
import deepcopy = require('deepcopy');
|
|
|
|
import { pack as packUser } from './user';
|
|
|
|
import { pack as packFile } from './drive-file';
|
2018-03-28 11:20:40 -05:00
|
|
|
import db from '../../../db/mongodb';
|
2018-02-01 17:06:01 -06:00
|
|
|
import parse from '../common/text';
|
2017-01-16 18:12:33 -06:00
|
|
|
|
2018-02-01 17:06:01 -06:00
|
|
|
const MessagingMessage = db.get<IMessagingMessage>('messaging_messages');
|
|
|
|
export default MessagingMessage;
|
2017-03-02 17:24:48 -06:00
|
|
|
|
2017-06-12 12:12:30 -05:00
|
|
|
export interface IMessagingMessage {
|
|
|
|
_id: mongo.ObjectID;
|
2018-02-01 17:21:30 -06:00
|
|
|
created_at: Date;
|
|
|
|
text: string;
|
|
|
|
user_id: mongo.ObjectID;
|
|
|
|
recipient_id: mongo.ObjectID;
|
|
|
|
is_read: boolean;
|
2017-06-12 12:12:30 -05:00
|
|
|
}
|
|
|
|
|
2017-03-02 17:24:48 -06:00
|
|
|
export function isValidText(text: string): boolean {
|
|
|
|
return text.length <= 1000 && text.trim() != '';
|
|
|
|
}
|
2018-02-01 17:06:01 -06:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Pack a messaging message for API response
|
|
|
|
*
|
|
|
|
* @param {any} message
|
|
|
|
* @param {any} me?
|
|
|
|
* @param {any} options?
|
|
|
|
* @return {Promise<any>}
|
|
|
|
*/
|
|
|
|
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
|
|
|
|
if (mongo.ObjectID.prototype.isPrototypeOf(message)) {
|
|
|
|
_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;
|
|
|
|
|
|
|
|
// Parse text
|
|
|
|
if (_message.text) {
|
|
|
|
_message.ast = parse(_message.text);
|
|
|
|
}
|
|
|
|
|
|
|
|
// Populate user
|
|
|
|
_message.user = await packUser(_message.user_id, me);
|
|
|
|
|
2018-02-26 11:10:52 -06:00
|
|
|
if (_message.file_id) {
|
2018-02-01 17:06:01 -06:00
|
|
|
// Populate file
|
|
|
|
_message.file = await packFile(_message.file_id);
|
|
|
|
}
|
|
|
|
|
|
|
|
if (opts.populateRecipient) {
|
|
|
|
// Populate recipient
|
|
|
|
_message.recipient = await packUser(_message.recipient_id, me);
|
|
|
|
}
|
|
|
|
|
|
|
|
resolve(_message);
|
|
|
|
});
|