Class: BuilderApi

BuilderApi

new BuilderApi()

Provides the DSL for model generation, it supports to modes of model definitions:

Definition object

This is the preferred way of describing a model behavior.

A model description object looks like this:

restmod.model({

  // MODEL CONFIGURATION

  $config: {
    name: 'resource',
    primaryKey: '_id'
  },

  // ATTRIBUTE MODIFIERS AND RELATIONS

  propWithDefault: { init: 20 },
  propWithDecoder: { decode: 'date', chain: true },
  hasManyRelation: { hasMany: 'Other' },
  hasOneRelation: { hasOne: 'Other' },

  // HOOKS

  $hooks: {
    'after-create': function() {
    }
  },

  // METHODS

  $extend: {
    Record: {
      instanceMethod: function() {
      }
    },
    Model: {
      scopeMethod: function() {
      }
    }
  }
});

Special model configuration variables can be set by using a $config block:

restmod.model({

  $config: {
    name: 'resource',
    primaryKey: '_id'
  }

 });

With the exception of model configuration variables and properties starting with a special character (@ or ~), each property in the definition object asigns a behavior to the same named property in a model's record.

To modify a property behavior assign an object with the desired modifiers to a definition property with the same name. Builtin modifiers are:

The following built in property modifiers are provided (see each mapped-method docs for usage information):

For relations modifiers take a look at RelationBuilderApi

For other extended bundled methods check out the ExtendedBuilderApi

