1
|
|
|
import Relation from "../Relation"; |
2
|
|
|
import ForeignKey from "../Field/ForeignKey"; |
3
|
|
|
import HasManyThrough from "../Relation/HasManyThrough"; |
4
|
|
|
import Field from "../Field"; |
5
|
|
|
import {ModelInterface} from "../../../JeloquentInterfaces"; |
6
|
|
|
|
7
|
|
|
export function addRelationFieldsToList(fields) { |
8
|
|
|
const fieldList = [...fields]; |
9
|
|
|
fields.forEach((field, i) => { |
10
|
|
|
if (field instanceof Relation) { |
11
|
|
|
fieldList.splice(i, 0, ...field.getRelationalFields()); |
12
|
|
|
} |
13
|
|
|
}); |
14
|
|
|
return fieldList; |
15
|
|
|
} |
16
|
|
|
|
17
|
|
|
export function setFields(model, fields: Field[]) { |
18
|
|
|
fields.forEach((field) => { |
19
|
|
|
field.setup(modelProxy(model)); |
20
|
|
|
model._originalFields.set(field.name, field); |
21
|
|
|
}); |
22
|
|
|
model.numberOfFields = model.originalFields.length; |
23
|
|
|
} |
24
|
|
|
|
25
|
|
|
export function setupTable(model, table) { |
26
|
|
|
model.originalFields.forEach((field) => { |
27
|
|
|
if (field instanceof ForeignKey) { |
28
|
|
|
field.tableSetup(table); |
29
|
|
|
} |
30
|
|
|
|
31
|
|
|
if (field instanceof HasManyThrough) { |
32
|
|
|
field.tableSetup(); |
33
|
|
|
} |
34
|
|
|
}); |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
export function modelProxy(model) { |
38
|
|
|
return new Proxy(model, { |
39
|
|
|
construct(target, argArray, newTarget): object { |
40
|
|
|
return Reflect.construct(target, argArray, newTarget); |
41
|
|
|
}, |
42
|
|
|
|
43
|
|
|
get(target: ModelInterface, p: string | symbol): unknown { |
44
|
|
|
if (Reflect.has(target, p)) { |
45
|
|
|
return Reflect.get(target, p); |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
if (typeof p !== 'string') { |
49
|
|
|
return null; |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
if (target._originalFields.has(p)) { |
53
|
|
|
return target._originalFields.get(p).value; |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
if (p.startsWith('original_') && !Reflect.has(target, p.replace('original_', '')) && target._originalFields.has(p.replace('original_', ''))) { |
57
|
|
|
return target._originalFields.get(p.replace('original_', '')).originalValue; |
58
|
|
|
} |
59
|
|
|
return null; |
60
|
|
|
}, |
61
|
|
|
|
62
|
|
|
set(target: ModelInterface, p: string | symbol, value: unknown): boolean { |
63
|
|
|
if (Reflect.has(target, p)) { |
64
|
|
|
return Reflect.set(target, p, value); |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
if (typeof p !== 'string') { |
68
|
|
|
return false; |
69
|
|
|
} |
70
|
|
|
|
71
|
|
|
if (target._originalFields.has(p)) { |
72
|
|
|
target._originalFields.get(p).value = value; |
73
|
|
|
return true; |
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
if (p.startsWith('_') && target._originalFields.has(p.replace('_', ''))) { |
77
|
|
|
const myField = target._originalFields.get(p.replace('_', '')); |
78
|
|
|
myField._value = value; |
79
|
|
|
return true; |
80
|
|
|
} |
81
|
|
|
|
82
|
|
|
return true; |
83
|
|
|
} |
84
|
|
|
}); |
85
|
|
|
} |
86
|
|
|
|