-
Notifications
You must be signed in to change notification settings - Fork 1
/
siren_translator.js
93 lines (82 loc) · 2.52 KB
/
siren_translator.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
const transitions = require('../state_transitions')
const _ = require('lodash')
/*
* Generates a Siren "entity". Useful for both resources,
* sub-resources and collection members.
*/
function generateSirenEntity (resource, name, host, state, isAuth, subEntityRel) {
let entity = {}
if (name !== 'undefined') entity.class = [name]
if (subEntityRel) {
entity.rel = [subEntityRel]
}
if (!_.isEmpty(resource)) entity.properties = resource
let possibleTransitions = transitions.getAvailableTransitions(state, isAuth)
let controls = getActionsAndLinks(possibleTransitions, resource, state, host, subEntityRel, isAuth)
if (controls.actions && controls.actions.length > 0) entity.actions = controls.actions
if (controls.links && controls.links.length > 0) entity.links = controls.links
return entity
}
/*
* Transforms a template into Siren fields
*/
function transformTemplate (template) {
let fields = []
for (let prop in template) {
if (template[prop] instanceof Object) {
fields.push({
name: prop,
type: transformTemplate(template[prop])
})
} else {
fields.push({
name: prop,
type: template[prop]
})
}
}
return fields
}
/*
* Returns actions to add to a siren Response
*/
function getActionsAndLinks (possibleTr, data, state, host, isSubEntity, isAuth) {
let actions = []
let links = []
for (let tr of possibleTr) {
if ((transitions.isForEachItem(tr, state) && isSubEntity) || (!transitions.isForEachItem(tr, state) && !isSubEntity)) {
let action = {}
action.href = host + transitions.getUrl(tr, state, data).href
if (transitions.isSelfRel(tr, state)) {
action.rel = 'self'
links.push(action)
} else {
action.name = tr.rel
action.method = tr.method
if (tr.template) action.fields = transformTemplate(tr.template)
actions.push(action)
}
}
}
return { actions, links }
}
/*
* Generates the response
*/
function translate (data, state, host, isAuth) {
let resourceName = /^[a-zA-Z0-9]+/.exec(state)[0]
let sirenResponse = {}
if (data instanceof Array) {
sirenResponse = generateSirenEntity({}, resourceName, host, state, isAuth)
sirenResponse.entities = []
for (let elem of data) {
sirenResponse.entities.push(generateSirenEntity(elem, resourceName, host, state, isAuth, resourceName))
}
} else {
sirenResponse = generateSirenEntity(data, resourceName, host, state, isAuth)
}
return sirenResponse
}
module.exports = {
translate
}