Skip to content

Instantly share code, notes, and snippets.

@adamyeats-zz
Last active December 22, 2015 07:18
Show Gist options
  • Save adamyeats-zz/6437031 to your computer and use it in GitHub Desktop.
Save adamyeats-zz/6437031 to your computer and use it in GitHub Desktop.
Charade dreamcode
var Charade = require('charade'),
c = new Charade();
// c.endpoint() creates an endpoint at the root URL
// the endpoint name must be singular as Charade will create a pluralisation
// e.g. GET /users will be magically set up to GET all users
var endpoint = c.endpoint('user');
// At the simplest level, Charade performs CRUD actions against a DB.
// respondsTo('get') will get a singular record (based on req.route.path) from the DB.
endpoint.respondsTo('get');
// respondsTo('post') will write a singular record (based on req.body) to the DB.
endpoint.respondsTo('post');
// respondsTo() can take variadic arguments for handling multiple HTTP verbs.
endpoint.respondsTo('get', 'post');
// You can define "sub-routes" (this maps to POST /user/new)
endpoint.sub('new').respondsTo('post');
// You can define actions to occur post-DB by simply chaining off the Promise
endpoint.respondsTo('post').then(
function (req, res) {
},
function (err) {
}
);
// You can define authenticated routes
endpoint.auth().then(
function (req, res) {
// the user is authorised
this.respondsTo('post');
},
function (err) {
// the user is not authorised
this.returnStatus(401, 'An API Message'); // sends a 401 and a JSON string { "api_error": "An API Message" }
}
);
// TODO: middleware?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment