pathikrit pathikrit - 1 year ago 95
Node.js Question

How to autogenerate API documentation from Express route mappings?

I am developing a REST API in nodejs + Express and I have been simultaneously documenting my API in the README file and I was wondering if it is possible to automate it. e.g. given:

app.get('/path/to', dosomething);'/path/to/:somethingelse', scream);

I want it to auto generate this

GET: /path/to dosomething
POST: /path/to/:somethingelse scream

zah zah
Answer Source

This is javascript, you can easily patch the original methods to also generate the docs.

Here is a sample code in coffeescript:

express = require 'express'
methods = require 'express/node_modules/methods' # array of all HTTP methods

app = express()

methods.forEach (method) ->
  orig = app[method]
  app[method] = (path, handler) ->
    console.log "patched method ", method, " ", path
    # generate docs here
    orig.apply(this, arguments)

You can also get the code of the handler function using handler.toString(). Add some Regex-Fu and you can extract more notes from a function written like this:

app.get "/foo", (req, res) ->
  "Lorem ipsum dolor sit amet, consectetuer adipiscing elit"
  more code here
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download