API Reference (v0.4.21)

References

For a list of standard middleware, see the Connect documentation.

A lot of Zappa methods are shortcuts or extensions of the Express API.

Only some of the Socket.IO events are documented here.

EXPORTS

require 'zappajs' returns a function with the following attributes:

zappa.version

Version of zappa running.

zappa.app

zappa.app function [, options]

zappa.app [options ,] function

Builds an app with express/socket.io, based on the function you provided.

This function will be called with the value of this/@ set to an object with all the attributes described in the root scope section.

Returns an object with attributes id (uuid generated by zappa for this app), app (express server) and io (socket.io server).

You might also provide an object containing options; options might be:

See their description in the following section.

zappa.run

zappa.run [port,] [host,] [options,] function

Same as zappa.app, but calls server.listen for you.

It will automatically print the equivalent to the following to stdout:

Express server listening on port xxxx in [development/production] mode
Zappa x.x.x orchestrating the show

The base export is actually a reference to this same function, so these are equivalent:

require('zappajs').run ->
  @get '/': 'hi'

require('zappajs') ->
  @get '/': 'hi'

You can pass the parameters in any order. Number is port, string is host, object is options, and function is your application. Port and host are optional. Omitted params will also be omitted in the server.listen call to express (defaulting to port 3000 and binding to INADDR_ANY).

You can also pass the parameters in the options object. The following options are available:

zappa.adapter

zappa.adapter engine[, options]

Creates a zappa view adapter that can be provided to @engine or @use partials:. This view adapter complies with both Express 2.x (render,compile) and Express 3.x specifications.

The engine might be a string (in which case it is passed to require first) or an engine object (in which case it must provide a compile method).

The view adapter provides the content of params at the root of the template’s dataset, except for those whose name is listed in options.blacklist. For example, the default zappa adapter is:

zappa.adapter 'coffeecup', blacklist: ['format', 'autoescape', 'locals', 'hardcode', 'cache']

See @view for more details.

ROOT SCOPE

The function you pass to zappa.app or zappa.run will be called with this/@ set to an object with the following attributes:

@get, @post, @put, @del, @all

@get '/path': handler

@get '/path', middleware, ..., handler

Define handlers for HTTP requests.

Shortcuts to express’ app.[verb]. Params will just be passed forward unmodified (except for the middleware and handler functions, which will be re-scoped), unless a single object is passed. In which case, each key in the object will be a route path, and the value its respective handler. The handler can be a function or a string. In the latter case, the handler passed to express will be a function that only calls res.send with this string.

The handler and middleware functions will have access to all variables described in the request handlers scope section.

If a handler returns a string, res.send(string) will be called automatically.

Ex.:

@get '/': 'hi'

@get '/', -> 'hi'

@get /regex/, -> 'hi'

@get '/': 'hi', '/wiki': 'wiki', '/chat': 'chat'

@get
  '/': -> 'hi'
  '/wiki': 'wiki'
  '/chat': -> @response.send 'chat'

# Route Middleware example
load_user = ->
  user = users[@params.id]
  if user
    @request.user = user
    @next()
  else
    @next "Failed to load user #{@params.id}"

@get '/', load_user, -> 'hi'

You can pass middleware arrays using Coffee-Script’s ... splats:

common = [auth, load_user, apply_policy]

@get '/', common..., -> 'hi'

Or as plain arrays, as Express allows:

common = [auth, load_user, apply_policy]

@get '/', common, -> 'hi'

@on

@on event: handler

Define handlers for events emitted by the client through socket.io.

Shortcut to socket.io’s socket.on 'event'.

The handler functions will have access to all variables described in the sockets handlers scope section. They won’t have access to their parent scope. To make variables available to these handlers, use helper.

Some standard events: connection, message, disconnect.

@helper

Helpers content is made available to both the request handler and sockets handler scopes.

@helper (data)

@helper name: data

The helper will provide the associated data.

@helper (function)

@helper name: function

A function that will be available to both the request handler and sockets handler scopes. It will have access to the same variables as whatever called it. Ex.:

@get '/': ->
  @sum 5, 7

