2

I have 3 different method responses in the API I'm working on currently set up like this:

app.use('/image', require('./routes/image/get'));
app.post('/image', require('./routes/image/post'));
app.put('/image', require('./routes/image/put'));

Is there a better way to do this?

Devin Rodriguez
  • 1,144
  • 1
  • 13
  • 30

1 Answers1

8

You may use .route() on your app's Express object to reduce some of the redundancy in your route definitions.

app.route('/image')
     .post(require('./routes/image/post'))
     .put(require('./routes/image/put'));

There is also .all(), which will invoke your handler regardless of the request http method.

No use()

I've omitted .use(), mentioned above, because it is not available on Route objects -- it sets up application middleware. Routers are another layer of middleware (see this question for an explanation of the difference). If the intent is really to call .use(), and not .get(), then that line would have to stay, before the call to .route() (middleware registration order matters).

Reusing the same handler for different http methods

If one would prefer to reuse the same handler for a set of methods, in the following style:

app.route("/image").allOf(["post", "put"], function (req, res) {
    //req.method can be used to alter handler behavior.
    res.send("/image called with http method: " + req.method);
});

then, the desired functionality can be obtained by adding a new property to express.Route's prototype:

var express = require('express');

express.Route.prototype.allOf = function (methods /*, ... */) {
    "use strict";

    var i, varargs, methodFunc, route = this;

    methods = (typeof methods === "string") ? [methods] : methods;
    if (methods.length < 1) {
        throw new Error("You must specify at least one method name.");
    }

    varargs = Array.prototype.slice.call(arguments, 1);
    for (i = 0; i < methods.length; i++) {
        methodFunc = route[methods[i]];
        if (! (methodFunc instanceof Function)) {
            throw new Error("Unrecognized method name: " +
                            methods[i]);
        }
        route = methodFunc.apply(route, varargs);
    }

    return route;
};
Community
  • 1
  • 1
init_js
  • 4,143
  • 2
  • 23
  • 53