npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

rest-parser

v1.0.6

Published

A REST-style request parser

Readme

rest-parser

A request parser that enforces REST style for any db model. Simply implement the required methods for the underlying object. The model object only needs to implement the methods .post, .get, .put, and .delete.

NPM

build status

Why?

We want to separate the request and authentication handlers from the database model code. This makes it easy to change backends without having to change your http routes. It's also great for exposing the same API over http for all of your database models without extra code.

Installation

This module is installed via npm:

$ npm install rest-parser

Usage

Example database connection object that uses simple in-memory dictionaries for application storage.

function Book(key) {
  this.db = {}
  this.key = key
}

Book.prototype.post = function (data, opts, cb) {
  if(!data) {
    return cb('Need values to save')
  }
  var key = data[this.key]
  this.db[key] = data
  return cb(null, key)
}

Book.prototype.get = function (opts, cb){
  if(!opts.id) {
    var values = []
    for (id in this.db) {
      values.push(this.db[id])
    }
    return cb(null, values)
  }
  var val = this.db[opts.id]
  if (!val) {
    return cb('NotFound')
  }
  return cb(null, this.db[opts.id])
}

Book.prototype.put = function (data, opts, cb) {
  if(!opts.id) {
    return cb('Need a opts.id')
  }
  this.db[opts.id] = data
  return cb(null, opts.id)
}


Book.prototype.delete = function (opts, cb) {
  if(!opts.id) {
    return cb('Need a opts.id')
  }
  delete this.db[opts.id]
  return cb(null)
}

Create a server

var RestParser = require('rest-parser')
var Book = require('./book.js')

// make the book model
var bookDB = new Book()
var REST = new RestParser(bookDB)

// Wire up API endpoints
router.addRoute('/api/book/:id?', function(req, res, opts) {
    var id = parseInt(opts.params.id) || opts.params.id
    REST.dispatch(req, { id: id }, function (err, data) {
      res.end(JSON.stringify(data))
    })
  })
})

var server = http.createServer(router)
server.listen(8000)

The server will now have these routes available:

GET /book
GET /book/:id
POST /book
PUT /book/:id
DELETE /book/:id

Advanced: auth, custom routes

Sometimes, you want control over the individual routes to expose only a subset, to require authentication, or some other query logic. It's easy to do with rest-parser -- just use the underlying handler methods:

var RestParser = require('rest-parser')
var Book = require('./book.js')

// make the book model
var bookDB = new Book()
var REST = new RestParser(book)

// Wire up API endpoints
router.addRoute({
  GET: '/api/book/:id', function(req, res, opts) {
    var id = parseInt(opts.params.id) || opts.params.id
    REST.get(req, { id: id }, function (err, data) {
      res.end(JSON.stringify(data))
    })
  }),
  POST: '/api/book/:id', function(req, res, opts) {
    var id = parseInt(opts.params.id) || opts.params.id
    if (!req.userid) {
      res.statusCode = 401
      res.end('Unauthorized!')
      return
    }

    REST.post(req, { id: id }, function (err, data) {
      res.end(JSON.stringify(data))
    })
  })
})

var server = http.createServer(router)
server.listen(8000)

API

RestParser(model)

Instantiates the parser with a given model.

The model object should have the following method signature:

  • model#put(data, opts, cb)
  • model#post(data, opts, cb)
  • model#delete(opts, cb)
  • model#get(opts, cb)

The parser will take the request object and route to the corresponding model method.

RestParser#post(req, opts, cb)

Does not enforce an id -- it is assumed that the id will be generated upon creation or otherwise will be handled by the model.

RestParser#put(req, opts, cb)

Parses the request body using getBodyData and passes to model.put.

RestParser#delete(req, opts, cb)

Passes to model.delete.

RestParser#get(req, opts, cb)

Passes to model.get

RestParser#dispatch(req, opts, cb)

This parses the req.method to dispatch appropriately to one of the above methods.

Examples

Create a new book

$ curl -x POST 'http://localhost:8000/api/book' -d {'author': 'Mark Twain', 'name': 'N/A'}
1

Update a book

$ curl -x PUT 'http://localhost:8000/api/book/1' -d {'author': 'Mark Twain', 'name': 'Life on the Mississippi'}
1

Get all books

$ curl 'http://localhost:8000/api/book'
[
  {
    'id': 1,
    'author': 'Mark Twain',
    'name': 'Life on the Mississippi'
  },
  etc...
]

Get a single book

$ curl 'http://localhost:8000/api/book/1'
{
  'id': 1,
  'author': 'Mark Twain',
  'name': 'Life on the Mississippi'
}

Delete a book

$ curl -x DELETE 'http://localhost:8000/api/book/1'

Get all books (none remain)

$ curl 'http://localhost:8000/api/book'
[]

License

Copyright (c) 2014, Karissa McKelvey All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

  • Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.

  • Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.