@on connection: ->
  @sum 26, 18

@helper sum: (a, b) ->
                        # Values when called from `@get` vs `@on`
  console.log a         # 5 vs 26
  console.log @request  # available vs undefined
  console.log @emit     # undefined vs available

Since the parameter is actually an object, you can define any number of helpers in one go:

@helper
  sum: (a, b) -> a + b
  subtract: (a, b) -> a - b

@view

@view path: contents

Define an inline template. It’s like you had a file on disk at path inside Express’ views directory. It will have precedence over a template on disk.

Ex.:

@view index: ->
  h1 @foo

@view 'index.eco': '''
  <h1><%= @foo %></h1>
'''

By default, the templating engine is CoffeeCup with extension .coffee. To use other engines, just use express’ mechanisms:

@render 'index.jade'

Or:

@set 'view engine': 'jade'

All variables at @/params (request params + those you created) are automatically made available to templates as params.foo (in CoffeeCup, @params.foo).

In addition, if you’re using the zappa view adapter (as is the case by default, with CoffeeCup), they’re also made available at the template’s “root namespace” (foo or CoffeeCup’s @foo).

Since in express templating data is usually mixed up with framework locals and template options, the adapter will only put variables in the template root if there isn’t a variable there with the same name already, and the name is not blacklisted.

To use this feature with other templating engines:

blacklist = 'scope self locals filename debug compiler compileDebug inline'.split ' '
@engine jade: @zappa.adapter 'jade', blacklist

To disable it on default zappa:

@use partials: { coffee: require('coffeecup').render }

@postrender

@postrender name: function

DOM rendering with server-side jQuery. Defines a function that can be applied after @render .

To use this feature, npm install jsdom first.

@postrender plans: ($) ->
  $('.staff').remove() if @user.plan isnt 'staff'
  $('div.' + @user.plan).addClass 'highlighted'

@get '/postrender': ->
  @locals.user = plan: 'staff'
  @render index: {postrender: 'plans'}

@include (file)

@include "file"

Will require the file at the path specified, and run a function exported as include against the same scope as the current function. Ex.:

# app.coffee
require('zappajs') ->
  @foo = 'bar'
  ping = 'pong'
  @get '/': 'main'
  @include './sub'

# sub.coffee
@include = ->
  console.log @foo    # 'bar'
  console.log ping    # error
  get '/sub': 'sub'

@include (module)

@include require "module"

Allows to require arbitrary modules (using the standard Node.js algorithm). The module must export a function named include.

This allows you to package your Zappa components in modules and locate them automatically.

@client

@client '/foo.js': ->
  sum = (a, b) -> a + b

  @helper foo: (param) ->
    console.log param                       # 'bar' or 'pong'
    sum 1, 2                                # 3
    console.log @zig                        # A request or event input param.
    if @render? then console.log 'route'
    else if @emit? then console.log 'event'

  @get '#/': ->
    @foo 'bar'
    console.log 'A client-side route.'

  @on welcome: ->
    @foo 'pong'
    console.log 'A socket.io event.'

Serves ";zappa.run(#{your_function});" as /foo.js, with content-type application/javascript.

To use it, you must also include /zappa/zappa.js in your page, before /foo.js.

@shared

@shared '/index.js': ->

  @helper role: (name) ->
    unless @user.role is name
      if @request? then @redirect '/login'
      else if window? then alert "This is not the page you're looking for."
      else if @socket? then client.disconnect()

  @get '#/admin': ->
    @role 'admin'
    # admin stuff

@get '/admin': ->
  @role 'admin'
  # admin stuff

@on 'delete everything': ->
  @role 'admin'

Same as @client, but also makes the elements defined in the function available at the server-side.

@coffee

@coffee '/foo.js': ->
  alert 'hi!'

Serves ";#{coffeescript_helpers}(#{your_function})();" as /foo.js, with content-type application/javascript.

@js

@js '/foo.js': '''
  alert('hi!');
'''

Serves the string as /foo.js, with content-type application/javascript.

@css (string paramater)

@css '/foo.css': '''
  body { font-family: sans-serif; }
'''

