-
Notifications
You must be signed in to change notification settings - Fork 4
/
couch-ar.js
250 lines (212 loc) · 7.08 KB
/
couch-ar.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
var cradle = require('cradle');
var fs = require('fs');
var Base = require('./Base');
var helpers = require('./helpers');
var databases = {}
var defaultDbName;
var defaultTimeout = 30;
/**
* initialize the DB and create constructor factories
* @param config
* @param callback
*/
exports.init = function(config, callback) {
var db;
var timer;
var timeout = typeof config['timeout'] != undefined ? config.timeout : defaultTimeout;
defaultDbName = config.dbName;
callback = callback || function() {
};
config.connectionOptions = config.connectionOptions || {};
if (config.host && config.port) {
db = new(cradle.Connection)(config.host, config.port, config.connectionOptions).database(config.dbName);
} else {
db = new cradle.Connection().database(config.dbName);
}
databases[config.dbName] = db;
db.exists(function(err, result) {
if (result === false) {
db.create(function() {
initDomainConstructors();
});
} else {
db.viewCleanup(function() {
db.compact(function() {
initDomainConstructors();
});
});
}
});
function initDomainConstructors() {
db.domainsToLoad = 0;
db.checkDomainsLoaded = function() {
if(this.domainsToLoad == 0) {
if (timer) {
clearTimeout(timer);
}
callback(/* null, */ db);
}
}
var filenames = fs.readdirSync(config.root);
filenames.forEach(function(filename) {
/\.js$/.test(filename) && require(config.root + '/' + filename) && db.domainsToLoad ++;
});
if (timeout) {
timer = setTimeout(function(){
console.log('Timed out initializing domains.');
callback(/* err, */ db);
}, timeout * 1000);
}
}
}
/**
* Create a domain constructor. Use this in each domain file
*/
exports.create = function(name, config, constr) {
config.dbName = config.dbName || defaultDbName;
var db = databases[config.dbName];
console.log('Adding to domain: ' + name);
config.properties.dateCreated = {};
config.properties.lastUpdated = {};
var factory = function() {
var c = Base(db, name, config);
constr && constr.call(c,c);
c.properties = config.properties;
return c;
}
// Run all of the creators
addCreateMethod();
addViews(function() {
addFinders();
db.domainsToLoad--;
db.checkDomainsLoaded();
});
factory.addView = function() {
addView.apply(factory, arguments);
}
factory.viewNames = [];
exports[config.dbName] = exports[config.dbName] || {};
return exports[name] = exports[config.dbName][name] = factory;
function addFinders() {
for (var prop in config.properties) {
if(config.properties[prop].finders !== false) {
addFinders(prop);
}
}
for (view in config.views) {
addFinders(view);
}
addFinders('id');
addList();
function addFinders(finderName) {
var upperName = helpers.toUpper(finderName);
factory['findAllBy' + upperName] = function(value, callback) {
executeView(finderName, value, callback);
}
factory['findBy' + upperName] = function(value, callback) {
factory['findAllBy' + upperName](value, function(results) {
callback(results[0]);
});
}
factory.viewNames.push(finderName);
}
function addList() {
factory.list = function(callback) {
var url = [name,'id'].join('/');
db.view(url, function(err, res) {
callback(instantiateResults(res));
})
}
}
}
function executeView(viewName, value, callback) {
var options = {};
if (Array.isArray(value)) {
options.startkey = value[0];
options.endkey = value[1];
} else if (typeof(value) == 'object') {
options = value;
} else {
options.key = value;
}
var url = [name, viewName].join('/');
db.view(url, options, function(err, res) {
err && console.log(err);
callback(err ? [] : instantiateResults(res));
});
}
function instantiateResults(res) {
return res.map(function(row) {
row.id = row._id;
row.rev = row._rev;
return factory.create(row);
})
}
function addView(viewName, viewDef, callback) {
db.get('_design/' + name, function(err, res) {
res.views[viewName] = wrapView(name, viewDef);
saveView(res.views, callback);
});
function saveView(views, callback) {
db.save('_design/' + name, views, function(err, res) {
factory['findAllBy' + helpers.toUpper(viewName)] = function(value, callback) {
executeView(viewName, value, callback);
}
factory['findBy' + helpers.toUpper(viewName)] = function(value, callback) {
executeView(viewName, value, function(objects) {
callback(objects[0]);
});
}
callback();
});
}
factory.viewNames.push(viewName);
}
function wrapView(type, view) {
if (view.map) {
view.map = view.map.toString();
var code = "$1if (doc.type==='" + type + "'){$2}}"
view.map = view.map.replace(/[\n]/g, '');
view.map = view.map.replace(/(function.*?\(.*?\).*?{)(.*)}.*$/, code);
}
return view;
}
function addViews(callback) {
var views = {};
if (config.views) {
Object.keys(config.views).forEach(function(viewName) {
var view = config.views[viewName];
wrapView(name, view);
views[viewName] = view;
});
}
for (prop in config.properties) {
if(config.properties[prop].finders !== false) {
views[prop] = {
map: "function(doc){if(doc.type === '" + name + "') {emit(doc." + prop + ", doc)}}"
}
}
}
views.id = {
map: "function(doc){if(doc.type === '" + name + "') {emit(doc._id, doc)}}"
}
db.save('_design/' + name, views, function(err, res) {
callback && callback();
});
}
/**
* Add the create() static method to the factory
*/
function addCreateMethod() {
factory.create = function(props) {
var obj = factory();
for (var n in props) {
obj[n] = props[n];
}
// copy ids as well
obj.id = obj.id || props._id || props.id
obj.rev = obj.rev || props._rev || props.rev;
return obj;
}
}
}