Skip to content

Instantly share code, notes, and snippets.

@xaviervia
Created September 21, 2012 04:16
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xaviervia/3759692 to your computer and use it in GitHub Desktop.
Save xaviervia/3759692 to your computer and use it in GitHub Desktop.
Ultra fast server setup with Node, CoffeeScript, Express and MongoDB

Minimal REST server with Node and MongoDB

  1. Install httpie
  2. Install node.js
  3. Paste those files into some folder
  4. Install CoffeeScript into node with npm install coffee
  5. Run the server coffee server.coffee

Use it

With httpie:

  • http localhost:3000/authors: Will give an empty list
  • http POST localhost:3000/authors name=Shakespeare: Will create an author and will return it in JSON
  • http localhost:3000/authors: again, this will return a list containing "Shakespeare" as an author
  • http localhost:3000/authors/<_id>: Replace <_id> with the long alphanumerical "_id" in the previous request, will return the record for Shakespeare.

Voilá

{
"name": "hello-world",
"description": "Hello World app",
"version": "0.0.1",
"private": "true",
"dependencies": {
"express": "3.x",
"cli-color": "x",
"mongodb": ">= 0.9.6-7"
}
}
#!/usr/bin/env coffee
express = require 'express'
clc = require 'cli-color'
mongo = require 'mongodb'
db = new mongo.Db 'test', new mongo.Server 'localhost', 27017
db.open (err, db) ->
orange = clc.xterm 202
green = clc.green
lime = clc.xterm 190
log = console.log
authors = db.collection 'authors'
app = express()
app.use express.bodyParser()
app.get '/authors', (req, res) ->
log lime 'GET /authors'
res.setHeader 'Content-type', 'application/json;charset=utf-8'
authors.find().toArray (err, items) ->
res.send items
app.get '/authors/:id', (req, res) ->
log lime "GET /authors/#{req.params.id}"
authors.findOne { "_id": mongo.ObjectID.createFromHexString(req.params.id) }, (err, item) ->
res.send item
app.post '/authors', (req, res) ->
log lime "POST /authors"
db.collection 'authors', (err, collection) ->
collection.insert req.body
res.send
message: 'inserted'
data: req.body
app.listen 3000
console.log green 'Caffeine in dock 3000'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment