|
| 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