Serves the string as /foo.css, with content-type text/css.

@css (object parameter)

border_radius = (radius) ->
  WebkitBorderRadius: radius
  MozBorderRadius: radius
  borderRadius: radius

@css '/foo.css':
  body:
    font: '12px Helvetica, Arial, sans-serif'

  'a.button':
    border_radius '5px'

Serves the object, compiled with coffee-css, with content-type text/css.

@stylus

@with css:'stylus'

@stylus '/foo.css': '''
  border-radius()
    -webkit-border-radius arguments
    -moz-border-radius arguments
    border-radius arguments

  body
    font 12px Helvetica, Arial, sans-serif

  a.button
    border-radius 5px
'''

Compiles the string with stylus and serves the results as /foo.css, with content-type text/css.

You must have stylus installed with npm install stylus.

@less

@with css:'less'

@less '/foo.css': '''
  .border-radius(@radius) {
    -webkit-border-radius: @radius;
    -moz-border-radius: @radius;
    border-radius: @radius;
  }

  body {
    font: 12px Helvetica, Arial, sans-serif;
  }

  a.button {
    .border-radius(5px);
  }
'''

Compiles the string with less and servers the results as ‘/foo.css’, with content-type text/css.

You must have less installed with npm install less.

@zappa

The same object that is exported when you require 'zappa'.

@express

The object returned by require 'express'.

@io

The object returned by require('socket.io').listen.

@app

The object returned by express().

Express Application API

@use

Shortcut to @app.use. It can be used in a number of additional ways:

It accepts multiple parameters:

@use express.bodyParser(), @app.router, express.cookies()

Strings:

@use 'bodyParser', @app.router, 'cookies'

And objects:

@use 'bodyParser', static: __dirname + '/public', session: {secret: 'fnord'}, 'cookies'

When passing strings and objects, zappa’s own middleware will be used if available, or express (connect) middleware otherwise. (Tip: middleware added with @use will be ran for every request. If you only want some requests to use a specific middleware, use the @get '/path', middleware1, middleware2, -> ... syntax.)

Currently available zappa middleware are:

static

Uses the Connect static middleware to serve static files.

Same as @express.static(root + '/public'), where root is the directory of the first file that required zappa.

@use 'static'
@use static: abs_path
@use static: {path: abs_path, maxAge: 60}

staticGzip

This features is deprecated and will be removed soon. Please use the new compress middleware, optionally with the staticCache middleware.

Uses gzippo for compression. Make sure the gzippo module is available to your application.

@use 'staticGzip'
@use staticGzip: __dirname + '/public'
@use staticGzip: { path: __dirname + '/public' }   # same as above
@use staticGzip: { contentTypeMatch: /text|javascript|json|coffee/ }

zappa

Serves /zappa/Zappa-simple.js, /zappa/Zappa.js, /zappa/zappa.js, /zappa/jquery.js and /zappa/sammy.js. Automatically added by @client and @shared if not added before.

To minimize page download delay on the client, use /zappa/Zappa.js, which combines Zappa, jQuery, Sammy.js, and Socket.IO client-side scripts into a single download. If your client-side code doesn’t require Sammy, use /zappa/Zappa-simple.js which combines Zappa, jQuery, and Socket.IO.

partials

Uses zappajs-partials (aka express-partials) to bring back layout and partials support to Express 3.x.

Since Express 3.x requires asynchronous template engines, but partials require synchronous template engines, if you provided any non-standard mappings to express via @engine you will need to provide these as well to partials:

# Our '.html' files are actually jade files.
@use partials:
  html: @zappa.adapter 'jade'

As with @engine, this is not required if the file extension matches the template engine name, and the .coffee extension is already mapped to CoffeeCup.

@configure

Shortcut to @app.configure. Accepts an object as param. Ex.:

@configure
  development: => @use 'foo'
  production: => @use 'bar'

@set

Shortcut to @app.set. Accepts an object as param. Ex.:

@set foo: 'bar', ping: 'pong'

@enable

Shortcut to @app.enable. Accepts multiple params in one go. Ex.:

@enable 'foo', 'bar'

