-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcontacts.js
59 lines (53 loc) · 1.67 KB
/
contacts.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
'use strict';
const path = require('path'),
_ = require('lodash');
const Serializer = require('jsonapi-serializer').Serializer;
const config = require(path.resolve('./config/config'));
const contactSerializer = new Serializer('contacts', {
attributes: ['trust', 'reference', 'created', 'isConfirmed', 'confirmed', 'from', 'to', 'message', 'creator'],
keyForAttribute: 'camelCase',
typeForAttribute(attribute) {
if (_.includes(['from', 'to', 'creator'], attribute)) {
return 'users';
}
},
topLevelLinks: {
self: (data) => {
if (_.isArray(data)) {
return `${config.url.all}/contacts`;
}
return `${config.url.all}/contacts/${data.from.username}/${data.to.username}`;
}
},
from: generateUserRelation('from'),
to: generateUserRelation('to'),
creator: generateUserRelation('creator')
});
function generateUserRelation(name) {
return {
ref: 'username',
type: 'users',
attributes: ['username', 'givenName', 'familyName', 'description'],
includedLinks: {
self: (data, { username }) => {
return `${config.url.all}/users/${username}`;
}
},
relationshipLinks: {
self: (data) => `${config.url.all}/contacts/${data.from.username}/${data.to.username}/relationships/${name}`,
related: (data, { username }) => `${config.url.all}/users/${username}`
}
};
}
exports.contact = function (data) {
// set contact id(s)
if (Array.isArray(data)) {
for(const datum of data) {
datum.id = `${datum.from.username}--${datum.to.username}`;
}
} else {
data.id = `${data.from.username}--${data.to.username}`;
}
// serialize
return contactSerializer.serialize(data);
};