-
Notifications
You must be signed in to change notification settings - Fork 39
/
Resource.ts
294 lines (255 loc) · 8.43 KB
/
Resource.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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
import "reflect-metadata";
import { Property } from "./Property";
import { BaseEntity, In, Like } from "typeorm";
import { BaseResource, ValidationError, Filter, PropertyType } from "admin-bro";
import { ParamsType } from "admin-bro/types/src/backend/adapters/base-record";
import { convertFilter } from "./utils/convertFilter";
import { ExtendedRecord } from "./ExtendedRecord";
import { getTitle } from "./utils/getTitle";
import { SEARCH_FIELD_SYMBOL } from "./symbols/SEARCH_FIELD_SYMBOL";
export class Resource extends BaseResource
{
public static validate: any;
public model: typeof BaseEntity;
private propsObject: Record<string, Property> = {};
constructor(model: typeof BaseEntity)
{
super(model);
this.model = model;
this.prepareProps();
}
public databaseName(): string
{
return this.model.getRepository().metadata.connection.options.database as string || "typeorm";
}
public databaseType(): string
{
return this.model.getRepository().metadata.connection.options.type || "typeorm";
}
public name(): string
{
return this.model.getRepository().metadata.tableName;
}
public id()
{
return this.model.name;
}
public properties()
{
return Object.values(this.propsObject);
}
public property(path: string): Property | null
{
return this.propsObject[path] || null;
}
public async count(filter)
{
return this.model.count(({
where: convertFilter(filter),
}));
}
public async populate(baseRecords, property: Property)
{
const fks: Array<any> = baseRecords.map(baseRecord => baseRecord.params[property.name()]);
const instances = await this.model.findByIds(fks);
const instancesRecord: Record<string, BaseEntity> = {};
for (const instance of instances)
{
if(instance.hasId())
instancesRecord[(instance as any).id] = instance;
}
for (const baseRecord of baseRecords)
{
const fk = baseRecord.params[property.name()];
const instance = instancesRecord[fk];
if(instance)
{
const record = new ExtendedRecord(instance, this);
record.setTitle(await getTitle(instance));
baseRecord.populated[property.name()] = record;
}
}
return baseRecords;
}
public async find(filter: Filter, {limit = 10, offset = 0, sort = {}}): Promise<Array<ExtendedRecord>>
{
const {direction, sortBy} = sort as any;
const instances = await this.model.find({
where: convertFilter(filter),
take: limit,
skip: offset,
order: {
[sortBy]: (direction || "asc").toUpperCase()
}
});
const records: Array<ExtendedRecord> = [];
for (const instance of instances)
{
const record = new ExtendedRecord(instance, this);
record.setTitle(await getTitle(instance));
records.push(record);
}
return records;
}
public async findMany(ids: Array<string>): Promise<Array<ExtendedRecord>>
{
const instances = await this.model.find({ where: { id: In(ids) } });
const records: Array<ExtendedRecord> = [];
for (const instance of instances)
{
const record = new ExtendedRecord(instance, this);
record.setTitle(await getTitle(instance));
records.push(record);
}
return records;
}
public async search(value: any, limit: number = 50): Promise<Array<ExtendedRecord>>
{
const meta = Reflect.getMetadata(SEARCH_FIELD_SYMBOL, this.model);
let kt: {key: string, type: PropertyType} | null = null;
if(meta)
{
const key = `${meta}`;
const prop = this.property(key);
if(prop != null)
kt = {key, type: prop.type()};
}
else
{
const nameProp = this.property("name");
const idProp = this.property("id");
if(nameProp)
kt = {key: "name", type: nameProp.type()};
else if(idProp)
kt = {key: "id", type: idProp.type()};
}
if(kt != null)
{
const instances = await this.model.find({
where: {[kt.key]: kt.type == "string" ? Like(`%${value}%`) : value},
take: limit
});
const records: Array<ExtendedRecord> = [];
for (const instance of instances)
{
const record = new ExtendedRecord(instance, this);
record.setTitle(await getTitle(instance));
records.push(record);
}
return records;
}
throw new Error("Search field not found.");
}
public async findOne(id)
{
const instance = await this.model.findOne(id);
const record = new ExtendedRecord(instance, this);
record.setTitle(await getTitle(instance));
return record;
}
public async findById(id)
{
return await this.model.findOne(id);
}
public async create(params: any): Promise<ParamsType>
{
const instance = await this.model.create(this.prepareParamsBeforeSave(params));
await this.validateAndSave(instance);
return instance;
}
public async update(pk, params: any = {}): Promise<ParamsType>
{
params = this.prepareParamsBeforeSave(params);
const instance = await this.model.findOne(pk);
if(instance)
{
for(const p in params)
instance[p] = params[p];
await this.validate(instance);
await instance.save();
return instance;
}
throw new Error("Instance not found.");
}
public async delete(pk)
{
await this.model.delete(pk);
}
private prepareProps()
{
const columns = this.model.getRepository().metadata.columns;
for (let i = 0; i < columns.length; i++)
{
const property = new Property(columns[i], this, i);
this.propsObject[property.path()] = property;
}
}
private prepareParamsBeforeSave(params: Object): Object
{
for (const p in params)
{
const property = this.property(p);
if(property)
{
if(["mixed", "boolean"].includes(property.type()))
params[p] = !params[p] ? null : JSON.parse(params[p]);
else if(["number", "float"].includes(property.type()))
params[p] = !params[p] ? null : Number(params[p]);
else if(["date", "datetime"].includes(property.type()))
params[p] = !params[p] ? null : new Date(params[p]);
else if(property.type() == "reference")
params[property.column.propertyName] = !params[p] ? null : +params[p];
}
}
return params;
}
private async validate(instance: BaseEntity)
{
if(Resource.validate)
{
const errors = await Resource.validate(instance);
if(errors && errors.length)
{
const validationErrors = errors.reduce((memo, error) => ({
...memo,
[error.property]: {
type: Object.keys(error.constraints)[0],
message: Object.values(error.constraints)[0],
}
}), {});
throw new ValidationError(`${this.name()} validation failed`, validationErrors);
}
}
}
private async validateAndSave(instance: BaseEntity)
{
await this.validate(instance);
try
{
await instance.save();
}
catch(error)
{
if(error.name === "QueryFailedError")
{
throw new ValidationError(`${this.name()} validation failed`, {
[error.column]: {
type: "schema error",
message: error.message
}
});
}
}
}
public static isAdapterFor(rawResource: any)
{
try
{
return !!rawResource.getRepository().metadata;
}
catch(e)
{
return false;
}
}
}