Code coverage report for src/definition.js

Statements: 100% (93 / 93)      Branches: 100% (54 / 54)      Functions: 100% (15 / 15)      Lines: 100% (93 / 93)     

All files » src/ » definition.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 2381 47           47           47           47           47           47           47               47   23 1     22 20 1     19 19                   47 42 42                   47 34 33   34             47 28   28 30 14 16 2 14 2 8 2           28                       47 43   43 26 26 2   24 24   2       24 2     22     1 13 13 13       43 28 15 13 13     28       15 11                     47     47 18 16 2 1   1         46 46 46 17 17 29 1     45 1   44 1     43     43 43   22 1   21 40           42 42   26 1   25 31         41       47       1
var Definition = function Definition(id, conf, container) {
  var self = this;
 
  /**
   * the id of the definition
   * @type {string}
   */
  self.id = id;
 
  /**
   * The callable that creates the service
   * @type {Function}
   */
  self.fn = false;
 
  /**
   * The arguments that will be send to the callable when called, order matters
   * @type {Array}
   */
  self.args = [];
 
  /**
   * The tags that the service will receive
   * @type {Array}
   */
  self.tags = [];
 
  /**
   * Contains the last created instance of the service, this is reused when the service is a shared service
   * @type {Boolean}
   */
  self.service = false;
 
  /**
   * Indicate wether the service behaves like a singleton; returning the same instance on repeated requests
   * @type {Boolean}
   */
  self.shared = false;
 
  /**
   * Create an instance from this definition
   * 
   * @method retrieve()
   * @return {mixed}
   */
  self.retrieve = function retrieve() {
 
    if(self.shared === true && self.service !== false) {
      return self.service;
    }
 
    var service = self.fn();
    if(service === undefined) {
      throw new Error('"'+id+'" service returned "'+undefined+'" on instantiation.');
    }
 
    self.service = service;
    return service;
  };
 
  /**
   * Add an argument (at the end) to the definition
   *
   * @method addArgument
   * @param {mixed} arg
   * @chainable
   */
  self.addArgument = function addArgument(arg) {
    self.args.push(arg);
    return self;
  };
 
  /**
   * Tag the service
   *
   * @method addTag()
   * @param {string} tag
   * @chainable
   */
  self.addTag = function addTag(tag) {
    if(self.tags.indexOf(tag) === -1)
      self.tags.push(tag);
 
    return self;
  };
 
  /**
   * Resolve arguments that are container ids
   * @return {Array} the resolved arguments
   */
  self.resolveArguments = function resolveArguments(arr) {
    arr = typeof arr !== 'undefined' ? arr : self.args;
 
    arr.forEach(function(arg, i){
      if(container.isId(arg)) {
        arr[i] = container.get(arg.replace(container.idPrefix, ''));
      } else if(Array.isArray(arg)) {
        arr[i] = self.resolveArguments(arg);
      } else if(arg.constructor == Object) {
        Object.keys(arg).forEach(function(k){
          if(container.isId(arg[k]))
            arg[k] = container.get(arg[k].replace(container.idPrefix, ''));
        });
      }
 
    });
 
    return arr;
  };
 
  /**
   * Create an callable that can creates instances for this definitions
   *
   * @method
   * @private
   * @param  {string} fnParam the container parameter that contains the constructor or factory function
   * @param  {string} type either 'c' for constructor or 'f' for factory
   * @return {Function}
   */
  self._createCallable = function(fnParam, type) {
    var res = false;
 
    var getCheckCallable = function(p) {
      var fn = false;
      if(typeof p === 'function') {
        fn = p;
      } else {
        try {
          fn = container.getParameter(p.replace(container.idPrefix, ''));
        } catch(e) {
          throw new Error('Whene trying to instanciate service "'+self.id+'", the parameter specifying the '+((type == 'f') ? ('factory') : ('constructor'))+': "'+fnParam+'" did not exist.');
        }
      }
      
      if(typeof fn !== 'function') {
        throw new Error('Whene trying to instanciate service "'+self.id+'", the parameter specifying the '+((type == 'f') ? ('factory') : ('constructor'))+': "'+fnParam+'" did not return a function, instead received: "'+fn+'"');
      }
 
      return fn;
    };
 
    function neu(constructor, args) {
        var instance = Object.create(constructor.prototype);
        var result = constructor.apply(instance, args);
        return typeof result === 'object' ? result : instance;
    }
 
    //constructor type use new
    if(type === 'c') {
      res = function() {      
        var _c = new getCheckCallable(fnParam);
        var _args = self.resolveArguments();
        return neu(_c, _args); 
      };
 
      return res;
    } 
 
    //factory type just call it
    return function() {      
        return getCheckCallable(fnParam).apply(container, self.resolveArguments()); //create using factory fn
    };
    
  };
 
  /**
   * Apply an defintion configuration
   * @param  {Object} conf
   * @return {Definition}
   * @chainable
   */
  self.configure = function(conf) {
 
    //shared
    if(conf.shared !== undefined) {
        if(String(conf.shared).toLowerCase() === 'true') {
          self.shared = true;
        } else if(String(conf.shared).toLowerCase() === 'false') {
          self.shared = false;
        } else {
          throw new Error('Configuration of "'+self.id+'" shared should be an boolean, received: "'+conf+'"');
        }
    }
 
    //constructing
    var fnParam = conf.constructorFn;
    var type = 'c';
    if(fnParam === undefined) {
      fnParam = conf.factoryFn;
      type = 'f';
    } else if(conf.factoryFn !== undefined) {
      throw new Error('Configuration of "'+self.id+'" should specify a constructor OR an factory function, not both - received: "'+conf+'"');
    }
 
    if(fnParam === undefined)
      throw new Error('Configuration of "'+self.id+'" must either specify an constructor or an factory function - received: "'+conf+'"');
 
    if(container.isId(fnParam) === false && typeof fnParam !== 'function') {
      throw new Error('Constructor or an factory function of "'+self.id+'" should be specified using a parameter id - received: "'+fnParam+'"');
    }
 
    self.fn = self._createCallable(fnParam, type);
 
    //arguments
    var args = conf.arguments;
    if(args !== undefined) {
 
      if(!Array.isArray(args))
        throw new Error('Instantiation arguments of "'+self.id+'" should be specified as an array - received: "'+args+'"');
 
      args.forEach(function(arg){
        self.addArgument(arg);
      });
 
    }
 
    //tags
    var tags = conf.tags;
    if(tags !== undefined) {
 
      if(!Array.isArray(tags))
        throw new Error('Service tags of "'+self.id+'" should be specified as an array - received: "'+tags+'"');
 
      tags.forEach(function(tag){
        self.addTag(tag);
      });
 
    }
 
    return self;
  };
 
  //configure the definition with the provided argument
  self.configure(conf);
 
};
 
module.exports = Definition;