@disable

Shortcut to @app.disable. Accepts multiple params in one go. Ex.:

@disable 'foo', 'bar'

@engine

Similarly to Express @app.engine, allows to register specific template engines.

This is normally not needed unless you want to change the behavior of the engine, for example to benefit from zappa.adapter.

Accepts an object as param. Ex.:

@engine eco: require 'eco'

Note that most template engines do not support the new Express 3.x conventions at this time, if you want to use them with Zappa you should either register them as shown above:

blacklist = 'scope self locals filename debug compiler compileDebug inline'.split ' '
@engine jade: @zappa.adapter 'jade', blacklist

or use the consolidate package:

@engine 'eco', require('consolidate').eco

@locals

Shortcut to @app.locals.

@param

@param name:callback,...

Shortcut to @app.param. Accepts multiple params in one go.

The callback is scoped identically to a middleware request handler. Additionally @param is assigned the value of the parameter.

@param 'user_id', ->
  if not @param.indexOf /^[0-9A-F]{24,24}$/i
    @next "Invalid User ID"
  else
    @next()

@with

This is a Zappa extension. The following options are supported.

@with css

@with css:'cssmod'

Will load the module cssmod, add a new method cssmod to the Root Scope, which will behave similarly to the @css method, assuming the cssmod module has a render method.

See the documentation for @stylus and @less for examples.

REQUEST HANDLERS SCOPE

The function you pass to @get, @post, etc., will be called with this/@ set to an object with the following attributes. These attributes are also available to functions passed to @param, and to middleware functions passed to @get, @post, etc.

@response

Directly from express.

Shortcut: @res is a synonym for @response.

Express Response API

@request

Directly from express.

Shortcut: @req is a synonym for @request.

Express Request API

@next

Directly from express.

Use @next "error message" to propagate an error message down the Express pipeline.

@query

Shortcut to @request.query

The parameters listed after ? in the URI.

@body

Shortcut to @request.body

This might be the raw body or a parsed body if you @use 'bodyParser' .

@params

Shortcut to @request.params

The parameters found in the URI path, for example

@get '/user/:name', ->
  @params.name

@session

Shortcut to @request.session.

@locals

Shortcut to @response.locals.

@send

Shortcut to @response.send Not available in middleware and param handlers.

@json

Shortcut to @response.json Not available in middleware and param handlers.

@jsonp

Shortcut to @response.jsonp Not available in middleware and param handlers.

@render

Shortcut to @response.render. Not available in middleware and param handlers.

Adds the following features:

- You can use the syntax: @render name: {foo: 'bar'}.

- You can use inline views (see @view).

- You can use post-rendering (see @postrender): render 'index', postrender: 'foo'.

- If the setting databag is on, the databag will be automatically available to templates as params.

- You can use layouts and partials (even though Express 3.x no longer provides them):

    @use 'partials'
    @get '/': ->
      @render 'index', layout:'layout'

