Gitter migration: Setup redirects (rollout pt. 3)
[gitter.git] / server / web / resource-route-generator.js
blob6688d0ff46276320451f0478a328386438bb5ac8
1 'use strict';
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;
12 if (resource.load) {
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);
22 req[idParam] = value;
23 return null;
25 .nodeify(next);
26 });
29 function defaultRespond(req, res, responseBody) {
30 if (responseBody === undefined) {
31 res.sendStatus(200);
32 } else {
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(
46 req,
47 res,
48 next
49 ) {
50 return promiseImpl(req, res)
51 .then(function(response) {
52 responder(req, res, response);
53 return null;
55 .catch(next);
56 });
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];
70 router.use(
71 '/' + subresourceName,
72 resourceRoute(routeIdentifier + '-' + subresourceName, subresource)
74 });
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];
86 router.use(
87 '/:' + idParam + '/' + subresourceName,
88 resourceRoute(routeIdentifier + '-' + subresourceName, subresource)
90 });
93 return router;