-
Notifications
You must be signed in to change notification settings - Fork 0
/
ubiquitary.js
100 lines (79 loc) · 1.87 KB
/
ubiquitary.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
/**
* For ILLUSTRATION purposes only!
*
* This is meant for functional testing only and not intended as a model for
* a "real-world" solution. This file is meant only to provide an API which
* provides the "same" - source - data in many popular hypermedia formats.
*/
var formatters,
rootUrl = '/api/characters';
formatters = {
'application/collection+json': function cjFormatter(input) {
var result;
result = {
collection: {
version: '1.0',
href: rootUrl
}
}
result.collection.items = Array.isArray(input)
? input.map(cjItem)
: [cjItem(input)];
return result;
},
'application/hal+json': function halFormatter(input) {
var result;
if (Array.isArray(input)) {
result = {
_links: {
self: { href: rootUrl }
},
size: input.length,
_embedded: {
characters: input.map(halFormatter)
}
};
} else {
result = input;
result._links = {
self: { href: rootUrl + '/' + input.alias }
};
}
return result;
}
};
function aCopyOf(obj) {
return JSON.parse(JSON.stringify(obj));
}
function cjItem(item) {
var result;
result = {
data: [
{name: 'alias', value: item.alias},
{name: 'name', value: item.name}
],
links: item.friends
.map(function friendsMap(link) {
return {rel: 'friends', href: link, array: true};
}).concat({rel: 'photo', href: item.photo})
};
return result;
}
function response(type, input/*, additionalAffordances*/) {
var result,
type;
if (input) {
type = mediaType(type);
result = formatters[type]
? formatters[type](aCopyOf(input))
: input;
}
return result;
}
function mediaType(type) {
return formatters[type] ? type : 'application/json';
}
module.exports = {
response: response,
mediaType: mediaType
};