-
Notifications
You must be signed in to change notification settings - Fork 0
/
MapperBase.ts
68 lines (67 loc) · 1.72 KB
/
MapperBase.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
import { myNosql } from "../database";
import { Data } from "../database/index";
import { ModelBase } from "./ModelBase";
export class MapperBase {
tableName: string;
getModelWidthMap(data: any): any[] {
const result: any = {};
for (let key in this) {
if (key === "tableName") continue;
result[key] = data[key];
}
return result;
}
getTableName() {
return this.tableName;
}
getById(id: number): any {
return this.getModelWidthMap(
(
myNosql.data[
this.getTableName() as keyof Data
] as unknown as Array<ModelBase>
).find((row) => row.id == id)
);
}
getList(): any[] {
return (
myNosql.data[
this.getTableName() as keyof Data
] as unknown as Array<ModelBase>
).map((row) => {
return this.getModelWidthMap(row);
});
}
setByModelId(data: ModelBase): boolean {
const table = myNosql.data[
this.getTableName() as keyof Data
] as unknown as Array<any>;
const rowIndex = table.findIndex((row) => row.id == data.id);
if (rowIndex !== -1) {
table[rowIndex] = this.getModelWidthMap(data);
} else {
data.id = this._getNextId(table);
table.push(this.getModelWidthMap(data));
}
return true;
}
delById(id: number): boolean {
const table = myNosql.data[
this.getTableName() as keyof Data
] as unknown as Array<any>;
const rowIndex = table.findIndex((row) => row.id == id);
if (rowIndex !== -1) {
table.splice(rowIndex, 1);
return true;
} else {
return false;
}
}
_getNextId(table: Array<ModelBase>): number {
let max = 0;
for (let row of table) {
max = max > row.id ? max : row.id;
}
return max + 1;
}
}