-
Notifications
You must be signed in to change notification settings - Fork 0
/
class-model-generator.js
79 lines (73 loc) · 1.8 KB
/
class-model-generator.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
module.exports = ClassModelGenerator;
var Query = require("./query/query");
var executables = require("./query/exec").methods();
function ClassModelGenerator (schema)
{
// Not to be used with "new"
var self = this;
self.model = model;
function model (args)
{
self.model.process(args);
return self.model;
}
model.process = process;
model.schema = schema;
model.name = schema.name;
model.table = schema.table;
model.query = new Query(model);
addGettersToModel(model);
}
function process (args)
{
this.query.add(args);
return this;
}
function addGettersToModel (model)
{
[
"find", "create", "update", "delete",
"by", "where", "all", "not", "desc",
"select", "limit", "order",
"first", "last",
"sql"
].forEach(function (method) {
// User.find.`by`
Object.defineProperty(model, method, {
set: function () {},
get: function ()
{
model(method);
return model;
}
});
});
// User.find.by.`email("[email protected]")`
for (var i = 0; i < model.schema.columns.length; i++) {
var method = model.schema.columns[i].name;
model[method] = methodable(method);
}
function methodable (method)
{
return function (args)
{
model(method);
if (args) {
model(args);
}
return model;
};
}
// User.find.where.name("Joe").desc.`rows(function (){})`
for (i = 0; i < executables.length; i++) {
var exec = executables[i];
model[exec] = executable(exec);
}
function executable (exec)
{
return function (cb)
{
return model.query[exec](cb);
};
}
}