trashposs/src/api/serializers/messaging-message.ts

69 lines
1.4 KiB
TypeScript
Raw Normal View History

2016-12-28 23:49:51 +01:00
/**
* Module dependencies
*/
import * as mongo from 'mongodb';
2017-03-18 12:05:11 +01:00
import deepcopy = require('deepcopy');
2016-12-28 23:49:51 +01:00
import Message from '../models/messaging-message';
import serializeUser from './user';
import serializeDriveFile from './drive-file';
2017-03-18 12:05:11 +01:00
import parse from '../common/text';
2016-12-28 23:49:51 +01:00
/**
* Serialize a message
*
2017-03-01 09:37:01 +01:00
* @param {any} message
* @param {any} me?
* @param {any} options?
* @return {Promise<any>}
2016-12-28 23:49:51 +01:00
*/
export default (
message: any,
2017-03-03 00:24:48 +01:00
me?: any,
2016-12-28 23:49:51 +01:00
options?: {
populateRecipient: boolean
}
2017-03-01 09:37:01 +01:00
) => new Promise<any>(async (resolve, reject) => {
2016-12-28 23:49:51 +01:00
const opts = options || {
populateRecipient: true
};
let _message: any;
// Populate the message if 'message' is ID
if (mongo.ObjectID.prototype.isPrototypeOf(message)) {
_message = await Message.findOne({
_id: message
});
} else if (typeof message === 'string') {
_message = await Message.findOne({
_id: new mongo.ObjectID(message)
});
} else {
_message = deepcopy(message);
}
// Rename _id to id
_message.id = _message._id;
delete _message._id;
2017-03-18 12:05:11 +01:00
// Parse text
if (_message.text) {
_message.ast = parse(_message.text);
}
2016-12-28 23:49:51 +01:00
// Populate user
_message.user = await serializeUser(_message.user_id, me);
if (_message.file) {
// Populate file
_message.file = await serializeDriveFile(_message.file_id);
}
if (opts.populateRecipient) {
// Populate recipient
_message.recipient = await serializeUser(_message.recipient_id, me);
}
resolve(_message);
});