forked from Arteha/admin-bro-typeorm
-
Notifications
You must be signed in to change notification settings - Fork 35
/
Copy pathResource.ts
227 lines (191 loc) · 6.3 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
/* eslint-disable no-param-reassign */
import { BaseEntity, In } from 'typeorm'
import { BaseResource, ValidationError, Filter, BaseRecord, flat } from 'adminjs'
import { Property } from './Property'
import { convertFilter } from './utils/filter/filter.converter'
import safeParseNumber from './utils/safe-parse-number'
type ParamsType = Record<string, any>;
export class Resource extends BaseResource {
public static validate: any;
protected model: typeof BaseEntity;
protected propsObject: Record<string, Property> = {};
constructor(model: typeof BaseEntity) {
super(model)
this.model = model
this.propsObject = 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.name
}
public id(): string {
return this.model.name
}
public idName(): string {
return this.model.getRepository().metadata.primaryColumns[0].propertyName
}
public properties(): Array<Property> {
return [...Object.values(this.propsObject)]
}
public property(path: string): Property {
return this.propsObject[path]
}
public async count(filter: Filter): Promise<number> {
return this.model.count(({
where: convertFilter(filter),
}))
}
public async find(
filter: Filter,
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
params,
): Promise<Array<BaseRecord>> {
const { limit = 10, offset = 0, sort = {} } = params
const { direction, sortBy } = sort
const instances = await this.model.find({
where: convertFilter(filter),
take: limit,
skip: offset,
order: {
[sortBy]: (direction || 'asc').toUpperCase(),
},
})
return instances.map((instance) => new BaseRecord(instance, this))
}
public async findOne(id: string | number): Promise<BaseRecord | null> {
const reference: any = {}
reference[this.idName()] = id
const instance = await this.model.findOneBy(reference)
if (!instance) {
return null
}
return new BaseRecord(instance, this)
}
public async findMany(ids: Array<string | number>): Promise<Array<BaseRecord>> {
const reference: any = {}
reference[this.idName()] = In(ids)
const instances = await this.model.findBy(reference)
return instances.map((instance) => new BaseRecord(instance, this))
}
public async create(params: Record<string, any>): Promise<ParamsType> {
const instance = this.model.create(flat.unflatten(this.prepareParams(params)))
await this.validateAndSave(instance)
return instance
}
public async update(pk: string | number, params: any = {}): Promise<ParamsType> {
const reference: any = {}
reference[this.idName()] = pk
const instance = await this.model.findOneBy(reference)
if (instance) {
const preparedParams = flat.unflatten<any, any>(this.prepareParams(params))
Object.keys(preparedParams).forEach((paramName) => {
instance[paramName] = preparedParams[paramName]
})
await this.validateAndSave(instance)
return instance
}
throw new Error('Instance not found.')
}
public async delete(pk: string | number): Promise<any> {
const reference: any = {}
reference[this.idName()] = pk
try {
const instance = await this.model.findOneBy(reference)
if (instance) {
await instance.remove()
}
} catch (error) {
if (error.name === 'QueryFailedError') {
throw new ValidationError({}, {
type: 'QueryFailedError',
message: error.message,
})
}
throw error
}
}
protected prepareProps() {
const { columns } = this.model.getRepository().metadata
return columns.reduce((memo, col, index) => {
const property = new Property(col, index)
return {
...memo,
[property.path()]: property,
}
}, {})
}
/** Converts params from string to final type */
protected prepareParams(params: Record<string, any>): Record<string, any> {
const preparedParams: Record<string, any> = { ...params }
this.properties().forEach((property) => {
const param = flat.get(preparedParams, property.path())
const key = property.path()
// eslint-disable-next-line no-continue
if (param === undefined) { return }
const type = property.type()
if (type === 'mixed') {
preparedParams[key] = param
}
if (type === 'number') {
if (property.isArray()) {
preparedParams[key] = param ? param.map((p) => safeParseNumber(p)) : param
} else {
preparedParams[key] = safeParseNumber(param)
}
}
if (type === 'reference') {
if (param === null) {
preparedParams[property.column.propertyName] = null
} else {
const [ref, foreignKey] = property.column.propertyPath.split('.')
const id = (property.column.type === Number) ? Number(param) : param
preparedParams[ref] = foreignKey ? {
[foreignKey]: id,
} : id
}
}
})
return preparedParams
}
// eslint-disable-next-line class-methods-use-this
async validateAndSave(instance: BaseEntity): Promise<any> {
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(validationErrors)
}
}
try {
await instance.save()
} catch (error) {
if (error.name === 'QueryFailedError') {
throw new ValidationError({
[error.column]: {
type: 'QueryFailedError',
message: error.message,
},
})
}
}
}
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
public static isAdapterFor(rawResource: any): boolean {
try {
return !!rawResource.getRepository().metadata
} catch (e) {
return false
}
}
}