/js-builder-decorator

Decorate any Javascript object with a convenient builder, which returns an immutable object

Primary LanguageJavaScriptMIT LicenseMIT

js-builder-decorator

Decorate any Javascript object with a convenient builder, which returns an immutable object with getters.

Build Status npm version npm version

Standard usage:

var StudentClass = function(){
  this.name = "Some default name";
  this.age = undefined;
  this.address = {};
  this.prettyName = function(){};
};
var StudentClassBuilder = BuilderDecorator(StudentClass);

var student = StudentClassBuilder()
  .name("John")
  .age(17)
  .address({postcode: "90210"})
  .prettyName(function(){ return "Hi, I'm " + this.name() + "!"; })
  .build();

student.name();       // "John"
student.age();        // 17
student.address();    // {postcode: "90210"}
student.prettyName(); // function(){ return "Hi, I'm " + this.name() + "!"; }

Requiring in Node:

var BuilderDecorator = require('js-builder-decorator').BuilderDecorator;

Locking functions after build

var StudentClassBuilderLocked = BuilderDecorator(StudentClass, {lockFunctionsAfterBuild: true});
var student = StudentClassBuilderLocked()
  .name("John")
  .prettyName(function(){ return "Hi, I'm " + this.name() + "!"; })
  .build();

student.name();       // "John"
student.prettyName(); // "Hi, I'm John!"

Enforcing no null fields

// Throwing exception if any field isn't set
var StudentClassBuilderNoNulls = BuilderDecorator(StudentClass, {allFieldsMustBeSet: true});

try {
  var student = StudentClassBuilderNoNulls().build(); // This throws an exception
} catch (E) {
  console.log(E); // The following fields were not set: name,age,address,prettyName
}

Installation

If you have Node.js installed, run npm install js-builder-decorator in your project directory.
Else, you can download the latest version from Github here.