This repository has been archived by the owner on Jan 19, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathosprey-resources.js
68 lines (61 loc) · 1.69 KB
/
osprey-resources.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
const router = require('osprey-router')
/**
* Expose `ospreyResources`.
*/
module.exports = ospreyResources
/**
* Accept endpoints and a handler function.
*
* @param {Array.<webapi-parser.EndPoint>} endpoints
* @param {Function} handler
* @return {Function}
*/
function ospreyResources (endpoints, handler) {
return createResources(router(), endpoints, handler)
}
/**
* Create a middleware router that handles a resource.
*
* @param {Function} app
* @param {Array.<webapi-parser.EndPoint>} endpoints
* @param {Function} handler
* @return {Function}
*/
function createResources (app, endpoints, handler) {
if (Array.isArray(endpoints)) {
endpoints.forEach(endpoint => {
createResource(app, endpoint, handler)
})
}
return app
}
/**
* Create middleware for a single RAML resource and recursively nest children.
*
* @param {Function} app
* @param {webapi-parser.EndPoint} endpoint
* @param {Function} handler
* @return {Function}
*/
function createResource (app, endpoint, handler) {
const methods = endpoint.operations || []
const path = endpoint.path.value()
methods.forEach(method => {
// Make method name lowercase so it matches names from
// osprey-router.
method.withMethod(method.method.value().toLowerCase())
const handle = handler(method, path)
// Enables the ability to skip a handler by returning null.
if (handle) {
app[method.method.value()](
path, endpoint.parameters, handle, exitRouter)
}
})
return app
}
/**
* Exit the router implementation.
*/
function exitRouter (req, res, next) {
return next('router')
}