src/Store/Model/Relation/HasMany.ts   A
last analyzed

Complexity

Total Complexity 12
Complexity/F 3

Size

Lines of Code 73
Function Count 4

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 52
dl 0
loc 73
rs 10
c 0
b 0
f 0
wmc 12
mnd 8
bc 8
fnc 4
bpm 2
cpm 3
noi 0

4 Functions

Rating   Name   Duplication   Size   Complexity  
B HasMany.getRelationalFields 0 3 6
A HasMany.setName 0 8 1
A HasMany.getValueByParentKey 0 5 4
A HasMany.setParentProperties 0 22 1
1
import Relation from "../Relation";
2
import {ModelStaticInterface} from "../../../JeloquentInterfaces";
3
import Collection from "../../Collection";
4
import ForeignKey from "../Field/ForeignKey";
5
6
/**
7
 *
8
 */
9
export default class HasMany extends Relation {
10
11
    localKey: string;
12
13
    constructor(model: ModelStaticInterface, foreignKey: string = null, localKey: string = null) {
14
        super(model, foreignKey);
15
        this.localKey = localKey ?? 'id';
16
    }
17
18
    get count(): number {
19
        const indexes = globalThis.Store.database().indexes(this.model.className);
20
        return indexes.get(this.foreignKey).get(this.$parent.primaryKey)?.size ?? 0;
21
    }
22
23
    get originalValue(): unknown {
24
        return this.getValueByParentKey('originalPrimaryKey');
25
    }
26
27
    get value(): unknown {
28
        return this.getValueByParentKey('primaryKey');
29
    }
30
31
    getRelationalFields():Array<ForeignKey> {
32
        return [];
33
    }
34
35
    setName(): HasMany {
36
        const parentClassName = this.$parent.snakeCaseClassName;
37
        const modelClassName = this.model.snakeCaseClassName;
38
39
        this.foreignKey = `${parentClassName}_id`;
40
        this.$name = `${modelClassName}s`; //todo fix plural notation
41
        return this;
42
    }
43
44
    protected getValueByParentKey(parentProperty): Collection {
45
        const keyIndex = this.model.getIndexByKey(this.foreignKey);
46
        return globalThis.Store.database().find(this.model.className,
47
            [...keyIndex.get(`${this.$parent[parentProperty]}`)?.values() ?? []]
48
        );
49
    }
50
51
    protected setParentProperties(): HasMany {
52
        super.setParentProperties();
53
54
        // todo remove and move to proxy
55
        Object.defineProperty(this.$parent,
56
            `${this.name}Count`, {
57
                get: () => {
58
                    return this.count;
59
                },
60
            }
61
        );
62
63
        // todo remove and move to proxy
64
        Object.defineProperty(this.$parent,
65
            `has${this.model.className}s`, {
66
                get: () => {
67
                    return this.count > 0;
68
                },
69
            }
70
        );
71
        return this;
72
    }
73
}