If other kind of value (different from object or function) is passed to a definition property, then it is considered to be a default value. (same as calling BuilderApi#define at a definition function)

var Model = restmod.model('/', {
  im20: 20 // same as { init: 20 }
})

// then say hello is available for use at model records
Model.$new().im20; // 20

To add/override methods from the record api, use the $extend block:

var Model = restmod.model('/', {
  $extend: {
    sayHello: function() { alert('hello!'); }
  }
})

// then say hello is available for use at model records
Model.$new().sayHello();

To add a static method or a collection method, you must specify the method scope: , prefix the definition key with ^, to add it to the model collection prototype, prefix it with * static/collection methods to the Model, prefix the definition property name with @ (same as calling BuilderApi#scopeDefine at a definition function).

var Model = restmod.model('/', {
  $extend: {
    'Collection.count': function() { return this.length; },  // scope is set using a prefix

    Model: {
      sayHello: function() { alert('hello!'); } // scope is set using a block
    }
})

// then the following call will be valid.
Model.sayHello();
Model.$collection().count();

More information about method scopes can be found in BuilderApi#define

To add hooks to the Model lifecycle events use the $hooks block:

var Model = restmod.model('/', {
  $hooks: {
    'after-init': function() { alert('hello!'); }
  }
})

// the after-init hook is called after every record initialization.
Model.$new(); // alerts 'hello!';

Definition function

The definition function gives complete access to the model builder api, every model builder function described in this page can be called from the definition function by referencing this.

restmod.model('', function() {
  this.attrDefault('propWithDefault', 20)
      .attrAsCollection('hasManyRelation', 'ModelName')
      .on('after-create', function() {
        // do something after create.
      });
});
Source:
  • module/builder.js, line 14

Methods

attrComputed(_attr, _fn) → {BuilderApi}

Sets a computed value for an attribute.

Computed values are set only on object construction phase. Computed values are always masked

Parameters:
Name Type Description
_attr string

Attribute name

_fn function

Function that returns value

Source:
  • module/factory.js, line 497
Returns:

self

Type
BuilderApi

attrDecoder(_name, _filter, _filterParam, _chain) → {BuilderApi}

Assigns a decoding function/filter to a given attribute.

Parameters:
Name Type Description
_name string

Attribute name

_filter string | function

filter or function to register

_filterParam mixed

Misc filter parameter

_chain boolean

If true, filter is chained to the current attribute filter.

Source:
  • module/serializer.js, line 276
Returns:

self

Type
BuilderApi

attrDefault(_attr, _init) → {BuilderApi}

Sets the default value for an attribute.

Defaults values are set only on object construction phase.

if _init is a function, then its evaluated every time the default value is required.

Parameters:
Name Type Description
_attr string

Attribute name

_init mixed

Defaulf value / iniline function

Source:
  • module/factory.js, line 480
Returns:

self

Type
BuilderApi

attrEncoder(_name, _filter, _filterParam, _chain) → {BuilderApi}

Assigns a encoding function/filter to a given attribute.

Parameters:
Name Type Description
_name string

Attribute name

_filter string | function

filter or function to register

_filterParam mixed

Misc filter parameter

_chain boolean

If true, filter is chained to the current attribute filter.

Source:
  • module/serializer.js, line 298
Returns:

self

Type
BuilderApi

attribute(_name, _description) → {BuilderApi}

Sets an attribute properties.

This method uses the attribute modifiers mapping to call proper modifiers on the argument.

For example, using the following description on the createdAt attribute

{ decode: 'date', param; 'YY-mm-dd' }

Is the same as calling

builder.attrDecoder('createdAt', 'date', 'YY-mm-dd')

Parameters:
Name Type Description
_name string

Attribute name

_description object

Description object

Source:
  • module/builder.js, line 296
Returns:

self

Type
BuilderApi

attrMap(_attr, _serverName) → {BuilderApi}

Sets an attribute mapping.

Allows a explicit server to model property mapping to be defined.

For example, to map the response property stats.created_at to model's created property.

builder.attrMap('created', 'stats.created_at');

It's also posible to use a wildcard '*' as server name to use the default name decoder as server name. This is used to force a property to be processed on decode/encode even if its not present on request/record (respectively), by doing this its posible, for example, to define a dynamic property that is generated automatically before the object is send to the server.

Parameters:
Name Type Description
_attr string

Attribute name

_serverName string

Server (request/response) property name

Source:
  • module/serializer.js, line 218
Returns:

self

Type
BuilderApi

attrMask(_attr, _mask) → {BuilderApi}

Sets an attribute mask.

An attribute mask prevents the attribute to be loaded from or sent to the server on certain operations.

The attribute mask is a string composed by: C: To prevent attribute from being sent on create R: To prevent attribute from being loaded from server * U: To prevent attribute from being sent on update

For example, the following will prevent an attribute to be send on create or update:

builder.attrMask('readOnly', 'CU');

If a true boolean value is passed as mask, then 'CRU' will be used If a false boolean valus is passed as mask, then mask will be removed

Parameters:
Name Type Description
_attr string

Attribute name

_mask boolean | string

Attribute mask

Source:
  • module/serializer.js, line 256
Returns:

self

Type
BuilderApi

attrMeta(_name, _metadata) → {BuilderApi}

Registers attribute metadata.

Parameters:
Name Type Description
_name string

Attribute name

_metadata object

Attribute metadata

Source:
  • module/factory.js, line 512
Returns:

self

Type
BuilderApi

attrVolatile(_name, _isVolatile) → {BuilderApi}

Makes an attribute volatile, a volatile attribute is deleted from source after encoding.

Parameters:
Name Type Description
_name string

Attribute name

_isVolatile boolean

defaults to true, if set to false then the attribute is no longer volatile.

Source:
  • module/serializer.js, line 318
Returns:

self

Type
BuilderApi

define(_where, _fun, _api) → {BuilderApi}

Adds methods to the model

This method allows to extend the different model API's.

The following API's can be extended using this method: Model: The static API, affects the Model object itself. Record: Affects each record generated by the model. Collection: Affects each collection generated by the model. Scope: Affects both the static API and collections. * Resource: Affects records and collections.

If no api is given

If no scope is given, By default this method extends the Record prototype. If called with an object instead of a function it can be used to extend the collection and the type with specific implementations.

Usage:

restmod.mixin(function() {
  this.define('myRecordMethod', function() {})
      .define('Model.myStaticMethod', function() {})
      .define('Collection', { }); // object to extend collection api with
});

It is posible to override an existing method using define, if overriden, the old method can be called using this.$super inside de new method.

Parameters:
Name Type Description
_where string
_fun function

Function to define or object with particular implementations

_api string

One of the api names listed above, if not given defaults to 'Record'

Source:
  • module/factory.js, line 558
Returns:

self

Type
BuilderApi

describe(_description) → {BuilderApi}

Parses a description object, calls the proper builder method depending on each property description type.

Parameters:
Name Type Description
_description object

The description object

Source:
  • module/builder.js, line 198
Returns:

self

Type
BuilderApi

extend(_name, _fun, _mapping) → {BuilderApi}

Extends the builder DSL

Adds a function to de builder and alternatively maps the function to an attribute definition keyword that can be later used when calling define or attribute.

Mapping works as following:

// Given the following call builder.extend('testAttr', function(_attr, _test, _param1, param2) { // wharever.. }, ['test', 'testP1', 'testP2']);

// A call to builder.attribute('chapter', { test: 'hello', testP1: 'world' });

// Its equivalent to builder.testAttr('chapter', 'hello', 'world');

The method can also be passed an object with various methods to be added.

Parameters:
Name Type Description
_name string | object

function name or object to merge

_fun function

function

_mapping array

function mapping definition

Source:
  • module/builder.js, line 265
Returns:

self

Type
BuilderApi

on(_hook, _do) → {BuilderApi}

Adds an event hook

Hooks are used to extend or modify the model behavior, and are not designed to be used as an event listening system.

The given function is executed in the hook's context, different hooks make different parameters available to callbacks.

Parameters:
Name Type Description
_hook string

The hook name, refer to restmod docs for builtin hooks.

_do function

function to be executed

Source:
  • module/factory.js, line 611
Returns:

self

Type
BuilderApi