-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathModel.js
95 lines (79 loc) · 2.61 KB
/
Model.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
/**
* @author OA Wu <oawu.tw@gmail.com>
* @copyright Copyright (c) 2015 - 2025, @oawu/orm
* @license http://opensource.org/licenses/MIT MIT License
* @link https://www.ioa.tw/
*/
const { promisify, Type: T } = require('@oawu/helper')
const Builder = require('./Libs/Builder.js')
const Table = require('./Libs/Table.js')
const _Model = require('./Libs/Model.js')
const _extend = model => {
for (let key in _Model.prototype) {
model.prototype[key] = _Model.prototype[key]
}
Object.defineProperty(model.prototype, 'dump', {
get() {
const tmp = {}
for (let key of this.$.attrs.keys()) {
tmp[key] = this.$.attrs.get(key)
}
return tmp
}
})
model.one = (...params) => Builder(model).findOne(...params)
model.all = (...params) => Builder(model).findAll(...params)
model.count = (...params) => Builder(model).count(...params)
model.truncate = (...params) => Builder(model).truncate(...params)
model.update = (...params) => Builder(model).update(...params)
model.delete = (...params) => Builder(model).delete(...params)
model.limit = (...params) => Builder(model).limit(...params)
model.offset = (...params) => Builder(model).offset(...params)
model.group = (...params) => Builder(model).group(...params)
model.having = (...params) => Builder(model).having(...params)
model.where = (...params) => Builder(model).where(...params)
model.order = (...params) => Builder(model).order(...params)
model.select = (...params) => Builder(model).select(...params)
model.join = (model, primary, foreign, type = 'INNER') => Builder(model).join(model, primary, foreign)
model.create = (attr = {}, allowKeys = [], closure = null) => {
if (T.func(attr) || T.asyncFunc(attr)) {
closure = attr
attr = {}
allowKeys = []
}
if (T.func(allowKeys) || T.asyncFunc(allowKeys)) {
closure = allowKeys
allowKeys = []
}
const newAttr = {}
for (let key in attr) {
if (!allowKeys.lenght || allowKeys.includes(key)) {
newAttr[key] = attr[key]
}
}
return promisify(closure, async _ => {
const table = await Table.instance(model)
return await _Model(table, newAttr, true).save()
})
}
return model
}
const _instances = new Map()
const Model = (model = null) => {
if (model === null) {
return Model
}
if (T.str(model)) {
return Model[model]
}
if (_instances.has(model)) {
model = _instances.get(model)
Model[model.name] = model
return model
}
model = _extend(model)
Model[model.name] = model
_instances.set(model, model)
return model
}
module.exports = Model