forest-express
Version:
Official package for all Forest Express Lianas
66 lines (65 loc) • 2.26 kB
JavaScript
;
var _ = require('lodash');
var JSONAPISerializer = require('jsonapi-serializer').Serializer;
function serializeConversations(conversations, collectionName, meta) {
function mapConversation(conversation) {
// jshint camelcase: false
conversation.id = conversation.id.replace('layer:///conversations/', '');
conversation.createdAt = conversation.created_at;
if (conversation.last_message) {
conversation.lastMessage = {
id: conversation.last_message.id.replace('layer:///messages/', ''),
sentAt: conversation.last_message.sent_at,
content: conversation.last_message.parts[0].body,
mimeType: conversation.last_message.parts[0].mime_type,
sender: conversation.last_message.sender.display_name
};
}
if (_.isArray(conversation.participants) && conversation.participants.length) {
conversation.title = conversation.participants.map(function (participant) {
return participant.display_name;
}).join(', ');
}
return conversation;
}
var type = "".concat(collectionName, "_layer_conversations");
var data = null;
if (_.isArray(conversations)) {
data = conversations.map(function (conversation) {
return mapConversation(conversation);
});
} else {
data = mapConversation(conversations);
}
return new JSONAPISerializer(type, data, {
attributes: ['title', 'createdAt', 'messages', 'lastMessage'],
messages: {
ref: 'id',
ignoreRelationshipData: true,
included: false,
nullIfMissing: true,
relationshipLinks: {
related: function related(dataSet) {
return {
href: "/forest/".concat(collectionName, "_layer_conversations/").concat(dataSet.id, "/relationships/messages")
};
}
}
},
lastMessage: {
ref: 'id',
attributes: ['sender', 'sentAt', 'content', 'mimeType']
},
keyForAttribute: function keyForAttribute(key) {
return key;
},
typeForAttribute: function typeForAttribute(attribute) {
if (attribute === 'lastMessage') {
return "".concat(collectionName, "_layer_messages");
}
return undefined;
},
meta: meta
});
}
module.exports = serializeConversations;