nexa

an RPC mechanism to declare and call APIs with node and express.

npm install nexa
36 downloads in the last month

nexa

yet another RPC mechanism to call functions on the backend from the browser. Relies on Nodejs and Express

calling format:

http    = require 'http'
express = require 'express'
Nexa    = require 'nexa'
expressValidator = require 'express-validator'

app = express()

app.use express.bodyParser()
app.use expressValidator

# the routes config file is in the same directory as this file
n = new Nexa()
n.on 'checkout', (request, args, callback) ->
    callback null, "hey #{args.name}: secret launch codes for #{args.email}"

app.use n.handler

app.listen 8080

The above code assumes that routes.coffee is in the same directory as your server. If it's elsewhere, you can specify the config path manually:

n = new nexa('/path/to/routes.coffee')

routes.coffee contains the declaration of the exposed API

module.exports =
    checkout:
        cache  : 0
        method : 'POST'
        parameters:
            email:
                validate : [
                    'email'
                    { type: 'len', arguments: [ 2, 20 ] }
                ]
                sanitize : [
                    'toLowerCase'
                    { type: 'trim', arguments: [ '\r\n\t' ] }
                    'xss'
                ]

cache affects the HTTP response headers sent to the client when making the request. default value is 0 which means don't cache the result. a number > 0 indicates number of seconds to cache

method is the HTTP request method. The default value is POST

Note: available sanitizing and validation functions available are directly from https://github.com/chriso/node-validator

this causes express to generate several routes automatically:

  • /api returns a block of javascript that defines all of the callable functions from the client. By default, this does not use AMD but you can use requirejs syntax by calling /api?amd=1 when loading the script

  • /api/checkout the route for the checkout call. This isn't called directly by the client, instead the javascript wrapper should be used. However this interface can be used for non javascript clients that need to interface with the API

checkout(email, cb)

where cb is in the format of a nodejs style callback. This function would be called from the client as:

checkout('john.doe@gmail.com', function(er, data){

});

for a full example, look in example/.

TODO

  • add example showing amd style usage
  • parse Apiary.io's document
  • specify namespace for non-AMD usage via GET parameter (maybe /api?ns=myapp ?)
  • consider bundling express-validator
  • publish an API doc that documents the HTTP interface for non-javascript capable clients
  • support other transports besides jquery's $.ajax
  • support a required option for parameters
npm loves you