-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
214 lines (189 loc) · 5.5 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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
const joi = require('joi')
const boom = require('@hapi/boom')
const qs = require('qs')
const call = require('@hapi/call')
const pkg = require('./package.json')
/**
* @type {Object}
* @private
*
* Store internal objects
*/
const internals = {
regexp: {
braces: /[{}']+/g,
params: /\{(\w+\*?|\w+\?|\w+\*[1-9][0-9]*)\}/g,
wildcard: /\*$/g
},
scheme: {
params: joi.object({
query: joi.object(),
params: joi.object()
}),
options: joi.object({
secure: joi.boolean(),
rel: joi.boolean().default(false),
host: joi.string(),
router: joi.object().instance(call.Router)
}).default({
host: false,
router: false
})
}
}
/**
* @function
* @private
*
* Check if condition is true and throw error if not
*
* @param {any} condition The condition to be checked
* @param {any} [msg=''] The error message
* @param {string} [type='badRequest'] The error type
*/
function assert (condition, msg = '', type = 'badRequest') {
if (!condition) {
throw boom[type](msg)
}
}
/**
* @function
* @private
*
* Parse optional parameters
*
* @param {Object} params The parameters to be inserted
* @param {string} section The section to be replaced
* @param {string} stripped The sections key
* @returns {*} Parsed source and destination for replacement
*/
function parseOptional (params, section, stripped) {
stripped = stripped.slice(0, -1)
const key = (params && params[stripped]) || ''
return {
dst: key && key.toString() ? section : `/${section}`,
src: key
}
}
/**
* @function
* @private
*
* Parse multi-parameters
*
* @param {Object} params The parameters to be inserted
* @param {string} section The section to be replaced
* @param {string} stripped The sections key
* @returns {*} Parsed source and destination for replacement
*/
function parseMulti (params, section, stripped) {
const split = stripped.split('*')
const value = params[split[0]]
assert(Array.isArray(value), `The ${stripped} parameter should be an array`)
assert(parseInt(split[1], 10) === value.length, 'The number of passed multi-parameters does not match the defined multiplier')
const src = value.join('/')
assert(src, `The '${stripped} parameter is missing`)
return { dst: section, src }
}
/**
* @function
* @private
*
* Parse plain parameters
*
* @param {Object} params The parameters to be inserted
* @param {string} section The section to be replaced
* @param {string} stripped The sections key
* @returns {*} Parsed source and destination for replacement
*/
function parsePlain (params, section, stripped) {
stripped = stripped.replace(internals.regexp.wildcard, '')
assert(params && params[stripped], `The '${stripped}' parameter is missing`)
return { dst: section, src: params[stripped] }
}
/**
* @function
* @private
*
* Get route configuration object of one or multiple connections by id
*
* @param {Object} server The related server object
* @param {call|undefined} The optional custom router
* @param {string} id The unique route ID to be looked for
* @returns {Object} The route configuration object
*
* @throws Whether there is no related route
*/
function lookupRoute (server, router, id) {
const route = router ? router.ids.get(id) : server.lookup(id)
assert(route, `There is no route on the router with the defined ID (${id})`, 'notFound')
return route
}
/**
* @function
* @public
*
* Handle the basic operations with relative paths
*
* @param {Object} server The server to be extended
* @param {string} id The unique route ID to be looked for
* @param {Object} params The parameters to be inserted
*/
function serverDecorator (server, id, params = {}, options = {}) {
params = joi.attempt(params, internals.scheme.params)
options = joi.attempt(options, internals.scheme.options)
const route = Object.assign({}, lookupRoute(server, options.router, id))
const routeSections = route.path.match(internals.regexp.params) || []
routeSections.forEach((routeSection) => {
const stripped = routeSection.replace(internals.regexp.braces, '')
let parsed
if (stripped.includes('?') || stripped.slice(-1) === '*') {
parsed = parseOptional(params.params, routeSection, stripped)
} else if (stripped.includes('*') && stripped.slice(-1) !== '*') {
parsed = parseMulti(params.params, routeSection, stripped)
} else {
parsed = parsePlain(params.params, routeSection, stripped)
}
route.path = route.path.replace(parsed.dst, parsed.src)
})
if (params.query) {
route.path += `?${qs.stringify(params.query)}`
route.path = route.path.replace(/\?$/, '')
}
return route.path
}
/**
* @function
* @public
*
* Plugin to generate URIs based on ID and parameters
*
* @param {Object} server The server to be extended
* @param {Object} pluginOptions The plugin options
*/
function akaya (server, pluginOptions) {
server.decorate('server', 'aka', serverDecorator.bind(this, server))
server.decorate('request', 'aka', function (id, params = {}, options = {}) {
options = joi.attempt(options, internals.scheme.options)
const path = server.aka(id, params, options)
let protocol
if (options.rel) {
return path
}
switch (options.secure) {
case true:
protocol = 'https'
break
case false:
protocol = 'http'
break
default:
protocol = this.headers['x-forwarded-proto'] || server.info.protocol
}
return `${protocol}://${options.host || this.info.host}${path}`
})
}
module.exports = {
register: akaya,
pkg
}