Skip to content

Commit 263516a

Browse files
authored
Merge pull request #22 from octet-stream/fix/references
2 parents b6e8020 + fe209dc commit 263516a

File tree

3 files changed

+52
-2
lines changed

3 files changed

+52
-2
lines changed

.changeset/spotty-peaches-hunt.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"better-auth-mikro-orm": patch
3+
---
4+
5+
Use `getReference` to ensure references loaded correctly

src/utils/adapterUtils.ts

Lines changed: 29 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -207,11 +207,38 @@ export function createAdapterUtils(orm: MikroORM): AdapterUtils {
207207
)
208208
}
209209

210+
/**
211+
* Normalizes property's raw input value: if property is a reference,
212+
* then it wraps value using [`orm.em.getReference`](https://mikro-orm.io/docs/entity-manager#entity-references) method,
213+
* to unsure it's correctly persisted.
214+
*
215+
* Otherwise the value is returned as is.
216+
*
217+
* @param property - Metadata of the property
218+
* @param value - Raw input value
219+
*/
220+
const normalizePropertyValue = (
221+
property: EntityProperty,
222+
value: unknown
223+
): unknown => {
224+
if (
225+
!property.targetMeta ||
226+
property.kind === ReferenceKind.SCALAR ||
227+
property.kind === ReferenceKind.EMBEDDED
228+
) {
229+
return value
230+
}
231+
232+
return orm.em.getReference(property.targetMeta.class, value)
233+
}
234+
210235
const normalizeInput: AdapterUtils["normalizeInput"] = (metadata, input) => {
211236
const fields: Record<string, any> = {}
212237
Object.entries(input).forEach(([key, value]) => {
213-
const path = getFieldPath(metadata, key)
214-
dset(fields, path, value)
238+
const property = getPropertyMetadata(metadata, key)
239+
const normalizedValue = normalizePropertyValue(property, value)
240+
241+
dset(fields, [property.name], normalizedValue)
215242
})
216243

217244
return fields

tests/node/adapter.test.ts

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,24 @@ suite("create", () => {
5050
expect(actual.userId).toBe(user.id)
5151
})
5252

53+
// https://github.com/octet-stream/better-auth-mikro-orm/issues/18
54+
test("with referenced value not presented in Identity Map (issue #18)", async () => {
55+
const user = await randomUsers.createAndFlushOne()
56+
57+
orm.em.clear()
58+
59+
const actual = await adapter.create<SessionInput, DatabaseSession>({
60+
model: "session",
61+
data: {
62+
token: generateId(),
63+
userId: user.id,
64+
expiresAt: new Date()
65+
}
66+
})
67+
68+
expect(actual.userId).toBe(user.id)
69+
})
70+
5371
suite("generateId", () => {
5472
suite("via database.generateId option", () => {
5573
test("custom generator", async () => {

0 commit comments

Comments
 (0)