restable
A Simple Isomorphic REST API Pattern for Express
Build a server-side RESTful API that can be called directly or via http REST client.
Install
npm install --save restable express
Usage
The syntax for consuming your API from the client-side and server-side is identical, but it's obviously faster from the server-side because there is no http request!
Create your API
var restable = var db = var books = { $ } { // $.body // $.query $ } var api =
Expose your API as a REST service
var express = var app = appapp
Consume your API with http REST client
var client = baseUrl: 'http://localhost:8080/api/' // GET /api/books?id=123client
Consume your API directly (no http)
var api = // GET /api/books?id=123 (but no http!)api // POST /api/books (but no http!)api
Options
restable(opts)
opts
- resources - an object whose keys are resource names
- a resource is an object with
get
,post
,put
and/ordelete
methods
- a resource is an object with
- helpers - an object whose keys are helper names
- a helper is a value that is available in all resource methods
- i.e. passing in your
db
as a helper is recommended
Your resource methods need to call either send(json)
or error(message)
.
var myResource = { // $.myHelper // $.myOtherHelper // $.send(json) // $.send(200, json) // $.error(message) // $.error(obj) // $.error(400, message) // $.error(400, obj) }
Advanced usage
You might have endpoints that behave differently based on the user that is calling it.
When your endpoint is called via http, the req
and res
objects are available. For example, you might be using some sort of authentication middleware:
GET /api/my/books
var api = apirest
But oh no! This won't work if we call it from the server-side without a req
object. But it's cool since we can specify req
like this:
GET /my-books.html
// express routeapp
Helpers
If you're using client-sessions or bleh, this is handy:
helpers { var $ = this return $req && $reqsession && $reqsessionuser || $user || {}}