all files / lib/resolver/ creator.js

100% Statements 18/18
100% Branches 4/4
100% Functions 3/3
100% Lines 18/18
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                                                               
"use strict";
var assert = require('../util').assert;
var ResolutionError = require('../ResolutionError');
 
/**
 * Creates a new component instance using a call to <code>Object.create</code>
 * passing the component as the prototype. An optional argument is accepted
 * which is the <code>properties</code> argument to <code>Object.create</code>.
 * The argument can either be the properties object, or a string dependency key
 * pointing to the properties object.
 *
 * @function
 * @exports Resolver:creator
 * @throws ResolutionError
 */
module.exports = function creator(ctx, res, next) {
  res.instance(false);
 
  var comp = ctx.component();
  assert.type(comp,
    'object',
    'creator resolver component must be an object',
    ResolutionError);
 
  var props = this.args()[0];
 
  function result(resolvedProps) {
    if (resolvedProps) {
      assert.type(resolvedProps,
        'object',
        "create properties must be an object",
        ResolutionError);
    }
    var instance = Object.create(comp, resolvedProps);
    res.resolve(instance);
    next();
  }
 
  if (typeof props === 'string') {
    ctx.resolve(props)
      .then(result)
      .catch(function(err) {
        res.fail(err);
        next();
      });
  } else {
    result(props);
  }
};