Skip to content

Instantly share code, notes, and snippets.

@aseemk
Last active December 10, 2015 16:38
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save aseemk/4461785 to your computer and use it in GitHub Desktop.
Save aseemk/4461785 to your computer and use it in GitHub Desktop.
A simple Restify API server example.
bunyan = require 'bunyan'
restify = require 'restify'
requireDir = require 'require-dir'
middleware = requireDir './middleware'
routes = requireDir './routes'
settings = require './settings'
app = restify.createServer
name: 'Foo Bar API'
version: '0.0.1'
log: bunyan.createLogger
name: 'api'
## MIDDLEWARE:
# Built-ins:
# (see http://mcavage.github.com/node-restify/#Bundled-Plugins for built-ins)
# not bothering to parse Accept headers right now; always sending JSON:
# app.use restify.acceptParser(app.acceptable)
app.use restify.authorizationParser()
app.use restify.dateParser()
app.use restify.queryParser()
app.use restify.bodyParser({mapParams: false, rejectUnknown: false})
# TODO we should enable and test throttling before going to production.
# app.use restify.throttle({###...###})
app.on 'after', restify.auditLogger
log: app.log
# Custom:
app.use middleware.auth()
## ROUTES:
# General:
app.get '/', (req, res, _) ->
res.send 'Hello world.'
# Users:
app.get '/users', routes.users.list
app.post '/users', routes.users.create
app.get '/users/:id', routes.users.get
app.post '/users/:id/password_reset', routes.users.requestPassword
app.get '/me', routes.users.getCurrent
app.post '/me', routes.users.updateCurrent
app.patch '/me', routes.users.updateCurrent
# Things:
app.get '/things', routes.things.list
app.post '/things', routes.things.create
app.get '/things/:id', routes.things.get
app.post '/things/:id', routes.things.update
app.patch '/things/:id', routes.things.update
app.del '/things/:id', routes.things.delete
## STARTUP -- listen if we're running; export if we're require()'ing:
if module is require.main
app.listen settings.PORT, _
log.info "Foo Bar API (#{settings.ENVIRONMENT}) listening on port #{settings.PORT}..."
else
module.exports = app
# this file's path is actually routes/users.coffee
_ = require 'underscore'
models = require '../models' # has an index.js file that calls requireDir()
restify = require 'restify'
{User} = models
{NotImplementedError} = restify
## ROUTES:
# GET /users
@list = (req, res, next) =>
# TODO
next new NotImplementedError
# POST /users
@create = (req, res, next) ->
# (create user...)
res.header 'Location', "/users/#{user.id}"
res.send 201, jsonify user
# ...
## HELPERS:
# returns the JSON representation of the given user:
jsonify = (user) ->
_.pick user, 'id', 'firstName', 'lastName', 'username', 'bio'
@j0n
Copy link

j0n commented Feb 16, 2013

Nice!
what module do you use as middleware for auth?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment