-
Notifications
You must be signed in to change notification settings - Fork 5
/
index.js
98 lines (94 loc) · 2.71 KB
/
index.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
var Hash = require('hashish');
var Seq = require('seq');
module.exports = {
patterns: {},
define: function(key, model, def) {
var _model, _def;
if (typeof(model) == 'string') {
// If 'model' is a string, interpret it as the name of a model that has
// already been defined. Try to inherit from that model.
if (!(model in this.patterns)) {
throw('No parent model with the key "'+model+'" has been defined.');
} else {
_model = this.patterns[model].class;
_def = Hash.merge(this.patterns[model].attributes, def);
}
} else {
_model = model;
_def = def;
}
this.patterns[key] = {
class: _model,
attributes: _def
};
},
build: function(model, data, callback) {
if (typeof(data) == 'function'){
callback = data;
data = {}
}
if (data === undefined) {
data = {}
}
var attributes = this.patterns[model].attributes
var values = Hash.merge(attributes, data);
// no callback given so use direct style
if (callback === undefined){
values = Hash.map(values, function(value, key){
if (typeof(value) == 'function'){
if (value.length > 0){
throw new Error('You need to pass a callback to the build function - setter for attribute "' + key + '" is asynchronous.');
} else {
return value.call();
}
} else {
return value;
}
});
var obj = new(this.patterns[model].class)(values);
return obj;
} else {
// callback given, convert everything to function style
var callbacks = []
Hash.forEach(values, function(value, key){
if (typeof(value) == 'function'){
if (value.length == 0){
callbacks.push({key: key, cbk: function(cbk){
return cbk(null, value.call());
}});
} else {
callbacks.push({key: key, cbk: value});
}
} else {
callbacks.push({key: key, cbk: function(cbk){
return cbk(null, value);
}});
}
});
Seq(callbacks)
.parEach(function(value){
value.cbk(this.into(value.key));
})
.seq(function(){
var obj = new(module.exports.patterns[model].class)(this.vars);
callback(null, obj);
})
.catch(function(err){
callback(err);
});
}
},
create: function(model, data, callback) {
if (typeof(data) == 'function') {
callback = data;
data = {};
}
this.build(model, data, function(err, builtObj){
if (err)
throw(err);
builtObj.save(function(error, createdObj) {
callback(error, createdObj);
})
});
}
}