Skip to content

Commit b73e216

Browse files
committed
test: add a nested relations test case
1 parent ff67211 commit b73e216

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed

src/collection.ts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -586,6 +586,9 @@ export class Collection<Schema extends StandardSchemaV1> {
586586
}
587587

588588
const sanitizedInitialValues = sanitize(initialValues)
589+
590+
console.log({ sanitizedInitialValues })
591+
589592
return {
590593
sanitizedInitialValues,
591594
/**
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
import { Collection } from '#/src/collection.js'
2+
import z from 'zod'
3+
4+
it('creates a record with a nested relation through another model', async () => {
5+
const contactSchema = z.object({ email: z.email() })
6+
const userSchema = z.object({ id: z.number(), contact: contactSchema })
7+
const postSchema = z.object({
8+
title: z.string(),
9+
author: userSchema,
10+
})
11+
12+
const contacts = new Collection({ schema: contactSchema })
13+
const users = new Collection({ schema: userSchema })
14+
const posts = new Collection({ schema: postSchema })
15+
16+
users.defineRelations(({ one }) => ({
17+
contact: one(contacts),
18+
}))
19+
posts.defineRelations(({ one }) => ({
20+
author: one(users),
21+
}))
22+
23+
const contact = await contacts.create({ email: 'john@example.com' })
24+
expect(contact).toEqual({ email: 'john@example.com' })
25+
26+
const user = await users.create({ id: 1, contact })
27+
expect(user).toEqual({ id: 1, contact: { email: 'john@example.com' } })
28+
29+
/**
30+
* Creating a post introduces this relation chain:
31+
* post.author -> user.contact -> contact
32+
*
33+
* Due to our sanitization logic, `author.contact` will be reset to
34+
* the default value based on its relation (`undefined` here).
35+
*/
36+
const post = await posts.create({ title: 'First', author: user })
37+
expect(post).toEqual({
38+
title: 'First',
39+
author: {
40+
id: 1,
41+
contact: { email: 'john@example.com' },
42+
},
43+
})
44+
})

0 commit comments

Comments
 (0)