all files / lib/ waterline.js

87.85% Statements 94/107
64.71% Branches 22/34
100% Functions 23/23
95.79% Lines 91/95
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 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283             176×           176×     176×   176×                                                           249×   249×                             174×     174× 174× 174×     174×                   174×     174×     174×     174×     263× 263×       263×   263×     174×       174× 174×     174×   174× 263× 15×     174× 174× 174×             174× 174×   174× 263×     263×   263× 1168×       263× 263×     263× 263× 263× 263×     174×         174× 176× 176× 176×     176×     18× 27×       18×     18× 67× 67× 67×     67× 67×       18× 18× 18×           174× 174× 174× 174×                                                 174×                                                       174× 263× 263×         174×   263×      
var _ = require('lodash');
var async = require('async');
var Schema = require('waterline-schema');
var Connections = require('./waterline/connections');
var CollectionLoader = require('./waterline/collection/loader');
var COLLECTION_DEFAULTS = require('./waterline/collection/defaults');
var hasOwnProperty = require('./waterline/utils/helpers').object.hasOwnProperty;
 
/**
 * Waterline
 */
 
var Waterline = module.exports = function() {
 
  Iif (!(this instanceof Waterline)) {
    return new Waterline();
  }
 
  // Keep track of all the collections internally so we can build associations
  // between them when needed.
  this._collections = [];
 
  // Keep track of all the active connections used by collections
  this._connections = {};
 
  return this;
};
 
/*
 ***********************************************************
 * Modules that can be extended
 ***********************************************************/
 
// Collection to be extended in your application
Waterline.Collection = require('./waterline/collection');
 
// Model Instance, returned as query results
Waterline.Model = require('./waterline/model');
 
/*
 ***********************************************************
 * Prototype Methods
 ***********************************************************/
 
/**
 * loadCollection
 *
 * Loads a new Collection. It should be an extended Waterline.Collection
 * that contains your attributes, instance methods and class methods.
 *
 * @param {Object} collection
 * @return {Object} internal models dictionary
 * @api public
 */
 
Waterline.prototype.loadCollection = function(collection) {
 
  // Cache collection
  this._collections.push(collection);
 
  return this._collections;
};
 
/**
 * initialize
 *
 * Creates an initialized version of each Collection and auto-migrates depending on
 * the Collection configuration.
 *
 * @param {Object} config object containing adapters
 * @param {Function} callback
 * @return {Array} instantiated collections
 * @api public
 */
 
Waterline.prototype.initialize = function(options, cb) {
  var self = this;
 
  // Ensure a config object is passed in containing adapters
  Iif (!options) throw new Error('Usage Error: function(options, callback)');
  Iif (!options.adapters) throw new Error('Options object must contain an adapters object');
  Iif (!options.connections) throw new Error('Options object must contain a connections object');
 
  // Allow collections to be passed in to the initialize method
  Iif (options.collections) {
    for (var collection in options.collections) {
      this.loadCollection(options.collections[collection]);
    }
 
    // Remove collections from the options after they have been loaded
    delete options.collections;
  }
 
  // Cache a reference to instantiated collections
  this.collections = {};
 
  // Build up all the connections used by the collections
  this.connections = new Connections(options.adapters, options.connections);
 
  // Grab config defaults or set them to empty
  var defaults = _.merge({}, COLLECTION_DEFAULTS, options.defaults);
 
  // Build a schema map
  this.schema = new Schema(this._collections, this.connections, defaults);
 
  // Load a Collection into memory
  function loadCollection(item, next) {
    var loader = new CollectionLoader(item, self.connections, defaults);
    var collection = loader.initialize(self);
 
    // Store the instantiated collection so it can be used
    // internally to create other records
    self.collections[collection.identity.toLowerCase()] = collection;
 
    next();
  }
 
  async.auto({
 
    // Load all the collections into memory
    loadCollections: function(next) {
      async.each(self._collections, loadCollection, function(err) {
        Iif (err) return next(err);
 
        // Migrate Junction Tables
        var junctionTables = [];
 
        Object.keys(self.schema).forEach(function(table) {
          if (!self.schema[table].junctionTable) return;
          junctionTables.push(Waterline.Collection.extend(self.schema[table]));
        });
 
        async.each(junctionTables, loadCollection, function(err) {
          Iif (err) return next(err);
          next(null, self.collections);
        });
      });
    },
 
    // Build up Collection Schemas
    buildCollectionSchemas: ['loadCollections', function(next, results) {
      var collections = self.collections;
      var schemas = {};
 
      Object.keys(collections).forEach(function(key) {
        var collection = collections[key];
 
        // Remove hasMany association keys
        var schema = _.clone(collection._schema.schema);
 
        Object.keys(schema).forEach(function(key) {
          if (hasOwnProperty(schema[key], 'type')) return;
          delete schema[key];
        });
 
        // Grab JunctionTable flag
        var meta = collection.meta || {};
        meta.junctionTable = hasOwnProperty(collection.waterline.schema[collection.identity], 'junctionTable') ?
          collection.waterline.schema[collection.identity].junctionTable : false;
 
        schemas[collection.identity] = collection;
        schemas[collection.identity].definition = schema;
        schemas[collection.identity].attributes = collection._attributes;
        schemas[collection.identity].meta = meta;
      });
 
      next(null, schemas);
    }],
 
    // Register the Connections with an adapter
    registerConnections: ['buildCollectionSchemas', function(next, results) {
      async.each(Object.keys(self.connections), function(item, nextItem) {
        var connection = self.connections[item];
        var config = {};
        var usedSchemas = {};
 
        // Check if the connection's adapter has a register connection method
        if (!hasOwnProperty(connection._adapter, 'registerConnection')) return nextItem();
 
        // Copy all values over to a tempory object minus the adapter definition
        Object.keys(connection.config).forEach(function(key) {
          config[key] = connection.config[key];
        });
 
        // Set an identity on the connection
        config.identity = item;
 
        // Grab the schemas used on this connection
        connection._collections.forEach(function(coll) {
          var identity = coll;
          Eif (hasOwnProperty(self.collections[coll].__proto__, 'tableName')) {
            identity = self.collections[coll].__proto__.tableName;
          }
 
          var schema = results.buildCollectionSchemas[coll];
          usedSchemas[identity] = schema;
        });
 
        // Call the registerConnection method
        connection._adapter.registerConnection(config, usedSchemas, function(err) {
          Iif (err) return nextItem(err);
          nextItem();
        });
      }, next);
    }]
 
  }, function(err) {
    Iif (err) return cb(err);
    self.bootstrap(function(err) {
      Iif (err) return cb(err);
      cb(null, { collections: self.collections, connections: self.connections });
    });
  });
 
};
 
/**
 * Teardown
 *
 * Calls the teardown method on each connection if available.
 */
 
Waterline.prototype.teardown = function teardown(cb) {
  var self = this;
 
  async.each(Object.keys(this.connections), function(item, next) {
    var connection = self.connections[item];
 
    // Check if the adapter has a teardown method implemented
    Iif (!hasOwnProperty(connection._adapter, 'teardown')) return next();
 
    connection._adapter.teardown(item, next);
  }, cb);
};
 
/**
 * Bootstrap
 *
 * Auto-migrate all collections
 */
 
Waterline.prototype.bootstrap = function bootstrap(cb) {
  var self = this;
 
  //
  // TODO:
  // Come back to this -- see https://github.com/balderdashy/waterline/issues/259
  // (the stuff in this file works fine-- the work would be structural changes elsewhere)
  //
 
  // // Use the shema to get a list of junction tables idents
  // // and then determine which are "logical" collections
  // // (i.e. everything EXCEPT junction tables)
  // var junctionTableIdents = _(this.schema).filter({junctionTable: true}).pluck('identity').value();
  // var logicalCollections = _(this.collections).omit(junctionTableIdents).value();
 
  // // Flatten logical collections obj into an array for convenience
  // var toBeSynced = _.reduce(logicalCollections, function(logicals,coll,ident) {
  //     logicals.push(coll);
  //     return logicals;
  //   }, []);
 
  // // console.log(junctionTableIdents);
  // // console.log(Object.keys(logicalCollections));
  // // console.log('\n',
  // //   'Migrating collections ::',
  // //   _(toBeSynced).pluck('identity').value()
  // // );
 
  // For now:
  var toBeSynced = _.reduce(this.collections, function(resources, collection, ident) {
    resources.push(collection);
    return resources;
  }, []);
 
  // Run auto-migration strategies on each collection
  // async.each(toBeSynced, function(collection, next) {
  async.eachSeries(toBeSynced, function(collection, next) {
  // async.eachLimit(toBeSynced, 9, function(collection, next) {
    collection.sync(next);
  }, cb);
};