-
Notifications
You must be signed in to change notification settings - Fork 10
/
model.ts
109 lines (83 loc) · 2.57 KB
/
model.ts
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
99
100
101
102
103
104
105
106
107
108
109
import { QueryBuilder } from './drivers/default/builders/queryBuilder';
import { ModelConstructor } from './contracts/modelConstructor';
import { AxiosResponse } from 'axios';
import { DefaultPersistedAttributes } from './types/defaultPersistedAttributes';
export abstract class Model<
Attributes = Record<string, unknown>,
PersistedAttributes = Record<string, unknown> | DefaultPersistedAttributes,
Relations = Record<string, unknown>,
Key extends number | string = number | string,
AllAttributes = Attributes & PersistedAttributes
> {
public $attributes!: AllAttributes;
public $relations!: Relations;
public $response?: AxiosResponse;
protected $keyName: string = 'id';
constructor(attributes?: AllAttributes, relations?: Relations) {
this.$init();
if (attributes) {
this.$setAttributes(attributes);
}
if (relations) {
this.$setRelations(this.$relations);
}
}
public abstract $resource(): string;
public static $query<M extends Model>(this: ModelConstructor<M>): QueryBuilder<M> {
return new QueryBuilder<M>(this);
}
public $query<M extends Model>(): QueryBuilder<M> {
return new QueryBuilder<M>(this.constructor as ModelConstructor<M>);
}
public async $save<M extends Model>(attributes?: Attributes): Promise<this> {
if (attributes) {
this.$setAttributes((attributes as unknown) as AllAttributes);
}
await this.$query().update(
this.$getKey(),
(attributes || this.$attributes) as Record<string, unknown>
);
return this;
}
public async $destroy<M extends Model>(force: boolean = false): Promise<this> {
await this.$query().destroy(this.$getKey(), force);
return this;
}
public $getKeyName(): string {
return this.$keyName;
}
public $setKeyName(keyName: string): this {
this.$keyName = keyName;
return this;
}
public $getKey(): Key {
return this.$attributes[this.$getKeyName()];
}
public $setKey(key: Key): this {
this.$attributes[this.$getKeyName()] = key;
return this;
}
public $setAttributes(attributes: AllAttributes): this {
for (const attribute in attributes) {
this.$attributes[attribute] = attributes[attribute];
}
return this;
}
public $setRelations(relations: Relations): this {
for (const relation in relations) {
this.$relations[relation] = relations[relation];
}
return this;
}
public $is(model: Model<Attributes, PersistedAttributes, Relations>): boolean {
return this.$getKey() === model.$getKey();
}
protected $init(): void {
if (!this.$attributes) {
this.$attributes = {} as AllAttributes;
}
if (!this.$relations) {
this.$relations = {} as Relations;
}
}
}