3 var express
= require('express');
4 var StatusError
= require('statuserror');
5 var identifyRoute
= require('gitter-web-env').middlewares
.identifyRoute
;
6 var Promise
= require('bluebird');
8 module
.exports
= function resourceRoute(routeIdentifier
, resource
) {
9 var router
= express
.Router({ caseSensitive
: true, mergeParams
: true });
10 var idParam
= resource
.id
;
13 var loadPromisified
= Promise
.method(resource
.load
);
15 router
.param(idParam
, function(req
, res
, next
, id
) {
16 loadPromisified(req
, id
)
17 .then(function(value
) {
18 if (value
=== null || value
=== undefined) {
19 throw new StatusError(404);
29 function defaultRespond(req
, res
, responseBody
) {
30 if (responseBody
=== undefined) {
33 res
.send(responseBody
);
37 function mount(method
, url
, methodName
) {
38 var promiseImpl
= resource
[methodName
];
39 if (!promiseImpl
) return;
41 promiseImpl
= Promise
.method(promiseImpl
).bind(resource
);
43 var responder
= resource
.respond
|| defaultRespond
;
45 router
[method
](url
, identifyRoute(routeIdentifier
+ '-' + methodName
), function(
50 return promiseImpl(req
, res
)
51 .then(function(response
) {
52 responder(req
, res
, response
);
59 mount('get', '/', 'index');
60 mount('get', '/new', 'new'); // TODO: remove this
61 mount('post', '/', 'create');
63 mount('put', '/', 'updateRoot');
64 mount('patch', '/', 'patchRoot');
65 mount('delete', '/', 'destroyRoot');
67 if (resource
.subresourcesRoot
) {
68 Object
.keys(resource
.subresourcesRoot
).forEach(function(subresourceName
) {
69 var subresource
= resource
.subresourcesRoot
[subresourceName
];
71 '/' + subresourceName
,
72 resourceRoute(routeIdentifier
+ '-' + subresourceName
, subresource
)
77 mount('get', '/:' + idParam
, 'show');
78 mount('get', '/:' + idParam
+ '/edit', 'edit'); // TODO: remove this
79 mount('put', '/:' + idParam
, 'update');
80 mount('patch', '/:' + idParam
, 'patch');
81 mount('delete', '/:' + idParam
, 'destroy');
83 if (resource
.subresources
) {
84 Object
.keys(resource
.subresources
).forEach(function(subresourceName
) {
85 var subresource
= resource
.subresources
[subresourceName
];
87 '/:' + idParam
+ '/' + subresourceName
,
88 resourceRoute(routeIdentifier
+ '-' + subresourceName
, subresource
)