Skip to content

Instantly share code, notes, and snippets.

@raydog
Created March 18, 2014 03:38
Show Gist options
  • Save raydog/ef12d999be76045aa9dd to your computer and use it in GitHub Desktop.
Save raydog/ef12d999be76045aa9dd to your computer and use it in GitHub Desktop.
Very simple resource-based routing thing for the new Express
var urllib = require('url');
var VALID_PARAM = /^[a-z0-9_]+$/i;
var ACTIONS = [
{ name: "index", verb:"get", path: "" },
{ name: "new", verb:"get", path: "/new" },
{ name: "create", verb:"post", path: "" },
{ name: "show", verb:"get", path: "/:param" },
{ name: "edit", verb:"get", path: "/:param/edit" },
{ name: "update", verb:"put", path: "/:param" },
{ name: "destroy", verb:"delete", path: "/:param" },
];
function _replace_param(path, param) {
return (path.indexOf(":param")>=0) ? path.replace(":param", ":" + param) : path;
}
function Resource(baseuri, param) {
"use strict";
this.baseuri = baseuri;
this.param = param || "id";
// Quick sanity check:
if (!VALID_PARAM.test(this.param)) {
throw new Error("Param `" + this.param + "` has an invalid character");
}
this.actions = [];
return this;
}
ACTIONS.forEach(function (action) {
Resource.prototype[action.name] = function () {
var args = Array.prototype.slice.call(arguments, 0);
var config = (args.length >= 1 && typeof args[0] === 'object') ? args.shift() : {};
config.verb = config.verb || action.verb;
config.path = config.path || _replace_param(action.path, this.param);
config.middleware = args;
this.actions.push(config);
return this;
};
});
Resource.prototype.attach = function (app) {
var resource = this;
this.actions.forEach(function (action) {
var uri = resource.baseuri + action.path;
var route = app.route(uri);
// Simple validation for nicer error messages:
if ( ! route[action.verb] ) {
throw new Error("Express doesn't understand the `" + action.verb + "` verb");
}
route[action.verb].apply(route, action.middleware);
});
this.actions = [];
};
module.exports = Resource;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment