document Model::Validate, ErrorsSet and ValidationError

# Batman.Model

For a general explanation of `Batman.Model` and it works, see [the guide](/docs/models.html).

_Note_: This documentation uses the term _model_ to refer to the class `Model`
or a `Model` subclass, and the term _record_ to refer to one instance of a
model.

## @primaryKey : string

`primaryKey` is a class level configuration option to change which key batman.js uses as the primary key. Change the option using `set`, like so:

    test 'primary key can be set using @set', ->
      class Shop extends Batman.Model
        @set 'primaryKey', 'shop_id'

      equal Shop.get('primaryKey'), 'shop_id'

The `primaryKey` is what batman.js uses to compare instances to see if they represent the same domain-level object: if two records have the same value at the key specified by `primaryKey`, only one will be in the identity map. The key specified by `primaryKey` is also used by the associations system when determining if a record is related to another record, and by the remote storage adapters to generate URLs for records.

_Note_: The default primaryKey is 'id'.

## @storageKey : string

`storageKey` is a class level option which gives the storage adapters something to interpolate into their specific key generation schemes. In the case of `LocalStorage` or `SessionStorage` adapters, the `storageKey` defines what namespace to store this record under in the `localStorage` or `sessionStorage` host objects, and with the case of the `RestStorage` family of adapters, the `storageKey` assists in URL generation. See the documentation for the storage adapter of your choice for more information.

The default `storageKey` is `null`.

## @persist(mechanism : StorageAdapter) : StorageAdapter

`@persist` is how a `Model` subclass is told to persist itself by means of a `StorageAdapter`. `@persist` accepts either a `StorageAdapter` class or instance and will return either the instantiated class or the instance passed to it for further modification.

    test 'models can be told to persist via a storage adapter', ->
      class Shop extends Batman.Model
        @resourceName: 'shop'
        @persist TestStorageAdapter

      record = new Shop
      ok record.hasStorage()

    test '@persist returns the instantiated storage adapter', ->
      adapter = false
      class Shop extends Batman.Model
        @resourceName: 'shop'
        adapter = @persist TestStorageAdapter

      ok adapter instanceof Batman.StorageAdapter

    test '@persist accepts already instantiated storage adapters', ->
      adapter = new Batman.StorageAdapter
      adapter.someHandyConfigurationOption = true
      class Shop extends Batman.Model
        @resourceName: 'shop'
        @persist adapter

      record = new Shop
      ok record.hasStorage()

## @encode(keys...[, encoderObject : [Object|Function]])

`@encode` specifies a list of `keys` a model should expect from and send back to a storage adapter, and any transforms to apply to those attributes as they enter and exit the world of batman.js in the optional `encoderObject`.

The `encoderObject` should have an `encode` and/or a `decode` key which point to functions. The functions accept the "raw" data (the batman.js land value in the case of `encode`, and the backend land value in the case of `decode`), and should return the data suitable for the other side of the link. The functions should have the following signatures:

    encoderObject = {
      encode: (value, key, builtJSON, record) ->
      decode: (value, key, incomingJSON, outgoingObject, record) ->
    }

By default these functions are the identity functions. They apply no transformation. The arguments for `encode` functions are as follows:

 + `value` is the client side value of the `key` on the `record`
 + `key` is the key which the `value` is stored under on the `record`. This is useful when passing the same `encoderObject` which needs to pivot on what key is being encoded to different calls to `encode`.
 + `builtJSON` is the object which is modified by each encoder which will eventually be returned by `toJSON`. To send the server the encoded value under a different key than the `key`, modify this object by putting the value under the desired key, and return `undefined`.
 + `record` is the record on which `toJSON` has been called.

For `decode` functions:

 + `value` is the server side value of the `key` which will end up on the `record`.
 + `key` is the key which the `value` is stored under in the incoming JSON.
 + `incomingJSON` is the JSON which is being decoded into the `record`. This can be used to create compound key decoders.
 + `outgoingObject` is the object which is built up by the decoders and then `mixin`'d to the record.
 + `record` is the record on which `fromJSON` has been called.

The `encode` and `decode` keys can also be false to avoid using the default identity function encoder or decoder.

_Note_: `Batman.Model` subclasses have no encoders by default, except for one which automatically decodes the `primaryKey` of the model, which is usually `id`. To get any data into or out of your model, you must white-list the keys you expect from the server or storage attribute.

    test '@encode accepts a list of keys which are used during decoding', ->
      class Shop extends Batman.Model
        @resourceName: 'shop'
        @encode 'name', 'url', 'email', 'country'

      json = {name: "Snowdevil", url: "snowdevil.ca"}
      record = new Shop()
      record.fromJSON(json)
      equal record.get('name'), "Snowdevil"

    test '@encode accepts a list of keys which are used during encoding', ->
      class Shop extends Batman.Model
        @resourceName: 'shop'
        @encode 'name', 'url', 'email', 'country'

      record = new Shop(name: "Snowdevil", url: "snowdevil.ca")
      deepEqual record.toJSON(), {name: "Snowdevil", url: "snowdevil.ca"}

    test '@encode accepts custom encoders', ->
      class Shop extends Batman.Model
        @resourceName: 'shop'
        @encode 'name',
          encode: (name) -> name.toUpperCase()

      record = new Shop(name: "Snowdevil")
      deepEqual record.toJSON(), {name: "SNOWDEVIL"}

    test '@encode accepts custom decoders', ->
      class Shop extends Batman.Model
        @resourceName: 'shop'
        @encode 'name',
          decode: (name) -> name.replace('_', ' ')

      record = new Shop()
      record.fromJSON {name: "Snow_devil"}
      equal record.get('name'), "Snow devil"

    test '@encode can be passed an encoderObject with false to prevent the default encoder or decoder', ->
      class Shop extends Batman.Model
        @resourceName: 'shop'
        @encode 'name', {encode: false, decode: (x) -> x}
        @encode 'url'

      record = new Shop()
      record.fromJSON {name: "Snowdevil", url: "snowdevil.ca"}
      equal record.get('name'), 'Snowdevil'
      equal record.get('url'), "snowdevil.ca"
      deepEqual record.toJSON(), {url: "snowdevil.ca"}, 'The name key is absent because of encode: false'

Some more handy examples:

    test '@encode can be used to turn comma separated values into arrays', ->
      class Post extends Batman.Model
        @resourceName: 'post'
        @encode 'tags',
          decode: (string) -> string.split(', ')
          encode: (array) -> array.join(', ')

      record = new Post()
      record.fromJSON({tags: 'new, hot, cool'})
      deepEqual record.get('tags'), ['new', 'hot', 'cool']
      deepEqual record.toJSON(), {tags: 'new, hot, cool'}

    test '@encode can be used to turn arrays into sets', ->
      class Post extends Batman.Model
        @resourceName: 'post'
        @encode 'tags',
          decode: (array) -> new Batman.Set(array...)
          encode: (set) -> set.toArray()

      record = new Post()
      record.fromJSON({tags: ['new', 'hot', 'cool']})
      ok record.get('tags') instanceof Batman.Set
      deepEqual record.toJSON(), {tags: ['new', 'hot', 'cool']}

## @validate(keys...[, options : [Object|Function]])

Validations allow a model to be marked as `valid` or `invalid` based on a set of programmatic rules. By validating a model's data before it gets to the server we can provide immediate feedback to the user about what they have entered and forgo waiting on a round trip to the server. `validate` allows the attachment of validations to the model on particular keys, where the validation is either a built in one (invoked by use of options to pass to them) or a custom one (invoked by use of a custom function as the second argument).

_Note_: Validation in batman.js is always asynchronous, despite the fact that none of the validations may use an asynchronous operation to check for validity. This is so that the API is consistent regardless of the validations used.

Built in validators are attached by calling `@validate` with options designating how to calculate the validity of the key:

    test '@validate accepts options to check for validity', ->
      QUnit.expect(0)
      class Post extends Batman.Model
        @resourceName: 'post'
        @validate 'title', 'body', {presence: true}

The built in validation options are listed below:

 + `presence : boolean`: Assert that the string value is existent (not undefined or null) and has length greather than 0.
 + `numeric : true`: Assert that the value is or can be coerced into a number using `parseFloat`.
 + `greaterThan : number`: Assert that the value is greater than the given number.
 + `greaterThanOrEqualTo : number`: Assert that the value is greater than or equal to the given number.
 + `equalTo : number`: Assert that the value is equal to the given number.
 + `lessThan : number`: Assert that the value is less than the given number.
 + `lessThanOrEqualTo : number`: Assert that the value is less than or equal to the given number.
 + `minLength : number`: Assert that the value's `length` property is greater than the given number.
 + `maxLength : number`: Assert that the value's `length` property is less than the given number.
 + `length : number`: Assert that the value's `length` property is exactly the given number.
 + `lengthWithin : [number, number]` or `lengthIn : [number, number]`: Assert that the value's `length` property is within the ranger specified by the given array of two numbers, where the first number is the lower bound and the second number is the upper bound.
 + `inclusion : in : [list, of, acceptable, values]`: Assert that the value is equal to one of the values in an array.
 + `exclusion : in : [list, of, unacceptable, values]`: Assert that the value is not equal to any of the values in an array.

Custom validators should have the signature `(errors, record, key, callback)`. The arguments are as follows:

 + `errors`: an `ErrorsSet` instance which expects to have `add` called on it to add errors to the model
 + `record`: the record being validated
 + `key`: the key to which the validation has been attached
 + `callback`: a function to call once validation has been completed. Calling this function is __mandatory__.

See `Model::validate` for information on how to get a particular record's validity.

## @loaded : Set

The `loaded` set is available on every model class and holds every model instance seen by the system in order to function as an identity map. Successfully loading or saving individual records or batches of records will result in those records being added to the `loaded` set. Destroying instances will remove records from the identity set.

    test 'the loaded set stores all records seen', ->
      class Post extends Batman.Model
        @resourceName: 'post'
        @persist TestStorageAdapter
        @encode 'name'

      ok Post.get('loaded') instanceof Batman.Set
      equal Post.get('loaded.length'), 0
      post = new Post()
      post.save()
      equal Post.get('loaded.length'), 1

    test 'the loaded adds new records caused by loads and removes records caused by destroys', ->
      class Post extends Batman.Model
        @resourceName: 'post'
        @encode 'name'

      adapter = new TestStorageAdapter(Post)
      adapter.storage =
          'posts1': {name: "One", id:1}
          'posts2': {name: "Two", id:2}

      Post.persist(adapter)
      Post.load()
      equal Post.get('loaded.length'), 2
      post = false
      Post.find(1, (err, result) -> post = result)
      post.destroy()
      equal Post.get('loaded.length'), 1

## @all : Set

The `all` set is an alias to the `loaded` set but with an added implicit `load` on the model. `Model.get('all')` will synchronously return the `loaded` set and asynchronously call `Model.load()` without options to load a batch of records and populate the set originally returned (the `loaded` set) with the records returned by the server.

_Note_: The notion of "all the records" is relative only to the client. It completely depends on the storage adapter in use and any backends which they may contact to determine what comes back during a `Model.load`. This means that if for example your API paginates records, the set found in `all` may hold on the first 50 records instead of the entire backend set.

`all` is useful for listing every instance of a model in a view, and since the `loaded` set will change when the `load` returns, it can be safely bound to.

    asyncTest 'the all set asynchronously fetches records when gotten', ->
      class Post extends Batman.Model
        @resourceName: 'post'
        @encode 'name'

      adapter = new AsyncTestStorageAdapter(Post)
      adapter.storage =
          'posts1': {name: "One", id:1}
          'posts2': {name: "Two", id:2}

      Post.persist(adapter)
      equal Post.get('all.length'), 0, "The synchronously returned set is empty"
      delay ->
        equal Post.get('all.length'), 2, "After the async load the set is populated"

## @clear() : Set

`Model.clear()` empties that `Model`'s identity map. This is useful for tests and other unnatural situations where records new to the system are guaranteed to be as such.

    test 'clearing a model removes all records from the identity map', ->
      class Post extends Batman.Model
        @resourceName: 'post'
        @encode 'name'

      adapter = new TestStorageAdapter(Post)
      adapter.storage =
          'posts1': {name: "One", id:1}
          'posts2': {name: "Two", id:2}
      Post.persist(adapter)
      Post.load()
      equal Post.get('loaded.length'), 2
      Post.clear()
      equal Post.get('loaded.length'), 0, "After clear() the loaded set is empty"

## @find(id, callback : Function) : Model

`Model.find()` retrieves a record with the specified `id` from the storage adapter and calls back with an error if one occurred and the record if the operation was successful. `find` delegates to the storage adapter the `Model` has been `@persist`ed with, so it is up to the storage adapter's semantics to determine what type of errors may return and the timeline on which the callback may be called. The `callback` is a required function which should adopt the node style callback signature which accepts two arguments: an error, and the record asked for. `find` returns an "unloaded" record which, following the load completion, will be populated with the data from the storage adapter.

_Note_: `find` gives two results to calling code: one immediately, and one later. `find` returns a record synchronously as it is called and calls back with a record, and importantly these two records are __not__ guaranteed to be the same instance. This is because batman.js maps the identities of incoming and outgoing records such that there is only ever one canonical instance representing a record, which is useful so bindings are always bound to the same thing. In practice, this means that calling code should use the record `find` calls back with if anything is going to bind to that object, which is most of the time. The returned record however remains useful for state inspection and bookkeeping.

    asyncTest '@find calls back the requested model if no error occurs', ->
      class Post extends Batman.Model
        @resourceName: 'post'
        @encode 'name'
        @persist AsyncTestStorageAdapter,
          storage:
            'posts2': {name: "Two", id:2}

      post = Post.find 2, (err, result) ->
        throw err if err
        post = result
      equal post.get('name'), undefined
      delay ->
        equal post.get('name'), "Two"

_Note_: `find` must be passed a callback function. This is for two reasons: calling code must be aware that `find`'s return value is not necessarily the canonical instance, and calling code must be able to handle errors.

    asyncTest '@find calls back with the error if an error occurs', ->
      class Post extends Batman.Model
        @resourceName: 'post'
        @encode 'name'
        @persist AsyncTestStorageAdapter

      error = false
      post = Post.find 3, (err, result) ->
        error = err
      delay ->
        ok error instanceof Error

## @load(options = {}, callback : Function)

`Model.load()` retrieves an array of records according to the given `options` from the storage adapter and calls back with an error if one occurred and the set of records if the operation was successful. `load` delegates to the storage adapter the `Model` has been `@persist`ed with, so it is up to the storage adapter's semantics to determine what the options do, what kind of errors may arise, and the timeline on which the callback may be called. The `callback` is a required function which should adopt the node style callback signature which accepts two arguments, an error, and the array of records. `load` returns undefined.

For the two main `StorageAdapter`s batman.js provides, the `options` do different things:

- For `Batman.LocalStorage`, `options` act as a filter. The adapter will scan all the records in `localStorage` and return only those records which match all the key/value pairs given in the options.
- For `Batman.RestStorage`, `options` are serialized into query parameters on the `GET` request.

It takes a callback with two arguments: error and the array of loaded records.

    asyncTest '@load calls back an array of records retrieved from the storage adapter', ->
      class Post extends Batman.Model
        @resourceName: 'post'
        @encode 'name'
        @persist TestStorageAdapter,
          storage:
            'posts1': {name: "One", id:1}
            'posts2': {name: "Two", id:2}

      posts = false
      Post.load (err, result) ->
        throw err if err
        posts = result

      delay ->
        equal posts.length, 2
        equal posts[0].get('name'), "One"

    asyncTest '@load calls back with an empty array if no records are found', ->
      class Post extends Batman.Model
        @resourceName: 'post'
        @encode 'name'
        @persist TestStorageAdapter, storage: []

      posts = false
      Post.load (err, result) ->
        throw err if err
        posts = result

      delay ->
        equal posts.length, 0

## @create(attributes = {}, callback) : Model

## @findOrCreate(attributes = {}, callback) : Model

## id : value

## dirtyKeys : Set

## errors : ErrorsSet

A record's errors are accessible with `get('errors')`, which returns a `Batman.Set` of `Batman.ValidationError`s.

- `user.get('errors')` returns the errors on the `user` record
- `user.get('errors.length')` returns the number of errors, total

You can also access the errors for a specific attribute of the record:

- `user.get('errors.email_address')` returns the errors on the `email_address` attribute
- `user.get('errors.email_address.length')` returns the number of errors on the `email_address` attribute

## constructor(idOrAttributes = {}) : Model

## isNew() : boolean

## updateAttributes(attributes) : Model

## toString() : string

## toJSON() : Object

## fromJSON() : Model

## toParam() : value

## state() : string

## hasStorage() : boolean

## load(options = {}, callback)

## save(options = {}, callback)

## destroy(options = {}, callback)

## validate(callback)

`Model::validate` checks the model against the validations declared in the model definition (see `Model@validate` above). Its callback takes two arguments:

- Any JavaScript errors
- A `Batman.ErrorsSet`

This method takes a callback with two arguments: any JavaScript error that occurs, then the `Batman.ErrorsSet` corresponding to the validation action.
For example:

    asyncTest "validate(callback) will call the callback only after all keys have been validated", 4, ->
      class Product extends Batman.Model
        @validate 'name', 'price', presence: yes

      p = new Product
      p.validate (js_error, validation_errors) ->
        throw js_error if js_error
        equal validation_errors.length, 2
        equal p.get('errors.length'), 2
        equal p.get('errors.name.length'), 1
        equal p.get('errors.price.length'), 1

# Batman.ValidationError

A `Batman.ValidationError` is a `Batman.Object`. It is initialized with an `attribute` and a `message`.  It also responds to `fullMessage`:

    test "ValidationError should humanize attribute in the full message", ->
      error = new Batman.ValidationError("fooBarBaz", "isn't valid")
      equal error.get('fullMessage'), "Foo bar baz isn't valid"

# Batman.ErrorsSet

A `Batman.ErrorsSet` is a `Batman.Set` populated with `Batman.ValidationErrors`.

- `user.get('errors')` returns the errors on the `user` record
- `user.get('errors.length')` returns the number of errors, total

You can also access the errors for a specific attribute of the record:

- `user.get('errors.email_address')` returns the errors on the `email_address` attribute
- `user.get('errors.email_address.length')` returns the number of errors on the `email_address` attribute

`Batman.ErrorsSet::add` is overridden for convenience. It takes an attribute name and a message, which it uses to
create a new `Batman.ValidationError` then it adds that error to the `Batman.ErrorsSet`.

# Batman.Model

For a general explanation of `Batman.Model` and it works, see [the guide](/docs/models.html).

_Note_: This documentation uses the term _model_ to refer to the class `Model`
or a `Model` subclass, and the term _record_ to refer to one instance of a
model.

## @primaryKey : string

`primaryKey` is a class level configuration option to change which key batman.js uses as the primary key. Change the option using `set`, like so:

    test 'primary key can be set using @set', ->
      class Shop extends Batman.Model
        @set 'primaryKey', 'shop_id'

      equal Shop.get('primaryKey'), 'shop_id'

The `primaryKey` is what batman.js uses to compare instances to see if they represent the same domain-level object: if two records have the same value at the key specified by `primaryKey`, only one will be in the identity map. The key specified by `primaryKey` is also used by the associations system when determining if a record is related to another record, and by the remote storage adapters to generate URLs for records.

_Note_: The default primaryKey is 'id'.

## @storageKey : string

`storageKey` is a class level option which gives the storage adapters something to interpolate into their specific key generation schemes. In the case of `LocalStorage` or `SessionStorage` adapters, the `storageKey` defines what namespace to store this record under in the `localStorage` or `sessionStorage` host objects, and with the case of the `RestStorage` family of adapters, the `storageKey` assists in URL generation. See the documentation for the storage adapter of your choice for more information.

The default `storageKey` is `null`.

## @persist(mechanism : StorageAdapter) : StorageAdapter

`@persist` is how a `Model` subclass is told to persist itself by means of a `StorageAdapter`. `@persist` accepts either a `StorageAdapter` class or instance and will return either the instantiated class or the instance passed to it for further modification.

    test 'models can be told to persist via a storage adapter', ->
      class Shop extends Batman.Model
        @resourceName: 'shop'
        @persist TestStorageAdapter

      record = new Shop
      ok record.hasStorage()

    test '@persist returns the instantiated storage adapter', ->
      adapter = false
      class Shop extends Batman.Model
        @resourceName: 'shop'
        adapter = @persist TestStorageAdapter

      ok adapter instanceof Batman.StorageAdapter

    test '@persist accepts already instantiated storage adapters', ->
      adapter = new Batman.StorageAdapter
      adapter.someHandyConfigurationOption = true
      class Shop extends Batman.Model
        @resourceName: 'shop'
        @persist adapter

      record = new Shop
      ok record.hasStorage()

## @encode(keys...[, encoderObject : [Object|Function]])

`@encode` specifies a list of `keys` a model should expect from and send back to a storage adapter, and any transforms to apply to those attributes as they enter and exit the world of batman.js in the optional `encoderObject`.

The `encoderObject` should have an `encode` and/or a `decode` key which point to functions. The functions accept the "raw" data (the batman.js land value in the case of `encode`, and the backend land value in the case of `decode`), and should return the data suitable for the other side of the link. The functions should have the following signatures:

    encoderObject = {
      encode: (value, key, builtJSON, record) ->
      decode: (value, key, incomingJSON, outgoingObject, record) ->
    }

By default these functions are the identity functions. They apply no transformation. The arguments for `encode` functions are as follows:

 + `value` is the client side value of the `key` on the `record`
 + `key` is the key which the `value` is stored under on the `record`. This is useful when passing the same `encoderObject` which needs to pivot on what key is being encoded to different calls to `encode`.
 + `builtJSON` is the object which is modified by each encoder which will eventually be returned by `toJSON`. To send the server the encoded value under a different key than the `key`, modify this object by putting the value under the desired key, and return `undefined`.
 + `record` is the record on which `toJSON` has been called.

For `decode` functions:

 + `value` is the server side value of the `key` which will end up on the `record`.
 + `key` is the key which the `value` is stored under in the incoming JSON.
 + `incomingJSON` is the JSON which is being decoded into the `record`. This can be used to create compound key decoders.
 + `outgoingObject` is the object which is built up by the decoders and then `mixin`'d to the record.
 + `record` is the record on which `fromJSON` has been called.

The `encode` and `decode` keys can also be false to avoid using the default identity function encoder or decoder.

_Note_: `Batman.Model` subclasses have no encoders by default, except for one which automatically decodes the `primaryKey` of the model, which is usually `id`. To get any data into or out of your model, you must white-list the keys you expect from the server or storage attribute.

    test '@encode accepts a list of keys which are used during decoding', ->
      class Shop extends Batman.Model
        @resourceName: 'shop'
        @encode 'name', 'url', 'email', 'country'

      json = {name: "Snowdevil", url: "snowdevil.ca"}
      record = new Shop()
      record.fromJSON(json)
      equal record.get('name'), "Snowdevil"

    test '@encode accepts a list of keys which are used during encoding', ->
      class Shop extends Batman.Model
        @resourceName: 'shop'
        @encode 'name', 'url', 'email', 'country'

      record = new Shop(name: "Snowdevil", url: "snowdevil.ca")
      deepEqual record.toJSON(), {name: "Snowdevil", url: "snowdevil.ca"}

    test '@encode accepts custom encoders', ->
      class Shop extends Batman.Model
        @resourceName: 'shop'
        @encode 'name',
          encode: (name) -> name.toUpperCase()

      record = new Shop(name: "Snowdevil")
      deepEqual record.toJSON(), {name: "SNOWDEVIL"}

    test '@encode accepts custom decoders', ->
      class Shop extends Batman.Model
        @resourceName: 'shop'
        @encode 'name',
          decode: (name) -> name.replace('_', ' ')

      record = new Shop()
      record.fromJSON {name: "Snow_devil"}
      equal record.get('name'), "Snow devil"

    test '@encode can be passed an encoderObject with false to prevent the default encoder or decoder', ->
      class Shop extends Batman.Model
        @resourceName: 'shop'
        @encode 'name', {encode: false, decode: (x) -> x}
        @encode 'url'

      record = new Shop()
      record.fromJSON {name: "Snowdevil", url: "snowdevil.ca"}
      equal record.get('name'), 'Snowdevil'
      equal record.get('url'), "snowdevil.ca"
      deepEqual record.toJSON(), {url: "snowdevil.ca"}, 'The name key is absent because of encode: false'

Some more handy examples:

    test '@encode can be used to turn comma separated values into arrays', ->
      class Post extends Batman.Model
        @resourceName: 'post'
        @encode 'tags',
          decode: (string) -> string.split(', ')
          encode: (array) -> array.join(', ')

      record = new Post()
      record.fromJSON({tags: 'new, hot, cool'})
      deepEqual record.get('tags'), ['new', 'hot', 'cool']
      deepEqual record.toJSON(), {tags: 'new, hot, cool'}

    test '@encode can be used to turn arrays into sets', ->
      class Post extends Batman.Model
        @resourceName: 'post'
        @encode 'tags',
          decode: (array) -> new Batman.Set(array...)
          encode: (set) -> set.toArray()

      record = new Post()
      record.fromJSON({tags: ['new', 'hot', 'cool']})
      ok record.get('tags') instanceof Batman.Set
      deepEqual record.toJSON(), {tags: ['new', 'hot', 'cool']}

## @validate(keys...[, options : [Object|Function]])

Validations allow a model to be marked as `valid` or `invalid` based on a set of programmatic rules. By validating a model's data before it gets to the server we can provide immediate feedback to the user about what they have entered and forgo waiting on a round trip to the server. `validate` allows the attachment of validations to the model on particular keys, where the validation is either a built in one (invoked by use of options to pass to them) or a custom one (invoked by use of a custom function as the second argument).

_Note_: Validation in batman.js is always asynchronous, despite the fact that none of the validations may use an asynchronous operation to check for validity. This is so that the API is consistent regardless of the validations used.

Built in validators are attached by calling `@validate` with options designating how to calculate the validity of the key:

    test '@validate accepts options to check for validity', ->
      QUnit.expect(0)
      class Post extends Batman.Model
        @resourceName: 'post'
        @validate 'title', 'body', {presence: true}

The built in validation options are listed below:

 + `presence : boolean`: Assert that the string value is existent (not undefined or null) and has length greather than 0.
 + `numeric : true`: Assert that the value is or can be coerced into a number using `parseFloat`.
 + `greaterThan : number`: Assert that the value is greater than the given number.
 + `greaterThanOrEqualTo : number`: Assert that the value is greater than or equal to the given number.
 + `equalTo : number`: Assert that the value is equal to the given number.
 + `lessThan : number`: Assert that the value is less than the given number.
 + `lessThanOrEqualTo : number`: Assert that the value is less than or equal to the given number.
 + `minLength : number`: Assert that the value's `length` property is greater than the given number.
 + `maxLength : number`: Assert that the value's `length` property is less than the given number.
 + `length : number`: Assert that the value's `length` property is exactly the given number.
 + `lengthWithin : [number, number]` or `lengthIn : [number, number]`: Assert that the value's `length` property is within the ranger specified by the given array of two numbers, where the first number is the lower bound and the second number is the upper bound.
 + `inclusion : in : [list, of, acceptable, values]`: Assert that the value is equal to one of the values in an array.
 + `exclusion : in : [list, of, unacceptable, values]`: Assert that the value is not equal to any of the values in an array.

Custom validators should have the signature `(errors, record, key, callback)`. The arguments are as follows:

 + `errors`: an `ErrorsSet` instance which expects to have `add` called on it to add errors to the model
 + `record`: the record being validated
 + `key`: the key to which the validation has been attached
 + `callback`: a function to call once validation has been completed. Calling this function is __mandatory__.

See `Model::validate` for information on how to get a particular record's validity.

## @loaded : Set

The `loaded` set is available on every model class and holds every model instance seen by the system in order to function as an identity map. Successfully loading or saving individual records or batches of records will result in those records being added to the `loaded` set. Destroying instances will remove records from the identity set.

    test 'the loaded set stores all records seen', ->
      class Post extends Batman.Model
        @resourceName: 'post'
        @persist TestStorageAdapter
        @encode 'name'

      ok Post.get('loaded') instanceof Batman.Set
      equal Post.get('loaded.length'), 0
      post = new Post()
      post.save()
      equal Post.get('loaded.length'), 1

    test 'the loaded adds new records caused by loads and removes records caused by destroys', ->
      class Post extends Batman.Model
        @resourceName: 'post'
        @encode 'name'

      adapter = new TestStorageAdapter(Post)
      adapter.storage =
          'posts1': {name: "One", id:1}
          'posts2': {name: "Two", id:2}

      Post.persist(adapter)
      Post.load()
      equal Post.get('loaded.length'), 2
      post = false
      Post.find(1, (err, result) -> post = result)
      post.destroy()
      equal Post.get('loaded.length'), 1

## @all : Set

The `all` set is an alias to the `loaded` set but with an added implicit `load` on the model. `Model.get('all')` will synchronously return the `loaded` set and asynchronously call `Model.load()` without options to load a batch of records and populate the set originally returned (the `loaded` set) with the records returned by the server.

_Note_: The notion of "all the records" is relative only to the client. It completely depends on the storage adapter in use and any backends which they may contact to determine what comes back during a `Model.load`. This means that if for example your API paginates records, the set found in `all` may hold on the first 50 records instead of the entire backend set.

`all` is useful for listing every instance of a model in a view, and since the `loaded` set will change when the `load` returns, it can be safely bound to.

    asyncTest 'the all set asynchronously fetches records when gotten', ->
      class Post extends Batman.Model
        @resourceName: 'post'
        @encode 'name'

      adapter = new AsyncTestStorageAdapter(Post)
      adapter.storage =
          'posts1': {name: "One", id:1}
          'posts2': {name: "Two", id:2}

      Post.persist(adapter)
      equal Post.get('all.length'), 0, "The synchronously returned set is empty"
      delay ->
        equal Post.get('all.length'), 2, "After the async load the set is populated"

## @clear() : Set

`Model.clear()` empties that `Model`'s identity map. This is useful for tests and other unnatural situations where records new to the system are guaranteed to be as such.

    test 'clearing a model removes all records from the identity map', ->
      class Post extends Batman.Model
        @resourceName: 'post'
        @encode 'name'

      adapter = new TestStorageAdapter(Post)
      adapter.storage =
          'posts1': {name: "One", id:1}
          'posts2': {name: "Two", id:2}
      Post.persist(adapter)
      Post.load()
      equal Post.get('loaded.length'), 2
      Post.clear()
      equal Post.get('loaded.length'), 0, "After clear() the loaded set is empty"

## @find(id, callback : Function) : Model

`Model.find()` retrieves a record with the specified `id` from the storage adapter and calls back with an error if one occurred and the record if the operation was successful. `find` delegates to the storage adapter the `Model` has been `@persist`ed with, so it is up to the storage adapter's semantics to determine what type of errors may return and the timeline on which the callback may be called. The `callback` is a required function which should adopt the node style callback signature which accepts two arguments: an error, and the record asked for. `find` returns an "unloaded" record which, following the load completion, will be populated with the data from the storage adapter.

_Note_: `find` gives two results to calling code: one immediately, and one later. `find` returns a record synchronously as it is called and calls back with a record, and importantly these two records are __not__ guaranteed to be the same instance. This is because batman.js maps the identities of incoming and outgoing records such that there is only ever one canonical instance representing a record, which is useful so bindings are always bound to the same thing. In practice, this means that calling code should use the record `find` calls back with if anything is going to bind to that object, which is most of the time. The returned record however remains useful for state inspection and bookkeeping.

    asyncTest '@find calls back the requested model if no error occurs', ->
      class Post extends Batman.Model
        @resourceName: 'post'
        @encode 'name'
        @persist AsyncTestStorageAdapter,
          storage:
            'posts2': {name: "Two", id:2}

      post = Post.find 2, (err, result) ->
        throw err if err
        post = result
      equal post.get('name'), undefined
      delay ->
        equal post.get('name'), "Two"

_Note_: `find` must be passed a callback function. This is for two reasons: calling code must be aware that `find`'s return value is not necessarily the canonical instance, and calling code must be able to handle errors.

    asyncTest '@find calls back with the error if an error occurs', ->
      class Post extends Batman.Model
        @resourceName: 'post'
        @encode 'name'
        @persist AsyncTestStorageAdapter

      error = false
      post = Post.find 3, (err, result) ->
        error = err
      delay ->
        ok error instanceof Error

## @load(options = {}, callback : Function)

`Model.load()` retrieves an array of records according to the given `options` from the storage adapter and calls back with an error if one occurred and the set of records if the operation was successful. `load` delegates to the storage adapter the `Model` has been `@persist`ed with, so it is up to the storage adapter's semantics to determine what the options do, what kind of errors may arise, and the timeline on which the callback may be called. The `callback` is a required function which should adopt the node style callback signature which accepts two arguments, an error, and the array of records. `load` returns undefined.

For the two main `StorageAdapter`s batman.js provides, the `options` do different things:

- For `Batman.LocalStorage`, `options` act as a filter. The adapter will scan all the records in `localStorage` and return only those records which match all the key/value pairs given in the options.
- For `Batman.RestStorage`, `options` are serialized into query parameters on the `GET` request.

It takes a callback with two arguments: error and the array of loaded records.

    asyncTest '@load calls back an array of records retrieved from the storage adapter', ->
      class Post extends Batman.Model
        @resourceName: 'post'
        @encode 'name'
        @persist TestStorageAdapter,
          storage:
            'posts1': {name: "One", id:1}
            'posts2': {name: "Two", id:2}

      posts = false
      Post.load (err, result) ->
        throw err if err
        posts = result

      delay ->
        equal posts.length, 2
        equal posts[0].get('name'), "One"

    asyncTest '@load calls back with an empty array if no records are found', ->
      class Post extends Batman.Model
        @resourceName: 'post'
        @encode 'name'
        @persist TestStorageAdapter, storage: []

      posts = false
      Post.load (err, result) ->
        throw err if err
        posts = result

      delay ->
        equal posts.length, 0

## @create(attributes = {}, callback) : Model

## @findOrCreate(attributes = {}, callback) : Model

## id : value

## dirtyKeys : Set

## errors : ErrorsSet

## constructor(idOrAttributes = {}) : Model

## isNew() : boolean

## updateAttributes(attributes) : Model

## toString() : string

## toJSON() : Object

## fromJSON() : Model

## toParam() : value

## state() : string

## hasStorage() : boolean

## load(options = {}, callback)

## save(options = {}, callback)

## destroy(options = {}, callback)

## validate(callback)

# Batman.ValidationError

# Batman.ErrorsSet


in. jokes

in. jokes

#! /usr/bin/env coffee

The expander supports multiple asyncronous functions.

To achieve that it needed to do some peculiar things.

Things that [some](https://www.google.co.za/search?q=uptight+people&espv=2&biw=1063&bih=1058&source=lnms&tbm=isch&sa=X&ei=q6CJVYTyIpPB7Ab95YLQBA&ved=0CAYQ_AUoAQ#tbm=isch&q=uptight) may disaprove of.

Like wearing [spandex in public](https://www.google.co.za/search?q=spandex+in+public+nuts&espv=2&biw=1063&bih=1058&tbm=isch&source=lnms&sa=X&ei=5Z-JVez6KeWY7gbl_oCYAg&ved=0CAYQ_AUoAQ#tbm=isch&q=spandex+in+public).

It broke the expansion (to be eval'd) into pieces and substituted a array ($e) for each function

The results of the division are loaded into a variable called `spandex`...

Which happens to be in scope at eval.

    require('../')

    $$in (arg) ->

        ### in(arg).as {{1}}###

        console.log arg

#! /usr/bin/env coffee

The expander supports multiple asyncronous functions, to achieve that needed it needed to do some strange things.

Things that some may disaprove of.

Like wearing [spandex in public](https://www.google.co.za/search?q=spandex+in+public+nuts&espv=2&biw=1063&bih=1058&tbm=isch&source=lnms&sa=X&ei=5Z-JVez6KeWY7gbl_oCYAg&ved=0CAYQ_AUoAQ#tbm=isch&q=spandex+in+public).


Add stub match data to the debug dataset

Debug Routines
==============

Occasionally, software has bugs. It's also often quite convenient
to be able to fix those bugs.

    window.DEBUG = {}

Debug Data Collections
----------------------

This is a collection of debug data, for great debugging, and debug.

    window.DEBUG.loadDebugData = ->
        dateBase = do DayBase
        WS.message.push
            type: 'mode'
            mode: 'judge'
        WS.message.push
            type: 'override'
            override: null
        WS.message.push
            type: 'teams'
            teams:
                aaa:
                    college: 'College A'
                    name: 'Team A'
                    notes: 'Bees'
                    present: yes
                bbb:
                    college: 'College B'
                    name: 'Team B'
                    notes: ''
                    present: yes
                ccc:
                    college: 'College C'
                    name: 'Team C Alpha'
                    notes: ''
                    present: no
                ccc2:
                    college: 'College C'
                    name: 'Team C Beta'
                    notes: ''
                    present: yes
                ddd:
                    college: 'College D'
                    name: 'Team D'
                    notes: 'eyes'
                    present: yes
        WS.message.push
            type: 'day'
            schedule: [
                {key: 'w', start: dateBase + 3600*9, displayName: 'Doors Open', association: 0}
                {key: 'x', start: dateBase + 3600*9 + 1800, displayName: 'Tinker Time', association: 0}
                {key: 'y', start: dateBase + 3600*11, displayName: 'Briefing', association: 3}
                {key: 'z', start: dateBase + 3600*12, displayName: 'League', association: 1}
            ]

        WS.message.push
            type: 'match'
            schedule: [
                {key: 'w', start: dateBase + 3600*12 + 3*60, teams: ['aaa', 'bbb', 'ccc', 'ddd'], scores: [4, 2.5, 2.5, 0], knockout_stage: null}
                {key: 'x', start: dateBase + 3600*12 + 8*60, teams: ['bbb', 'aaa', 'ddd', 'ccc2'], scores: null, knockout_stage: null}
                {key: 'y', start: dateBase + 3600*12 + 13*60, teams: ['ccc2', 'aaa', 'ddd', 'bbb'], scores: null, knockout_stage: null}
                {key: 'z', start: dateBase + 3600*12 + 18*60, teams: ['aaa', 'bbb', 'ccc2', 'ddd'], scores: null, knockout_stage: null}
            ]


docs(document): disable syntax highlighting for query parameters

    schema   = require './helper/schema'
    sentry   = require './db/sentry'
    Document = require './model/Document'

    JSONStream = require 'JSONStream'

## param()

    exports.param = (req, res, next, id) ->
      return res.status(400).json message: 'Invalid ObjectId' if not /^[a-f0-9]{24}$/.test id
      return next() if req.method is 'OPTIONS'

      req.doc = new Document(req.type, id).once('error', next).once 'ready', ->
        req.isOwner = @exists() and req.user.tilbyder is @get 'tilbyder'

        if not @exists() or (@get('status') isnt 'Offentlig' and not req.isOwner)
          return res.status(404).json message: 'Not Found' if req.method isnt 'HEAD'
          return res.status(404).end()

        next()

## all()

    exports.all = (req, res, next) ->
      res.set 'X-Cache-Hit', req.doc.wasCacheHit()
      res.set 'ETag', "\"#{req.doc.get 'checksum'}\""
      res.set 'Last-Modified', new Date(req.doc.get 'endret').toUTCString()

      if req.method not in ['GET', 'HEAD'] and not req.isOwner
        return res.status(403).json message: 'Request Denied'

      if req.get 'If-Match'
        return res.status(412).end() if req.doc.isNoneMatch req.get 'If-Match'

      else if req.get 'If-None-Match'
        return res.status(304).end() if req.doc.isMatch req.get 'If-None-Match'

      else
        if req.doc.isNotModifiedSince req.get 'If-Modified-Since'
          return res.status(304).end()

        if req.doc.isModifiedSince req.get 'If-Unmodified-Since'
          return res.status(412).end()

      next()

## OPTIONS

```http
OPTIONS /{type}/{id}
```

    exports.options = (req, res, next) ->
      res.set 'Access-Control-Allow-Methods', [
        'HEAD', 'GET', 'PUT', 'PATCH', 'DELETE'
      ].join ', '
      res.set 'Access-Control-Allow-Headers', [
        'Content-Type'
        'If-Match'
        'If-Modified-Since'
        'If-None-Match'
        'If-Unmodified-Since'
      ].join ', '
      res.sendStatus 204

## HEAD and GET

```http
HEAD /{type}/{id}
GET /{type}/{id}
```

    exports.head = exports.get = (req, res, next) ->
      return res.sendStatus 200 if req.method is 'HEAD'

      opts =
        query: $or: [{status: 'Offentlig'}, {tilbyder: req.user.tilbyder}]
        fields: {}

### Fields Projection

```none
&fields=field1[,field2[,..]]
```

Private (`privat.`) fields are hidden unless the current API user is the owner
of the document. This is to prevent unauthorized information disclosure.

      opts.fields.privat = false if not req.isOwner

If you only want some of the document properties returned you can use the
`fields` query parameter to control the projection of document properties.
Multiple fields must be comma separated without any additional spacing.

This projection also applies to expanded sub-documents when using the `&expand=`
query parameter below.

      if req.query?.fields
        opts.fields[field] = true for field in req.query.fields.split ','
        opts.fields.privat = false if not req.isOwner

The list of default fields below will always be returned for compliance reasons.

        opts.fields = Object.assign opts.fields,
          endret: true
          lisens: true
          status: true
          navn  : true
          tilbyder  : true
          navngiving: true

### Sub-document Expansion

```none
&expand=field1[,field2[..]]
```

Sub-document expansion is an easy and convenient way to get connected documents
such as `grupper`, `bilder`, and `områder` as their full objects instead of a
list of `ObjectIDs`. It works by setting the `expand` query parameter to the
fields to expand.

**Rate limit**

Sub-document expansion will decrease your remaining API rate limit with `1` per
collection expanded in addition to the request itself. Thus, if you request a
document (1) with two collection expanded (2) your remaining API rate limit will
be decremented with 3. This is to encurrage resonable expansion of relevant
collections only.

**Order and limit**

Sub-document expansion will return at most 10 first sub-documents for each
collection expanded and out of order. Only sub-documents avaiable to the current
API user will be return as sub-documents my not be published or may have been
deleted.

      if req.query?.expand
        opts.expand = req.query.expand.split ','

### Sub-document Limit

```none
&limit={n}
```

If you wisth to return less sub-documents in order to increase response time and
body size you may do so by using the `limit` query parameter. This will affect
all sub-documents expanded by the `expand` query parameter.

      if req.query?.limit and parseInt req.query.limit, 10
        opts.limit = parseInt req.query.limit, 10

---

      req.doc.getExpanded opts, (err, doc) ->
        return next err if err
        res.json doc

## PUT and PATCH

```http
PUT /{type}/{id}
PATCH /{type}/{id}
```

    exports.patch = exports.put = (req, res, next) ->
      return res.status(400).json message: 'Body is missing' if Object.keys(req.body).length is 0
      return res.status(400).json message: 'Body should be a JSON Hash' if req.body instanceof Array

      req.body.tilbyder = req.user.tilbyder

      method = (if req.method is 'PUT' then 'replace' else 'update')
      req.doc[method] req.body, (err, warn, data) ->
        if err
          return next(err) if err.name isnt 'ValidationError'

          sentry.captureDocumentError req, err

          return res.status(422).json
            document: req.body
            message: 'Validation Failed'
            errors: err.details #TODO(starefossen) document this

        res.set 'ETag', "\"#{data.checksum}\""
        res.set 'Last-Modified', new Date(data.endret).toUTCString()

        return res.status(200).json
          document: data
          message: 'Validation Warnings' if warn.length > 0
          warnings: warn if warn.length > 0

## DELETE

```http
DELETE /{type}/{id}
```

    exports.delete = (req, res, next) ->
      req.doc.delete (err) ->
        return next err if err
        return res.sendStatus 204

    schema   = require './helper/schema'
    sentry   = require './db/sentry'
    Document = require './model/Document'

    JSONStream = require 'JSONStream'

## param()

    exports.param = (req, res, next, id) ->
      return res.status(400).json message: 'Invalid ObjectId' if not /^[a-f0-9]{24}$/.test id
      return next() if req.method is 'OPTIONS'

      req.doc = new Document(req.type, id).once('error', next).once 'ready', ->
        req.isOwner = @exists() and req.user.tilbyder is @get 'tilbyder'

        if not @exists() or (@get('status') isnt 'Offentlig' and not req.isOwner)
          return res.status(404).json message: 'Not Found' if req.method isnt 'HEAD'
          return res.status(404).end()

        next()

## all()

    exports.all = (req, res, next) ->
      res.set 'X-Cache-Hit', req.doc.wasCacheHit()
      res.set 'ETag', "\"#{req.doc.get 'checksum'}\""
      res.set 'Last-Modified', new Date(req.doc.get 'endret').toUTCString()

      if req.method not in ['GET', 'HEAD'] and not req.isOwner
        return res.status(403).json message: 'Request Denied'

      if req.get 'If-Match'
        return res.status(412).end() if req.doc.isNoneMatch req.get 'If-Match'

      else if req.get 'If-None-Match'
        return res.status(304).end() if req.doc.isMatch req.get 'If-None-Match'

      else
        if req.doc.isNotModifiedSince req.get 'If-Modified-Since'
          return res.status(304).end()

        if req.doc.isModifiedSince req.get 'If-Unmodified-Since'
          return res.status(412).end()

      next()

## OPTIONS

```http
OPTIONS /{type}/{id}
```

    exports.options = (req, res, next) ->
      res.set 'Access-Control-Allow-Methods', [
        'HEAD', 'GET', 'PUT', 'PATCH', 'DELETE'
      ].join ', '
      res.set 'Access-Control-Allow-Headers', [
        'Content-Type'
        'If-Match'
        'If-Modified-Since'
        'If-None-Match'
        'If-Unmodified-Since'
      ].join ', '
      res.sendStatus 204

## HEAD and GET

```http
HEAD /{type}/{id}
GET /{type}/{id}
```

    exports.head = exports.get = (req, res, next) ->
      return res.sendStatus 200 if req.method is 'HEAD'

      opts =
        query: $or: [{status: 'Offentlig'}, {tilbyder: req.user.tilbyder}]
        fields: {}

### Fields Projection

```
&fields=field1[,field2[,..]]
```

Private (`privat.`) fields are hidden unless the current API user is the owner
of the document. This is to prevent unauthorized information disclosure.

      opts.fields.privat = false if not req.isOwner

If you only want some of the document properties returned you can use the
`fields` query parameter to control the projection of document properties.
Multiple fields must be comma separated without any additional spacing.

This projection also applies to expanded sub-documents when using the `&expand=`
query parameter below.

      if req.query?.fields
        opts.fields[field] = true for field in req.query.fields.split ','
        opts.fields.privat = false if not req.isOwner

The list of default fields below will always be returned for compliance reasons.

        opts.fields = Object.assign opts.fields,
          endret: true
          lisens: true
          status: true
          navn  : true
          tilbyder  : true
          navngiving: true

### Sub-document Expansion

```
&expand=field1[,field2[..]]
```

Sub-document expansion is an easy and convenient way to get connected documents
such as `grupper`, `bilder`, and `områder` as their full objects instead of a
list of `ObjectIDs`. It works by setting the `expand` query parameter to the
fields to expand.

**Rate limit**

Sub-document expansion will decrease your remaining API rate limit with `1` per
collection expanded in addition to the request itself. Thus, if you request a
document (1) with two collection expanded (2) your remaining API rate limit will
be decremented with 3. This is to encurrage resonable expansion of relevant
collections only.

**Order and limit**

Sub-document expansion will return at most 10 first sub-documents for each
collection expanded and out of order. Only sub-documents avaiable to the current
API user will be return as sub-documents my not be published or may have been
deleted.

      if req.query?.expand
        opts.expand = req.query.expand.split ','

### Sub-document Limit

```
&limit={n}
```

If you wisth to return less sub-documents in order to increase response time and
body size you may do so by using the `limit` query parameter. This will affect
all sub-documents expanded by the `expand` query parameter.

      if req.query?.limit and parseInt req.query.limit, 10
        opts.limit = parseInt req.query.limit, 10

---

      req.doc.getExpanded opts, (err, doc) ->
        return next err if err
        res.json doc

## PUT and PATCH

```http
PUT /{type}/{id}
PATCH /{type}/{id}
```

    exports.patch = exports.put = (req, res, next) ->
      return res.status(400).json message: 'Body is missing' if Object.keys(req.body).length is 0
      return res.status(400).json message: 'Body should be a JSON Hash' if req.body instanceof Array

      req.body.tilbyder = req.user.tilbyder

      method = (if req.method is 'PUT' then 'replace' else 'update')
      req.doc[method] req.body, (err, warn, data) ->
        if err
          return next(err) if err.name isnt 'ValidationError'

          sentry.captureDocumentError req, err

          return res.status(422).json
            document: req.body
            message: 'Validation Failed'
            errors: err.details #TODO(starefossen) document this

        res.set 'ETag', "\"#{data.checksum}\""
        res.set 'Last-Modified', new Date(data.endret).toUTCString()

        return res.status(200).json
          document: data
          message: 'Validation Warnings' if warn.length > 0
          warnings: warn if warn.length > 0

## DELETE

```http
DELETE /{type}/{id}
```

    exports.delete = (req, res, next) ->
      req.doc.delete (err) ->
        return next err if err
        return res.sendStatus 204


Explicit hash digest

Explicit hash digest

# Crypto

*Cryptographic helper functions.*

    crypto = require 'crypto'
    config = require 'config'
    Promise = require 'bluebird'

## crypto.encrypt

* (string) `message` - The message to encrypt.
* (optional string) `password` - The password to use to encrypt the message.
  Defaults to the site's global crypto key.

*AES encrypt a message with a password.*

    exports.encrypt = (message, password) ->

      new Promise (resolve, reject) ->

        cipher = crypto.createCipher(
          'aes256'
          password ? config.get 'packageSettings:shrub-core:cryptoKey'
        )

        cipherText = []
        cipherText.push cipher.update message, 'binary', 'hex'
        cipherText.push cipher.final 'hex'
        resolve cipherText.join ''

## crypto.decrypt

* (string) `message` - The message to decrypt.
* (optional string) `password` - The password to use to decrypt the message.
  Defaults to the site's global crypto key.

*AES decrypt a message with a password.*

    exports.decrypt = (message, password) ->

      new Promise (resolve, reject) ->

        decipher = crypto.createDecipher(
          'aes256'
          password ? config.get 'packageSettings:shrub-core:cryptoKey'
        )
        decipher.setAutoPadding false

        decipherText = []
        decipherText.push decipher.update message, 'hex', 'binary'
        decipherText.push decipher.final 'binary'
        decipherText = decipherText.join ''

        # Slice off any padding.
        if 16 >= code = decipherText.charCodeAt decipherText.length - 1
          decipherText = decipherText.slice 0, -code

        resolve decipherText

## crypto.hasher

CREDIT:
[https://gist.github.com/boronine/3548196](https://gist.github.com/boronine/3548196)
cha0s promisify'd it and made it work with Buffer objects.

* (object) `options` - The options to use. The options object may include the
  following values:
    * `plaintext`: The plaintext password to hash and return as `key`. If none
      is provided, an 8-character random plaintext password will be generated.
    * `salt`: The salt to hash the password with. If none is provided, a
      512-bit salt will be generated.
    * `iterations`: The number of iterations to use for the PBKDF. Defaults to
      10000\. **NOTE:** This ***must*** be the same number when generating and
      verifying hashes, otherwise verification will fail.

*Cryptographic authentication functionality.*

    exports.hasher = (options = {}) ->

Generate random 8-character base64 password if none provided

      unless options.plaintext?

        return exports.randomBytes(6).then((buffer) ->
          options.plaintext = buffer.toString 'base64'
          exports.hasher options
        )

Generate random 512-bit salt if no salt provided

      unless options.salt?

        return exports.randomBytes(64).then((buffer) ->
          options.salt = buffer
          exports.hasher options
        )

      options.digest ?= 'sha1'
      options.iterations ?= 10000

      exports.pbkdf2(
        options.plaintext, options.salt, options.iterations, 64, options.digest

      ).then (key) ->
        options.key = new Buffer key
        options

Promisify some useful node.js crypto functions.

    exports.pbkdf2 = Promise.promisify crypto.pbkdf2, crypto
    exports.randomBytes = Promise.promisify crypto.randomBytes, crypto

# Crypto

*Cryptographic helper functions.*

    crypto = require 'crypto'
    config = require 'config'
    Promise = require 'bluebird'

## crypto.encrypt

* (string) `message` - The message to encrypt.
* (optional string) `password` - The password to use to encrypt the message.
  Defaults to the site's global crypto key.

*AES encrypt a message with a password.*

    exports.encrypt = (message, password) ->

      new Promise (resolve, reject) ->

        cipher = crypto.createCipher(
          'aes256'
          password ? config.get 'packageSettings:shrub-core:cryptoKey'
        )

        cipherText = []
        cipherText.push cipher.update message, 'binary', 'hex'
        cipherText.push cipher.final 'hex'
        resolve cipherText.join ''

## crypto.decrypt

* (string) `message` - The message to decrypt.
* (optional string) `password` - The password to use to decrypt the message.
  Defaults to the site's global crypto key.

*AES decrypt a message with a password.*

    exports.decrypt = (message, password) ->

      new Promise (resolve, reject) ->

        decipher = crypto.createDecipher(
          'aes256'
          password ? config.get 'packageSettings:shrub-core:cryptoKey'
        )
        decipher.setAutoPadding false

        decipherText = []
        decipherText.push decipher.update message, 'hex', 'binary'
        decipherText.push decipher.final 'binary'
        decipherText = decipherText.join ''

        # Slice off any padding.
        if 16 >= code = decipherText.charCodeAt decipherText.length - 1
          decipherText = decipherText.slice 0, -code

        resolve decipherText

## crypto.hasher

CREDIT:
[https://gist.github.com/boronine/3548196](https://gist.github.com/boronine/3548196)
cha0s promisify'd it and made it work with Buffer objects.

* (object) `options` - The options to use. The options object may include the
  following values:
    * `plaintext`: The plaintext password to hash and return as `key`. If none
      is provided, an 8-character random plaintext password will be generated.
    * `salt`: The salt to hash the password with. If none is provided, a
      512-bit salt will be generated.
    * `iterations`: The number of iterations to use for the PBKDF. Defaults to
      10000\. **NOTE:** This ***must*** be the same number when generating and
      verifying hashes, otherwise verification will fail.

*Cryptographic authentication functionality.*

    exports.hasher = (options = {}) ->

Generate random 8-character base64 password if none provided

      unless options.plaintext?

        return exports.randomBytes(6).then((buffer) ->
          options.plaintext = buffer.toString 'base64'
          exports.hasher options
        )

Generate random 512-bit salt if no salt provided

      unless options.salt?

        return exports.randomBytes(64).then((buffer) ->
          options.salt = buffer
          exports.hasher options
        )

      # Node.js PBKDF2 forces sha1
      options.hash = 'sha1'
      options.iterations = options.iterations ? 10000

      exports.pbkdf2(
        options.plaintext, options.salt, options.iterations, 64

      ).then (key) ->
        options.key = new Buffer key
        options

Promisify some useful node.js crypto functions.

    exports.pbkdf2 = Promise.promisify crypto.pbkdf2, crypto
    exports.randomBytes = Promise.promisify crypto.randomBytes, crypto


Clean up cache documentation

Clean up cache documentation

    "use strict"

    redis    = require './db/redis'
    mongo    = require './db/mongo'
    ObjectID = require('mongodb').ObjectID

## getFilter()

Get data filter for object type.

### Params

* `String` type - object type to get filter for.
* `boolean` preventDefault - prevent default filter switch.

### Return

Returns a `String` key - `boolean` value `Object` where each key represent a
document field. The value determines if they field should be included or not.

Returns an empty `Object` if the `preventDefault` parameter is set to `true` and
no filter was found for the given `type`.

    getFilter = (type, preventDefault) ->

      dataFields =
        default:
          _id       : false
          tilbyder  : true
          endret    : true
          checksum  : true
          status    : true
          navn      : true
          bilder    : true
          grupper   : true

        bilder:
          _id       : false
          tilbyder  : true
          endret    : true
          checksum  : true
          status    : true
          navn      : true

      return dataFields[type] if dataFields[type]
      return {} if preventDefault
      return dataFields.default

## filterData()

Filter data for given type.

### Params

* `String` type - object type to filter data for.
* `Object` data - data to filter on.

### Return

Returns an `Object` with a subset of the original object containing only the
accepted object properties for the given object type.

### Todo

* [ ] Handle undefined values.

    filterData = (type, data) ->
      res = {}
      res[key] = data[key] for key,val of getFilter(type) when val is true and data[key]
      return res

## getDoc()

Get a document from MongoDB for given object type and object id.

This function will automaticly filter object keys according to type in order to
prevent fetching of uncesserary data.

### Params

* `String` type - object type to get document for.
* `String` id - object id for document.
* `function` cb - callback function.

### Callback

#### Params

* `Error` err - error object if lookup failed; otherwise `null`.
* `Object` doc - filtered document if found; otherwise `null`.

    getDoc = (type, id, cb) ->
      mongo[type].findOne {_id: new ObjectID(id)}, getFilter(type), cb

## set()

Store data object in Redis for a given cache key.

### Params

* `String` key - cache key to store data for.
* `Object` data - data to store for cache key.
* `function` cb - callback function.

### Callback

#### Params

* `Error` err - error object if Redis write failed; otherwise `null`.
* `Object` data - the original data as it was stored in Redis.

    set = (key, data, cb) ->
      redis.hmset key, data, (err) -> cb(err, data)

## get()

Retrive data from cache for given a cache key.

### Params

* `String` key - cache key to get data for.
* `function` cb - callback function

### Callback

#### Params

* `Error` err -  error object if Redis lookup failed, otherwise `null`.
* `Object` data - data retrieved from Redis if found; otherwise `null`.

    get = (key, cb) ->
      redis.hgetall key, cb

## setForType()

Store data in Redis for given object type and object id.

This function will automaticly remove object properties from input data in order
to match the object type cache preferences as defined in [#getFilter()](#getFilter).

### Params

* `String` type - object type to set cache data for.
* `String` id - object id to set cache data for.
* `Object` data - data store in cache for type and id.
* `function` cb - callback function.

### Callback

#### Params

* `Error` err - error object if Redis failed; otherwise `null`.
* `Object` data - the filtered data object as it was stored in Redis.

    setForType = (type, id, data, cb) ->
      set "#{type}:#{id}", filterData(type, data), cb

## getForType()

Get data from Redis for object type and object id.

`NB` This function will return `Arrays` if the document is retrived directly
from MongoDB. `Arrays` stored in Redis will be returned as comma seperated
strings.

### Params

* `String` type - object type to get cache data for.
* `String` id - object id to get cache data for.
* `function` cb - callback function.

### Callback

#### Params

* `Error` err - error object if Redis failed; otherwise `null`.
* `Object` data - the data object returned from Redis or Mongodb.

    getForType = (type, id, cb) ->
      get "#{type}:#{id}", (err, data) ->
        return cb null, data, true if data

        getDoc type, id, (err, data) ->
          return cb err, null, false if err

          data = status: 'Slettet' if not data

          # We don't need to use setForType() here since data is already formated
          # when using getDoc()

          set "#{type}:#{id}", data, (err, data) ->
            cb err, data, false

## Export

Expose the functions we want to be public by exporting them.

    module.exports =
      getFilter : getFilter
      filterData: filterData
      getDoc    : getDoc
      set       : set
      get       : get
      setForType: setForType
      getForType: getForType

    "use strict"

    redis    = require './db/redis'
    mongo    = require './db/mongo'
    ObjectID = require('mongodb').ObjectID

## getFilter()

Get data filter for object type.

### Params

* `String` type - object type to get filter for.
* `boolean` preventDefault - prevent default filter switch.

### Return

Returns a `String` key - `boolean` value `Object` where each key represent a
document field. The value determines if they field should be included or not.

Returns an empty `Object` (`{}`) if the `preventDefault` parameter is set to
`true` and no filter was found for the given `type`.

    getFilter = (type, preventDefault) ->

      dataFields =
        default:
          _id       : false
          tilbyder  : true
          endret    : true
          checksum  : true
          status    : true
          navn      : true
          bilder    : true
          grupper   : true

        bilder:
          _id       : false
          tilbyder  : true
          endret    : true
          checksum  : true
          status    : true
          navn      : true

      return dataFields[type] if dataFields[type]
      return {} if preventDefault
      return dataFields.default

## filterData()

Filter data for given type.

### Params

* `String` type - object type to filter data for.
* `Object` data - data to filter on.

### Return

Returns an `Object` with a subset of the original object containing only the
accepted object properties for the given object type.

### Todo

* [] Handle undefined values.

    filterData = (type, data) ->
      res = {}
      res[key] = data[key] for key,val of getFilter(type) when val is true and data[key]
      return res

## getDoc()

Get a document from MongoDB for given object type and object id.

This function will automaticly filter object keys according to type in order to
prevent fetching of uncesserary data.

### Params

* `String` type - object type to get document for.
* `String` id - object id for document.
* `function` cb - callback function.

### Callback

#### Params

* `Error` err - error object if lookup failed; otherwise `null`.
* `Object` doc - filtered document if found; otherwise `null`.

    getDoc = (type, id, cb) ->
      mongo[type].findOne {_id: new ObjectID(id)}, getFilter(type), cb

## set()

Store data object in Redis for a given cache key.

### Params

* `String` key - cache key to store data for.
* `Object` data - data to store for cache key.
* `function` cb - callback function.

### Callback

#### Params

* `Error` err - error object if Redis write failed; otherwise `null`.
* `Object` data - the original data as it was stored in Redis.

    set = (key, data, cb) ->
      redis.hmset key, data, (err) -> cb(err, data)

## get()

Retrive data from cache for given a cache key.

### Params

* `String` key - cache key to get data for.
* `function` cb - callback function

### Callback

#### Params

* `Error` err -  error object if Redis lookup failed, otherwise `null`.
* `Object` data - data retrieved from Redis if found; otherwise `null`.

    get = (key, cb) ->
      redis.hgetall key, cb

## setForType()

Store data in Redis for given object type and object id.

This function will automaticly remove object properties from input data in order
to match the object type cache preferences as defined in [#getFilter()](#getFilter).

### Params

* `String` type - object type to set cache data for.
* `String` id - object id to set cache data for.
* `Object` data - data store in cache for type and id.
* `function` cb - callback function.

### Callback

#### Params

* `Error` err - error object if Redis failed; otherwise `null`.
* `Object` data - the filtered data object as it was stored in Redis.

    setForType = (type, id, data, cb) ->
      set "#{type}:#{id}", filterData(type, data), cb

## getForType()

Get data from Redis for object type and object id.

`NB` This function will return `Arrays` if the document is retrived directly
from MongoDB. `Arrays` stored in Redis will be returned as comma seperated
strings.

### Params

* `String` type - object type to get cache data for.
* `String` id - object id to get cache data for.
* `function` cb - callback function.

### Callback

#### Params

* `Error` err - error object if Redis failed; otherwise `null`.
* `Object` data - the data object returned from Redis or Mongodb.

    getForType = (type, id, cb) ->
      get "#{type}:#{id}", (err, data) ->
        return cb null, data, true if data

        getDoc type, id, (err, data) ->
          return cb err, null, false if err

          data = status: 'Slettet' if not data

          # We don't need to use setForType() here since data is already formated
          # when using getDoc()

          set "#{type}:#{id}", data, (err, data) ->
            cb err, data, false

## Export

Expose the functions we want to be public by exporting them.

    module.exports =
      getFilter : getFilter
      filterData: filterData
      getDoc    : getDoc
      set       : set
      get       : get
      setForType: setForType
      getForType: getForType


Restoring justice

Restoring justice

People can not wait for so much time and get the prize – image((. Cats have to move !

Autoform callback hooks

    AutoForm.hooks
      getInLine:
        after:
          method: (error, result) ->
            if error?
              console.log err
            else
              Session.set 'queueEntry', result

    Template.waiting.helpers
      nameSchema: -> NameSchema
      lineLength: ->

Hacks, should probably be using Tracker for this

        lineLength = this.queueMeta.nextTicketNumber - this.queueMeta.currentlyServingTicketNumber - 1
        lineLength = 0 if lineLength < 0
        return lineLength
      queueEntry: ->
        Session.get 'queueEntry'
      html: -> this.queueMeta.html
      isBeingServed: ->
        queueEntry = Session.get 'queueEntry'
        return if not queueEntry?

Get new gifUrl

        Session.set 'gifUrl',"http://thecatapi.com/api/images/get?format=src&type=gif&size=med&time=#{new Date().getTime()}"

Clear queueEntry if queueMeta.currentlyServingTicketNumber is > queueEntry.ticketNumber

        if this.queueMeta.currentlyServingTicketNumber > queueEntry.ticketNumber
          Session.set 'queueEntry', null

        this.queueMeta.currentlyServingTicketNumber is queueEntry.ticketNumber and
          this.queueMeta.timeCurrentTicketExpires > moment.utc().toDate()

    Template.waiting.events
      'click .queueInLine': (event) ->

Return immediatly if the user is already queued. More logic on the server, but
this will help.

        return if (Session.get 'queueEntry')?

Call the meteor method to get queued.

        Meteor.call 'getInQueue', 'fakeName', (error, result) ->
          if error?
            console.log err
          else
            Session.set 'queueEntry', result

      Template.waiting.rendered = ->
        $('body').css 'background-color', '#eee'

Autoform callback hooks

    AutoForm.hooks
      getInLine:
        after:
          method: (error, result) ->
            if error?
              console.log err
            else
              Session.set 'queueEntry', result

    Template.waiting.helpers
      nameSchema: -> NameSchema
      lineLength: ->

Hacks, should probably be using Tracker for this

        lineLength = this.queueMeta.nextTicketNumber - this.queueMeta.currentlyServingTicketNumber - 1
        lineLength = 0 if lineLength < 0
        return lineLength
      queueEntry: ->
        Session.get 'queueEntry'
      html: -> this.queueMeta.html
      isBeingServed: ->
        queueEntry = Session.get 'queueEntry'
        return if not queueEntry?

Get new gifUrl

        Session.set 'gifUrl',"http://thecatapi.com/api/images/get?format=src&type=jpg&size=med&time=#{new Date().getTime()}"

Clear queueEntry if queueMeta.currentlyServingTicketNumber is > queueEntry.ticketNumber

        if this.queueMeta.currentlyServingTicketNumber > queueEntry.ticketNumber
          Session.set 'queueEntry', null

        this.queueMeta.currentlyServingTicketNumber is queueEntry.ticketNumber and
          this.queueMeta.timeCurrentTicketExpires > moment.utc().toDate()

    Template.waiting.events
      'click .queueInLine': (event) ->

Return immediatly if the user is already queued. More logic on the server, but
this will help.

        return if (Session.get 'queueEntry')?

Call the meteor method to get queued.

        Meteor.call 'getInQueue', 'fakeName', (error, result) ->
          if error?
            console.log err
          else
            Session.set 'queueEntry', result

      Template.waiting.rendered = ->
        $('body').css 'background-color', '#eee'


Hard code font size to a sensible value

Hard code font size to a sensible value

Dynamically determining the font size was more trouble that it was worth

    PngRenderer = require './png_renderer'

    class PngStepCount extends PngRenderer

      do_render: (ctx, path) =>
        width  = @config.width
        height = @config.height

        for step, i in path
          ctx.font      = '12pt Arial'
          ctx.textAlign = @config.step_count.text.align
          ctx.fillStyle = @config.step_count.text.color

          x = (width  * 0.5) + (width  * step.x)
          y = (height * 0.5) + (height * step.y)

          ctx.beginPath()
          ctx.fillText i, x, y

    module.exports = PngStepCount

    PngRenderer = require './png_renderer'

    class PngStepCount extends PngRenderer

      do_render: (ctx, path) =>
        width  = @config.width
        height = @config.height

        for step, i in path
          ctx.font      = "#{Math.floor height * 0.25}pt Arial"
          ctx.textAlign = @config.step_count.text.align
          ctx.fillStyle = @config.step_count.text.color

          x = (width  * 0.5) + (width  * step.x)
          y = (height * 0.5) + (height * step.y)

          ctx.beginPath()
          ctx.fillText i, x, y

    module.exports = PngStepCount