-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
233 lines (189 loc) · 5.1 KB
/
index.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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
import {DBConfig} from "./types.d.ts";
import {Schema} from "./schema/index.ts";
import {QueryBuilder} from "./QueryBuilder.ts";
import {Connector} from "./Connector.ts";
import {TableCreator} from "./schema/TableCreator.ts";
export interface IEntity {
created_at: string | number,
updated_at: string | number,
}
export const database = async (config: DBConfig) => {
if (!config.poolSize) {
config.poolSize = 5;
}
await Connector.connect(config);
const schema = Schema(Connector.instance.client);
return {
connect: async () => {
await Connector.instance.connect(config);
},
schema,
async execute(sql: string) {
return await Connector.instance.client.execute(sql);
},
};
};
export class Model<T> {
public table: string;
public timestamps = true;
private _conn: any;
private queryBuilder: QueryBuilder<T>;
constructor(tableName: string = '') {
this.table = tableName;
this._conn = Connector.instance;
this._conn.checkConnection();
this.queryBuilder = new QueryBuilder<T>(this.table, database);
}
where(
fieldOrFields: any,
operatorOrFieldValue?: any,
fieldValue?: any,
) {
const whereOperator = typeof fieldValue !== "undefined"
? operatorOrFieldValue
: "=";
const whereValue = typeof fieldValue !== "undefined"
? fieldValue
: operatorOrFieldValue;
if (typeof fieldOrFields === "string") {
this.queryBuilder.where(fieldOrFields, whereOperator, whereValue);
} else {
Object.entries(fieldOrFields).forEach(([field, value]) => {
// @ts-ignore
this.queryBuilder.where(field, "=", value);
});
}
return this;
}
async update(
fieldOrFields: T,
fieldValue?: any,
) {
let fieldsToUpdate = {};
if (this.timestamps) {
// @ts-ignore
if (fieldOrFields.created_at) {
// @ts-ignore
fieldOrFields.created_at = new Date(fieldOrFields.created_at).toISOString().slice(0, 19).replace('T', ' ');
}
// @ts-ignore
fieldOrFields.updated_at = new Date().toISOString().slice(0, 19).replace('T', ' ');
}
if (typeof fieldOrFields === "string") {
// @ts-ignore
fieldsToUpdate[fieldOrFields] = fieldValue!;
} else {
fieldsToUpdate = {
...fieldsToUpdate,
...fieldOrFields,
};
}
const wheres = this.queryBuilder.wheres;
await this.runQuery(
this.queryBuilder.update(fieldsToUpdate as T),
);
this.queryBuilder.wheres = wheres;
const result = await this.runQuery(
this.queryBuilder,
);
if (result.rows.length > 1) {
return result.rows;
}
return result.rows[0];
}
async count() {
let result;
try {
result = await this.runQuery(
this.queryBuilder.count(),
);
} catch (err) {
console.log(err);
throw err;
}
this.queryBuilder.reset()
return result.rows[0].count;
}
async updateById(id: string | number, fields: any) {
this.where("id", id);
return await this.update(fields);
}
async find(id: string | number) {
const result = await this.runQuery(
this.queryBuilder.where("id", "=", id as string).single(),
);
return result.rows[0];
}
async create(
fields: T,
) {
const created = await this.runQuery(
this.queryBuilder.insert(fields)
);
created.item = await this.find(created.lastInsertId);
return created.item;
}
async delete() {
const result = await this.runQuery(
this.queryBuilder.delete(),
);
return result.affectedRows > 0;
}
async deleteById(id: string | number) {
this.where('id', id as string);
const result = await this.runQuery(
this.queryBuilder.delete(),
);
return result.affectedRows > 0;
}
async first() {
this.queryBuilder.single();
const result = await this.runQuery(
this.queryBuilder,
);
return result.rows[0];
}
select(selects: Array<string> | string) {
if (typeof selects == "string") {
this.queryBuilder.select([selects]);
}
if (typeof selects == "object") {
this.queryBuilder.select(selects);
}
return this;
}
async get() {
const result = await this.runQuery(
this.queryBuilder,
);
return result.rows;
}
async sql(sql: string) {
return await this._conn.client.execute(this.queryBuilder.sql(sql));
}
private async runQuery(query: QueryBuilder<T>) {
const result = await this._conn.client.execute(query.query());
result.rows = result.rows as Array<T>;
this.queryBuilder = new QueryBuilder<T>(this.table, this._conn);
return result;
}
public async truncate(): Promise<any> {
const result = await this.sql("TRUNCATE " + this.table);
console.log(result);
return result;
}
get database(): any {
return this._conn;
}
get tableName(): string {
return this.table;
}
public definition(table: TableCreator) {
// will be override
}
public async migrate() {
const tableCreator = new TableCreator(this.table);
this.definition(tableCreator);
await tableCreator.run();
}
}