-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathadapterUtils.ts
More file actions
381 lines (328 loc) · 10.6 KB
/
adapterUtils.ts
File metadata and controls
381 lines (328 loc) · 10.6 KB
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
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
import type {EntityMetadata, EntityProperty, MikroORM} from "@mikro-orm/core"
import {ReferenceKind, serialize} from "@mikro-orm/core"
import type {Where} from "better-auth"
import {dset} from "dset"
import {createAdapterError} from "./createAdapterError.js"
export interface AdapterUtils {
/**
* Normalizes given model `name` for Mikro ORM using [naming strategy](https://mikro-orm.io/docs/naming-strategy) defined by the config.
*
* @param name - The name of the entity
*/
normalizeEntityName(name: string): string
/**
* Returns metadata for given `entityName` from MetadataStorage.
*
* @param entityName - The name of the entity to get the metadata for
*
* @throws BetterAuthError when no metadata found
*/
getEntityMetadata(name: string): EntityMetadata
/**
* Returns a path to a `field` reference.
*
* @param entityName - The name of the entity
* @param fieldName - The field's name
* @param throwOnShadowProps - Whether or throw error for Shadow Props. Use it for where clause so Mikro ORM will not throw when accessing such props from database.
*
* @throws BetterAuthError when no such field exist on the `entity`
* @throws BetterAuthError if complex primary key is discovered in `fieldName` relation
*/
getFieldPath(
metadata: EntityMetadata,
fieldName: string,
throwOnShadowProps?: boolean
): string[]
/**
* Normalized Better Auth data for Mikro ORM.
*
* @param entityName - The name of the entity
* @param input - The data to normalize
*/
normalizeInput(
metadata: EntityMetadata,
input: Record<string, any>
): Record<string, any>
/**
* Normalizes the Mikro ORM output for Better Auth.
*
* @param entityName - The name of the entity
* @param output - The result of a Mikro ORM query
* @param select - A list of fields to return
*/
normalizeOutput(
metadata: EntityMetadata,
output: Record<string, any>,
select?: string[]
): Record<string, any>
/**
* Transfroms hiven list of Where clause(s) for Mikro ORM.
*
* @param entityName - Entity name
* @param where - A list where clause(s) to normalize
*/
normalizeWhereClauses(
metadata: EntityMetadata,
where?: Where[]
): Record<string, any>
}
const ownReferences = [
ReferenceKind.SCALAR,
ReferenceKind.ONE_TO_MANY,
ReferenceKind.EMBEDDED
]
/**
* Creates bunch of utilities for adapter
*
* @param orm - Mikro ORM instance
*/
export function createAdapterUtils(orm: MikroORM): AdapterUtils {
const naming = orm.config.getNamingStrategy()
const metadata = orm.getMetadata()
const normalizeEntityName: AdapterUtils["normalizeEntityName"] = name =>
naming.getEntityName(naming.classToTableName(name))
const getEntityMetadata: AdapterUtils["getEntityMetadata"] = (
entityName: string
) => {
entityName = normalizeEntityName(entityName)
if (!metadata.getByClassName(entityName, false)) {
createAdapterError(
`Cannot find metadata for "${entityName}" entity. Make sure it defined and listed in your Mikro ORM config.`
)
}
return metadata.getByClassName(entityName)
}
/**
* Returns metadata for a property by given `fieldName`.
*
* @param metadata - Entity metadata
* @param fieldName - The name of the field to get metadata for
*/
function getPropertyMetadata(
metadata: EntityMetadata,
fieldName: string
): EntityProperty {
const prop = metadata.props.find(prop => {
if (ownReferences.includes(prop.kind) && prop.name === fieldName) {
return true
}
if (
prop.kind === ReferenceKind.MANY_TO_ONE &&
(prop.name === fieldName ||
prop.fieldNames.includes(naming.propertyToColumnName(fieldName)))
) {
return true
}
return false
})
if (!prop) {
createAdapterError(
`Can't find property "${fieldName}" on entity "${metadata.className}".`
)
}
return prop
}
/**
* Returns referenced _column_ name for given `prop` using [naming strategy](https://mikro-orm.io/docs/naming-strategy) defined by the config.
*
* @param entityName - The name of the entity
* @param prop - Property metadata
*/
function getReferencedColumnName(entityName: string, prop: EntityProperty) {
if (ownReferences.includes(prop.kind)) {
return prop.name
}
if (prop.kind === ReferenceKind.MANY_TO_ONE) {
return naming.columnNameToProperty(naming.joinColumnName(prop.name))
}
createAdapterError(
`Reference kind ${prop.kind} is not supported. Defined in "${entityName}" entity for "${prop.name}" field.`
)
}
/**
* Returns referenced _property_ name in camelCase.
*
* @param entityName - The name of the entity
* @param prop - Property metadata
*/
const getReferencedPropertyName = (
metadata: EntityMetadata,
prop: EntityProperty
) => getReferencedColumnName(metadata.className, prop)
const getFieldPath: AdapterUtils["getFieldPath"] = (
metadata,
fieldName,
throwOnShadowProps = false
) => {
const prop = getPropertyMetadata(metadata, fieldName)
if (prop.persist === false && throwOnShadowProps) {
createAdapterError(
`Cannot serialize "${fieldName}" into path, because it cannot be persisted in "${metadata.tableName}" table.`
)
}
if (
prop.kind === ReferenceKind.SCALAR ||
prop.kind === ReferenceKind.EMBEDDED
) {
return [prop.name]
}
if (prop.kind === ReferenceKind.MANY_TO_ONE) {
if (prop.referencedPKs.length > 1) {
createAdapterError(
`The "${fieldName}" field references to a table "${prop.name}" with complex primary key, which is not supported`
)
}
return [prop.name, naming.referenceColumnName()]
}
createAdapterError(
`Cannot normalize "${fieldName}" field name into path for "${metadata.className}" entity.`
)
}
/**
* Normalizes property's raw input value: if property is a reference,
* then it wraps value using [`orm.em.getReference`](https://mikro-orm.io/docs/entity-manager#entity-references) method,
* to unsure it's correctly persisted.
*
* Otherwise the value is returned as is.
*
* @param property - Metadata of the property
* @param value - Raw input value
*/
const normalizePropertyValue = (
property: EntityProperty,
value: unknown
): unknown => {
if (
!property.targetMeta ||
property.kind === ReferenceKind.SCALAR ||
property.kind === ReferenceKind.EMBEDDED
) {
return value
}
return orm.em.getReference(property.targetMeta.class, value)
}
const normalizeInput: AdapterUtils["normalizeInput"] = (metadata, input) => {
const fields: Record<string, any> = {}
Object.entries(input).forEach(([key, value]) => {
const property = getPropertyMetadata(metadata, key)
const normalizedValue = normalizePropertyValue(property, value)
dset(fields, [property.name], normalizedValue)
})
return fields
}
const normalizeOutput: AdapterUtils["normalizeOutput"] = (
metadata,
output
) => {
output = serialize(output)
const result: Record<string, any> = {}
Object.entries(output)
.map(([key, value]) => ({
path: getReferencedPropertyName(
metadata,
getPropertyMetadata(metadata, key)
),
value
}))
.forEach(({path, value}) => dset(result, path, value))
return result
}
/**
* Creates a `where` clause with given params.
*
* @param fieldName - The name of the field
* @param path - Path to the field reference
* @param value - Field's value
* @param op - Query operator
* @param target - Target object to assign the result to. The object will be *mutated*
*/
function createWhereClause(
path: Array<string | number>,
value: unknown,
op?: string,
target: Record<string, any> = {}
): Record<string, any> {
dset(target, op == null || op === "eq" ? path : path.concat(op), value)
return target
}
/**
* Same as `createWhereClause`, but creates a statement with only `$in` operator and check if the `value` is an array.
*
* @param fieldName - The name of the field
* @param path - Path to the field reference
* @param value - Field's value
* @param target - Target object to assign the result to. The object will be *mutated*
*/
function createWhereInClause(
fieldName: string,
path: Array<string | number>,
value: unknown,
target?: Record<string, any>
): Record<string, any> {
if (!Array.isArray(value)) {
createAdapterError(
`The value for the field "${fieldName}" must be an array when using the $in operator.`
)
}
return createWhereClause(path, value, "$in", target)
}
const normalizeWhereClauses: AdapterUtils["normalizeWhereClauses"] = (
metadata,
where
) => {
if (!where) {
return {}
}
if (where.length === 1) {
const [w] = where
if (!w) {
return {}
}
const path = getFieldPath(metadata, w.field, true)
switch (w.operator) {
case "in":
return createWhereInClause(w.field, path, w.value)
case "contains":
return createWhereClause(path, `%${w.value}%`, "$like")
case "starts_with":
return createWhereClause(path, `${w.value}%`, "$like")
case "ends_with":
return createWhereClause(path, `%${w.value}`, "$like")
// The next 5 case statemets are _expected_ to fall through so we can simplify and reuse the same logic for these operators
case "gt":
case "gte":
case "lt":
case "lte":
case "ne":
return createWhereClause(path, w.value, `$${w.operator}`)
default:
return createWhereClause(path, w.value)
}
}
const result: Record<string, any> = {}
where
.filter(({connector}) => !connector || connector === "AND")
.forEach(({field, operator, value}, index) => {
const path = ["$and", index].concat(getFieldPath(metadata, field, true))
if (operator === "in") {
return createWhereInClause(field, path, value, result)
}
return createWhereClause(path, value, "eq", result)
})
where
.filter(({connector}) => connector === "OR")
.forEach(({field, value}, index) => {
const path = ["$and", index].concat(getFieldPath(metadata, field, true))
return createWhereClause(path, value, "eq", result)
})
return result
}
return {
getEntityMetadata,
normalizeEntityName,
getFieldPath,
normalizeInput,
normalizeOutput,
normalizeWhereClauses
}
}