sleepy

Easier RESTful APIs. Code less, sleep more.

Sleepy

Sleepy is a tiny routing framework for RESTful APIs. It runs on Express and it loves CoffeeScript.

$ npm install sleepy

Sleepy works with your existing codebase. Even if you're writing new code from scratch, it's good practice to separate your API code from your routing code. The only requirement for Sleepy is that a method must have at least one argument - a callback function that accepts a JSON object.

sleepy = require 'sleepy'
beds = new sleepy.Resource 'beds'
  actions:
    index: listBeds         #    GET /beds
    show: getBed            #    GET /beds/:bed_id
    create: addBed          #   POST /beds
    update: updateBed       #    PUT /beds/:bed_id
    destroy: removeBed      # DELETE /beds/:bed_id

Bind your API to your express app:

beds.bind app
  resources:
    pillows:
      actions:
        index: listPillows      #    GET /beds/:bed_id/pillows
        show: getPillow         #    GET /beds/:bed_id/pillows/:pillow_id
        create: addPillow       #   POST /beds/:bed_id/pillows
        update: updatePillow    #    PUT /beds/:bed_id/pillows/:pillow_id
        destroy: removePillow   # DELETE /beds/:bed_id/pillows/:pillow_id
    king: getKingBeds             #    GET /beds/king
    make:                         #   POST /beds/:bed_id/make
      path: '/:bed_id/make'
      method: makeBed
      verb: 'post'              

Sleepy assumes that your methods have the arguments named in your paths (both implictly and explicitly). For instance, in the example above, removePillow is expected to have arguments named 'bed_id' and 'pillow_id'. If the arguments are not found, they're passed as null. If you use CoffeeScript's { @bed_id, @pillow_id } notation, Sleepy will pass your arguments without a hitch.

For security purposes, query arguments must be explicitly stated in your path:

    search: path: 'search?:query', method: searchBeds    #  GET /beds/search

In create and update actions (as well as post and put), Sleepy will pass the body of the request as an argument with a singular resource name (in our example, 'bed').

Overriding Sleepy's implicit mapping is easy. For instance, if the getBed method expects a bedId argument:

    show: method: getBed, params: bedId: 'params.bed_id' #  GET /beds/:bed_id

...