-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
106 lines (83 loc) · 2.65 KB
/
index.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
101
102
103
104
105
106
var extend = require('extend');
var defaultOptions = {
propName: "links"
};
function hateoas(options) {
options = extend({}, defaultOptions, options);
if (!options.baseUrl) {
throw Error("Missing required argument 'baseUrl'");
}
if (options.baseUrl[options.baseUrl.length-1] == "/") {
options.baseUrl = options.baseUrl.substring(0, options.baseUrl.length-1);
}
var linkHandlers = {};
var collectionLinkHandlers = {};
function registerLinkHandler(type, handler) {
if (!linkHandlers[type]) {
linkHandlers[type] = [];
}
linkHandlers[type].push(handler);
}
function registerCollectionLinkHandler(type, handler) {
if (!collectionLinkHandlers[type]) {
collectionLinkHandlers[type] = [];
}
collectionLinkHandlers[type].push(handler);
}
function prefix(link) {
if (!link.length || link[0] !== "/") {
return link;
}
return options.baseUrl + link;
}
function getLinksGeneric(handlers, type, data) {
if (handlers[type]) {
var links = handlers[type].reduce(function(links, handler) {
return extend({}, links, handler(data, type, links));
}, {});
return Object.keys(links).reduce(function(prefixedLinks, linkName) {
prefixedLinks[linkName] = prefix(links[linkName]);
return prefixedLinks;
}, {});
} else {
return [];
}
}
var getLinks = getLinksGeneric.bind(null, linkHandlers);
var getCollectionLinks = getLinksGeneric.bind(null, collectionLinkHandlers);
function linkCollection(type, collection) {
var result = {
data: collection.map(link.bind(null, type))
};
var links = getCollectionLinks(type, collection);
if (options.propName) {
result[options.propName] = links;
} else {
extend(result, links);
}
return result;
}
function link(type, data) {
if (Array.isArray(data)) {
return linkCollection(type, data);
}
if (linkHandlers[type]) {
var links = getLinks(type, data);
if (options.propName) {
data[options.propName] = links;
} else {
extend(data, links);
}
return data;
} else {
return data;
}
}
return {
registerLinkHandler: registerLinkHandler,
registerCollectionLinkHandler: registerCollectionLinkHandler,
getLinks: getLinks,
link: link
};
}
module.exports = hateoas;