You may `@enable 'default layout' to activate the default layout; or provide your own:

    @view layout: ->
      html ->
        body: @body

To disable layout processing: `@render 'index', layout: no`.

See the documentation for `partials` for more information.

@redirect

Shortcut to @response.redirect. Not available in middleware and param handlers.

@format

Shortcut to @response.format. Not available in middleware and param handlers.

Example:

@get '/clients/:id':
  client = retrieve_client @params.id
  @format
    text: =>
      @send client.name
    html: =>
      @render 'client', client
    json: =>
      @json client
    'image/png':
      qr_encode client

SOCKETS HANDLERS SCOPE

The function you pass to @on will be called with this/@ set to an object with the following attributes:

@socket

Directly from socket.io.

@data

Directly from socket.io.

@ack

Directly from socket.io. Provides acknowledgement of messages sent by @emit on the client.

@on foo: ->
  @ack 'Got it!'

@client '/index.js', ->
  @connect()

  $ =>
    @emit start: 'now', (data) ->
      alert data  # 'Got it!'

@id

Shortcut to @socket.id.

@client

An empty object unique for each socket. You can put data pertaining to the client here, as an alternative to @socket.set.

@emit

Shortcut to @socket.emit. Send a message to the client.

Adds the following features:

- You can use the syntax: @emit name: {foo: 'bar'}.

@broadcast

Shortcut to @socket.broadcast. Send a message to all clients except ours.

Adds the following features:

- You can use the syntax: @broadcast name: {foo: 'bar'}.

@join

@join room

Shortcut to @socket.join.

@leave

@leave room

Shortcut to @socket.leave.

@broadcast_to

@broadcast_to room, msg

Shortcut to @io.sockets.in(room).emit.

Broadcast to a room.

@session

@session (error,session) ->

Gets the associated Express session.

The session object is only available if the Express session was previously linked to the socket using client-side @share. This is done automatically for the default, local Express session and local Socket.IO server.

See examples/share_*.coffee for a complete example using separate servers for Socket.IO and Express. The Socket.IO and Express applications can run on the same host (Node.js clustering) or on different hosts.

VIEW SCOPE

The normal view scope is a CoffeeCup scope extended via zappa.adapter (so that @foo === @params.foo).

CLIENT-SIDE ROOT SCOPE

This is the scope inside a @client or @shared callback.

@app

The Sammy.js application, if Sammy is present.

@get

Route with sammy.js.

@connect

Should be called first when the client is started to establish the Socket.IO websocket with the server.

@on

Event handlers with socket.io.

Some standard events: connect, connecting, disconnect, connect_failed, error, message, reconnect_failed, reconnect, reconnecting.

@emit

Send a message to the server.

# Send a message but no data
@emit 'message'

# Send a message with associated data
@emit 'message', data
@emit message: data

# Send multiple messages at once
@emit message1: data1, message2: data2

# Callback receives acknowledgment from server's @ack
@emit -> alert 'Server received it'

# Callback receives acknowledgment from server with data
@emit (data) ->

@helper

Same as its server-side counterpart. Helper functions are available in routes and socket handlers.

CLIENT-SIDE ROUTE HANDLERS SCOPE

The client-side route-handler scope contains any client-side helper, and the following.

@app

The Sammy.js application, if Sammy is present.

@sammy_context

The sammy.js EventContext.

@render

Sammy.js render

@redirect

Sammy.js redirect

@params

Sammy.js route parameters.

CLIENT-SIDE SOCKETS HANDLERS SCOPE

The client-side socket-handler scope contains any helper function, and the following.

@app

The Sammy.js application, if Sammy is present.

@socket

The Socket.IO socket created during @connect().

@id

The Socket.IO socket ID.

@data

The message data (received from the server).

@emit

Same as the client-side root scope’s @emit.

@share

@share(channel_name,socket,callback) will associate the socket to the channel_name. This is used to make the Express session data available to the Socket.IO server.

The channel name __local is reserved for the local Socket.IO server (in order for Socket.IO server-side to get access to the Express session object in a single-instance scenario).

For a multi-server / Node.js cluster example, see examples/share_*.coffee.

APP SETTINGS

You can use the following options with @set, @enable and @disable.

‘minify’

Uses uglify-js to minify the outputs of /zappa/Zappa.js, /zappa/Zappa-simple.js, /zappa/zappa.js, @client, @shared, @coffee, @js.

‘default layout’

If enabled, zappa adds the following template with the name layout:

doctype 5
html ->
  head ->
    title @title if @title
    if @scripts
      for s in @scripts
        script src: extension s, '.js'
    script(src: extension @script, '.js') if @script
    if @stylesheets
      for s in @stylesheets
        link rel: 'stylesheet', href: extension s, '.css'
    link(rel: 'stylesheet', href: extension @stylesheet, '.css') if @stylesheet
    style @style if @style
  body @body

where extension accepts path with or without the given extension.

‘databag’

If enabled, views will receive an object containing the merge of @query, @params, and @body. This object will be called params (or @params in coffeecup views).

‘x-powered-by’

Unless disabled, ZappaJS adds a X-Powered-By header in HTTP responses.

‘zappa_prefix’

Normally a prefix of /zappa is used for all Zappa-specific URIs. This settings allows you to specify a different path.