-
-
Notifications
You must be signed in to change notification settings - Fork 643
/
Copy pathResource.js
329 lines (305 loc) · 7.36 KB
/
Resource.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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
'use strict'
/*
* adonis-framework
*
* (c) Harminder Virk <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
const _ = require('lodash')
const Macroable = require('macroable')
const GE = require('@adonisjs/generic-exceptions')
const Route = require('./index')
const RouteStore = require('./Store')
/**
* Route Resource class is used to define resourceful
* routes. You can create a resource instance by
* calling `Route.resource()` method.
*
* @class RouteResource
* @group Http
* @constructor
*/
class RouteResource extends Macroable {
constructor (resource, controller, groupPrefix = null) {
super()
this._validateResourceName(resource)
this._validateController(controller)
this._resourceUrl = this._makeResourceUrl(resource)
this._controller = controller
/**
* The name prefix is used to prefix the route names.
* Generally used when resource is defined inside
* the Route group
*
* @type {String}
*/
this.prefix = groupPrefix ? `${groupPrefix}.${resource}` : resource
this._routes = []
this._addBasicRoutes()
}
/**
* Validates the resource name to make sure it
* is a valid string.
*
* @method _validateResourceName
*
* @param {String} resource
*
* @return {void}
*
* @private
*/
_validateResourceName (resource) {
if (typeof (resource) !== 'string') {
throw GE.InvalidArgumentException.invalidParameter('Route.resource expects name to be a string', resource)
}
}
/**
* Validates the resource controller to a valid
* string. Existence of controller is validated
* when the controller is resolved.
*
* @method _validateController
*
* @param {String} controller
*
* @return {void}
*
* @private
*/
_validateController (controller) {
if (typeof (controller) !== 'string') {
throw GE.InvalidArgumentException.invalidParameter('Route.resource expects reference to a controller', controller)
}
}
/**
* Makes the correct resource url by properly
* configuring nested resources.
*
* @method _makeResourceUrl
*
* @param {String} resource
*
* @return {String}
*
* @private
*
* @example
* ```js
* _makeResourceUrl('user.posts')
* // returns - user/:user_id/posts
* ```
*/
_makeResourceUrl (resource) {
return resource
.replace(/(\w+)\./g, (index, group) => `${group}/:${group}_id/`)
.replace(/^\/|\/$/g, '')
}
/**
* Add route to the routes array and to the
* routes store.
*
* @method _addRoute
*
* @param {String} action
* @param {String} route
* @param {Array} verbs
*
* @private
*/
_addRoute (action, route, verbs = ['HEAD', 'GET']) {
const routeInstance = new Route(route, `${this._controller}.${action}`, verbs)
routeInstance.as(`${this.prefix}.${action}`)
RouteStore.add(routeInstance)
this._routes.push({ action, routeInstance })
}
/**
* Add basic routes to the routes list. The list
* is further filtered using `only` and `except`
* methods.
*
* @method _addBasicRoutes
*
* @private
*/
_addBasicRoutes () {
this._addRoute('index', this._resourceUrl)
this._addRoute('create', `${this._resourceUrl}/create`)
this._addRoute('store', this._resourceUrl, ['POST'])
this._addRoute('show', `${this._resourceUrl}/:id`)
this._addRoute('edit', `${this._resourceUrl}/:id/edit`)
this._addRoute('update', `${this._resourceUrl}/:id`, ['PUT', 'PATCH'])
this._addRoute('destroy', `${this._resourceUrl}/:id`, ['DELETE'])
}
/**
* Matches the route against an array of names. It will
* match the route action and it's original name
*
* @method _matchName
*
* @param {Route} route
* @param {Array} names
*
* @return {Boolean}
*
* @private
*/
_matchName (route, names) {
return names.indexOf(route.action) > -1 || names.indexOf(route.routeInstance.name) > -1
}
/**
* Remove all routes from the resourceful list except the
* one defined here.
*
* @method only
*
* @param {Array} names
*
* @chainable
*
* @example
* ```js
* Route
* .resource()
* .only(['store', 'update'])
* ```
*/
only (names) {
_.remove(this._routes, (route) => {
if (!this._matchName(route, names)) {
RouteStore.remove(route.routeInstance)
return true
}
})
return this
}
/**
* Remove the routes define here from the resourceful list.
*
* @method except
*
* @param {Array} names
*
* @chainable
*
* @example
* ```js
* Route
* .resource()
* .except(['delete'])
* ```
*/
except (names) {
_.remove(this._routes, (route) => {
if (this._matchName(route, names)) {
RouteStore.remove(route.routeInstance)
return true
}
})
return this
}
/**
* Limit the number of routes to api only. In short
* this method will remove `create` and `edit`
* routes.
*
* @method apiOnly
*
* @chainable
*
* @example
* ```js
* Route
* .resource()
* .apiOnly()
* ```
*/
apiOnly () {
return this.except(['create', 'edit'])
}
/**
* Save middleware to be applied on the resourceful routes. This
* method also let you define conditional middleware based upon
* the route attributes.
*
* For example you want to apply `auth` middleware to the `store`,
* `update` and `delete` routes and want other routes to be
* publicly accessible. Same can be done by passing a
* closure to this method and returning an array
* of middleware to be applied.
*
* ## NOTE
* The middleware closure will be executed for each route.
*
* @method middleware
*
* @param {Array|Map} middleware
*
* @chainable
*
* @example
* ```js
* Route
* .resource()
* .middleware(['auth'])
*
* // or use ES6 maps
* Route
* .resource('user', 'UserController')
* .middleware(new Map([
* [['user.store', 'user.update', 'user.delete'], 'auth']
* ]))
* ```
*/
middleware (middleware) {
const middlewareMap = middleware instanceof Map ? middleware : new Map([
[['*'], _.castArray(middleware)]
])
for (let [routeNamesList, middlewareList] of middlewareMap) {
routeNamesList = _.castArray(routeNamesList)
middlewareList = _.castArray(middlewareList)
_.each(this._routes, (route) => {
if (routeNamesList[0] === '*') {
route.routeInstance.middleware(middlewareList)
} else if (this._matchName(route, routeNamesList)) {
route.routeInstance.middleware(middlewareList)
}
})
}
return this
}
/**
* Define route formats for all the routes inside
* a resource.
*
* @method formats
*
* @param {Array} formats
* @param {Boolean} [strict = false]
*
* @chainable
*
* @example
* ```js
* Route
* .resource()
* .formats(['json'], true)
* ```
*/
formats (formats, strict = false) {
_.each(this._routes, (route) => {
route.routeInstance.formats(formats, strict)
})
}
}
/**
* Defining _macros and _getters property
* for Macroable class
*
* @type {Object}
*/
RouteResource._macros = {}
RouteResource._getters = {}
module.exports = RouteResource