Fork me on GitHub

Pointer

Build Status

Server/Client router: http://nodeca.github.io/pointer/

npm install pointer

To make client version:

make browserify

You also need a modern browser or es5-shims to get it working.

API Overview

//
// fill in routes
//

// simple case
router.addRoute('/foo/{bar}', {
  params: {
    bar: /\d+/,
    type: 'integer' /* coerce result to int (string by default) */
  },
  meta: /* any data you want */
});

// with single parameter
router.addRoute({
  pattern: '/foo/{bar}',
  params: { bar: /\d+/ },
  meta: /* any data you want */
});

// route with optional param and it's default value
router.addRoute('/f{forum_id}(-{page}).html', {
  params: {
    forum_id: /\d+/
    page: {
      match: /\d+/
      default: 1
    }
  },
  meta: /* any data you want */
};

// named router (used for linkTo)
router.addRoute('/t{thread_id}', {
  name: 'thread.list',
  params: {
    thread_id: /\d+/
  },
  meta: /* any data you want */
});

// routes grouped by prefix
router.addRoute('/css/{file}(-{md5}).{ext}', {
  prefix: '/assets',
  meta: /* any data you want */
});
// -> /assets/css/{file}(-{md5}).{ext}


//
// Build links
//

router.linkTo('thread.list', {
  thread_id: 123
}); // -> '/t123'


//
// Build links with filling of missed parts.
//

router.linkTo('page', { id: 13 }) // -> '//domain.com/page/13'

router.linkTo('page', { id: 13 }, {
  protocol: 'http',
  hostname: 'defaultdomain.com',
  port:     3000
}) // -> 'http://domain.com:3000/page/13'


//
// find matching route
//

var match = router.match(url);
if (match) {
  match.params; // object with params, e.g. {id: 123, page: undefined}
  match.meta;   // your custom data
}


//
// Dump routes to "executable" string for client asset.
// Needed to keep regexps properly.
//

console.log(router.stringify());

var clientRouter = new Pointer(router.stringify());
class

Pointer

Constructor

Class methods

Instance properties

constructor

Pointer.new

    • new Pointer([routes])
    • routes
      • Object
      • Array
    • Routes map in form of pattern: options pairs, or Array of routes in form of [options]. If you need data to serialize for client, take it from Pointer#config.

Creates new instance of router, prefilled with given routes (if provided).

See Also
class method

Pointer.parseURL

    • Pointer.parseURL(url)
      • Object
    • url
      • String
    • URL to parse

Returns parts of parsed URL:

  • protocol: eg. http, https, file, etc.
  • host: eg. www.mydomain.com, localhost, etc.
  • port: eg. 80
  • path: the path to the file (eg. /folder/dir/index.html)
  • query: the entire querystring, eg. item=value&item2=value2
  • anchor: the entire string after the # symbol
instance method

Pointer#addRoute

    • Pointer#addRoute([pattern][, options])
    • pattern
      • String
    • Pattern as for new Route, shortcut for options.pattern.

    • options
      • Object
    • Route options, see below.

Create and add new route.

Options

Second argument of addRoute is options. It consist of following keys:

  • pattern (Optional, String): will be used as the pattern for new Route if pattern argument is omited.

  • name (Optional, String|Array): name or list of names of the route. Used to build URLs with Pointer#linkTo. Several routes may have same name, see Pointer#linkTo for detailed information.

  • prefix (Optional, String): think of it as of mount point.

  • params (Optional, Object): options of params in the route. See new Route for details.

  • meta (Optional, Mixed): meta data to mix into match object. See new Route for details.

See Also:
instance method

Pointer#linkTo

    • Pointer#linkTo(name[, params][, linkDefaults])
      • String
      • Null
    • name
      • String
    • Name of the URL (or group of URLs).

    • params
      • Object
    • Params to feed to URL builder.

    • linkDefaults
      • Object
    • hash of default values for resulting URL protocol, hostname, and port.

Creates pretty URL for the route registered with given name. If there were several routes registered with such name, the one that produce the longest URL is used.

See Also
instance method

Pointer#match

    • Pointer#match(url)
      • Object
      • Null
    • url
      • String
    • URL to find mathing route for.

Returns first matching route or false if none found. See Route#match for details of matched data Object.

instance method

Pointer#matchAll

    • Pointer#matchAll(url)
      • Array
    • url
      • String
    • URL to find mathing routes for.

Returns all matching routes or an empty array if none found. Each element of the resulting array is result of Route#match call.

instance method

Pointer#stringify

    • Pointer#stringify()
      • String

Serialize added routes (including RegExp properties) into "executable" string, that can be used to build client code.

instance property

Pointer#config

    • Pointer#config
      • Array

Stores array of added routes, suitable for export.

class

Route

internal

Constructor

Instance methods

constructor

Route.new

    • new Route(pattern[, params][, meta][, prefix])
    • pattern
      • String
    • URL pattern. See description below.

    • params
      • Object
    • Params options. Se description below.

    • meta
      • Mixed
    • Meta vars to be returned as part of MatchData by Route#match on successfull matching.

Route constructor.

Pattern

Pattern can be a simple string:

pattern: /my/very/simple/route
regexp:  #/my/very/simple/route#

Or string with some parameter (surrounded with {}) substitutions:

pattern: /my/route/with/{some}/param
regexp:  #/my/route/with/(?<some>[^/]+)/param#

Also it can have optional (surrounded with ()) part:

pattern: /my/route/with(/optional)/part
regexp:  #/my/route/with(?:/optional)?/part#

You may have as many params and optional groups as you want. You can even nest them:

pattern: /my/{kind_of}(-router)(.{format})
regexp:  #/my/(?<kind_of>[^/]+)(?:-router)?(?:[.](?<format>[^/]+))?#
Params

Params are given in form of param_name -> param_options pairs. Options might be an Object (see Syntax Sugar below) or RegExp (shorthand for {match: ...}).

  • match (Optional, RegExp, Default: [^/]+): RegExp that param should match

  • type (Optional, String, Default: 'string'): Set 'integer' to coerce result to int.

  • default (Optional, Mixed): Default value, if param was not presented in the URL upon match() (when it was in the optional group or even not presentes in pattern).

You are free to specify as many params options as you want. You also can specify options of params that are not presented in matching rule, so their default values willl be used when matching route will be found, e.g.:

new Route('/t{thread_id}/last-page.html', {
  thread_id: /\d+/,
  page: -1
}, my_handler);

You may specify param options as RegExp, in this case it will be equal to specifying only match option, these are equal:

{
  thread_id: /\d+/
}

// shorthand syntax for:

{
  thread_id: {
    match: /\d+/
  }
}

Also you can specify param options as String or Integer, in this case it will be equal to specifying default option only:

{
  page: 123
}

// shorthand syntax for:

{
  page: {
    default: 123
  }
}

Very often you need to get params as integers. Use type option to cast:

{
  thread_id: {
    match: /\d+/
    type: 'integer'
  }
}
instance method

Route#buildURL

    • Route#buildURL(params[, linkDefaults])
      • String
      • Null
    • params
      • Object
    • Params to fill into resulting URL.

    • linkDefaults
      • Object
    • hash of default values for resulting URL protocol, hostname, and port.

Returns URL representation of the route with given params. Returns Null when there were not enough params to build URL.

instance method

Route#match

    • Route#match(url)
      • Object
      • Null
    • url
      • String
    • URL to match route against

Returns Object with matching data (see below) if Route matches against given url:

  • params (Object): Params collected from the URL.
  • meta (Mixed): Meta data associated with route.