Skip to content

Instantly share code, notes, and snippets.

@subkitio
Last active December 26, 2015 19:56
Show Gist options
  • Save subkitio/e312970471240e5dfb7a to your computer and use it in GitHub Desktop.
Save subkitio/e312970471240e5dfb7a to your computer and use it in GitHub Desktop.
A simple REST-Style API
const Guid = require('guid');
const _ = require('lodash');
this.state.todos = state.todos || {};
this.GET = get;
this.POST = add;
this.PUT = set;
this.delete = remove;
this[this.req.method](this.req.params.id, this.req.body);
function get(id){
if(id && !this.state.todos[id]) return this.res.status(404).end();
if(id && this.state.todos[id]) return this.res.send(this.state.todos[id]);
this.res.send(_.toArray(this.state.todos));
}
function add(id, todo){
todo.id = id || Guid.create();
this.state.todos[todo.id] = todo;
this.res.status(201).send(todo);
}
function set(id, todo){
if(!this.state.todos[id]) {
return this.res.status(404).end();
}
this.state.todos[id] = todo;
this.res.status(202).send(todo);
}
function remove(id){
if(id && !this.state.todos[id]) {
return this.res.status(404).end();
}
if(!id){
this.state.todos = {};
return this.res.status(204).end();
}
delete this.state.todos[id];
this.res.status(204).end();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment