-
Notifications
You must be signed in to change notification settings - Fork 601
/
waterline.js
271 lines (211 loc) · 8.52 KB
/
waterline.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
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
// ██╗ ██╗ █████╗ ████████╗███████╗██████╗ ██╗ ██╗███╗ ██╗███████╗
// ██║ ██║██╔══██╗╚══██╔══╝██╔════╝██╔══██╗██║ ██║████╗ ██║██╔════╝
// ██║ █╗ ██║███████║ ██║ █████╗ ██████╔╝██║ ██║██╔██╗ ██║█████╗
// ██║███╗██║██╔══██║ ██║ ██╔══╝ ██╔══██╗██║ ██║██║╚██╗██║██╔══╝
// ╚███╔███╔╝██║ ██║ ██║ ███████╗██║ ██║███████╗██║██║ ╚████║███████╗
// ╚══╝╚══╝ ╚═╝ ╚═╝ ╚═╝ ╚══════╝╚═╝ ╚═╝╚══════╝╚═╝╚═╝ ╚═══╝╚══════╝
//
var _ = require('@sailshq/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 Waterline = module.exports = function() {
if (!(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
if (!options) {
throw new Error('Usage Error: function(options, callback)');
}
if (!options.adapters) {
throw new Error('Options object must contain an adapters object');
}
if (!options.connections) {
throw new Error('Options object must contain a connections object');
}
// Allow collections to be passed in to the initialize method
if (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) {
if (err) {
return next(err);
}
// Migrate Junction Tables
var junctionTables = [];
_.each(self.schema, function(val, table) {
if (!self.schema[table].junctionTable) {
return;
}
junctionTables.push(Waterline.Collection.extend(self.schema[table]));
});
async.each(junctionTables, loadCollection, function(err) {
if (err) {
return next(err);
}
next(null, self.collections);
});
});
},//</loadCollections>
// Build up Collection Schemas
buildCollectionSchemas: ['loadCollections', function(unused, next) {
var collections = self.collections;
var schemas = {};
_.each(collections, function(val, key) {
var collection = collections[key];
// Remove hasMany association keys
var schema = _.clone(collection._schema.schema);
_.each(schema, function(val, key) {
if (_.has(schema[key], 'type')) {
return;
}
delete schema[key];
});
// Grab JunctionTable flag
var meta = collection.meta || {};
meta.junctionTable = _.has(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);
}],//</buildCollectionSchemas>
// Register the Connections with an adapter
registerConnections: ['buildCollectionSchemas', function(results, next) {
async.each(_.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 (!_.has(connection._adapter, 'registerConnection')) {
return nextItem();
}
// Copy all values over to a tempory object minus the adapter definition
_.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;
if (_.has(Object.getPrototypeOf(self.collections[coll]), 'tableName')) {
identity = Object.getPrototypeOf(self.collections[coll]).tableName;
}
var schema = results.buildCollectionSchemas[coll];
usedSchemas[identity] = {
definition: schema.definition,
tableName: schema.tableName || identity
};
});
// Call the registerConnection method
connection._adapter.registerConnection(config, usedSchemas, function(err) {
if (err) {
return nextItem(err);
}
nextItem();
});
}, next);//</async.each>
}]//<registerConnections>
}, function asyncCb(err) {
if (err) {
return cb(err);
}
var ontology = {
collections: self.collections,
connections: self.connections
};
cb(null, ontology);
});
};
/**
* 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
if (!_.has(connection._adapter, 'teardown')) {
return next();
}
connection._adapter.teardown(item, next);
}, cb);
};