forked from mulesoft-labs/osprey-resources
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathosprey-resources.js
More file actions
79 lines (69 loc) · 1.83 KB
/
osprey-resources.js
File metadata and controls
79 lines (69 loc) · 1.83 KB
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
var extend = require('xtend')
var router = require('osprey-router')
/**
* Expose `ospreyResources`.
*/
module.exports = ospreyResources
/**
* Accept resources and a handler function.
*
* @param {Array} resources
* @param {Function} handler
* @return {Function}
*/
function ospreyResources(resources, handler, routerOpts) {
return createResources(router(routerOpts), resources, '', null, handler);
}
/**
* Create a middleware router that handles the resource.
*
* @param {Function} app
* @param {Array} resources
* @param {String} prefix
* @param {Object} params
* @param {Function} handler
* @return {Function}
*/
function createResources (app, resources, prefix, params, handler) {
if (Array.isArray(resources)) {
resources.forEach(function (resource) {
createResource(app, resource, prefix, params, handler)
})
}
return app
}
/**
* Create middleware for a single RAML resource and recursively nest children.
*
* @param {Function} app
* @param {Object} resource
* @param {String} prefix
* @param {Object} params
* @param {Function} handler
* @return {Function}
*/
function createResource (app, resource, prefix, params, handler) {
var methods = resource.methods
var resources = resource.resources
var uriParams = extend(params, resource.uriParameters)
var path = prefix + (resource.relativeUri || '')
if (methods) {
methods.forEach(function (method) {
var handle = handler(method, path)
// Enables the ability to skip a handler by returning null.
if (handle != null) {
app[method.method](path, uriParams, handle, exitRouter)
}
})
}
if (resources) {
createResources(app, resources, path, uriParams, handler)
}
return app
}
/**
* Exit the router implementation.
*/
function exitRouter (req, res, next) {
return next('router')
}