|
| 1 | +import { createStore, fillState } from 'test/Helpers' |
| 2 | +import { Model, Attr, Str, HasOne } from '@/index' |
| 3 | + |
| 4 | +describe('feature/relations/constraints/constraints', () => { |
| 5 | + class User extends Model { |
| 6 | + static entity = 'users' |
| 7 | + |
| 8 | + @Attr() id!: number |
| 9 | + @Str('') name!: string |
| 10 | + |
| 11 | + @HasOne(() => Phone, 'userId') |
| 12 | + phone!: Phone | null |
| 13 | + } |
| 14 | + |
| 15 | + class Phone extends Model { |
| 16 | + static entity = 'phones' |
| 17 | + |
| 18 | + @Attr() id!: number |
| 19 | + @Attr() userId!: number |
| 20 | + @Str('') number!: string |
| 21 | + |
| 22 | + @HasOne(() => Type, 'phoneId') |
| 23 | + type!: Type | null |
| 24 | + } |
| 25 | + |
| 26 | + class Type extends Model { |
| 27 | + static entity = 'types' |
| 28 | + |
| 29 | + @Attr() id!: number |
| 30 | + @Attr() phoneId!: number |
| 31 | + @Str('') name!: string |
| 32 | + } |
| 33 | + |
| 34 | + it('can add constraints to the relationship query', async () => { |
| 35 | + const store = createStore() |
| 36 | + |
| 37 | + fillState(store, { |
| 38 | + users: { |
| 39 | + 1: { id: 1, name: 'John Doe' }, |
| 40 | + 2: { id: 2, name: 'Jane Doe' }, |
| 41 | + 3: { id: 3, name: 'Johnny Doe' } |
| 42 | + }, |
| 43 | + phones: { |
| 44 | + 1: { id: 1, userId: 1, number: '123' }, |
| 45 | + 2: { id: 2, userId: 2, number: '345' }, |
| 46 | + 3: { id: 3, userId: 3, number: '789' } |
| 47 | + } |
| 48 | + }) |
| 49 | + |
| 50 | + const users = store |
| 51 | + .$repo(User) |
| 52 | + .with('phone', (query) => { |
| 53 | + query.where('number', '345') |
| 54 | + }) |
| 55 | + .get() |
| 56 | + |
| 57 | + expect(users[0].phone).toBe(null) |
| 58 | + expect(users[1].phone!.number).toBe('345') |
| 59 | + expect(users[2].phone).toBe(null) |
| 60 | + }) |
| 61 | + |
| 62 | + it('can load nested relationships', async () => { |
| 63 | + const store = createStore() |
| 64 | + |
| 65 | + fillState(store, { |
| 66 | + users: { |
| 67 | + 1: { id: 1, name: 'John Doe' }, |
| 68 | + 2: { id: 2, name: 'Jane Doe' }, |
| 69 | + 3: { id: 3, name: 'Johnny Doe' } |
| 70 | + }, |
| 71 | + phones: { |
| 72 | + 1: { id: 1, userId: 1, number: '123' }, |
| 73 | + 2: { id: 2, userId: 2, number: '345' }, |
| 74 | + 3: { id: 3, userId: 3, number: '789' } |
| 75 | + }, |
| 76 | + types: { |
| 77 | + 1: { id: 1, phoneId: 1, name: 'iPhone' }, |
| 78 | + 2: { id: 2, phoneId: 2, name: 'Android' } |
| 79 | + } |
| 80 | + }) |
| 81 | + |
| 82 | + const users = store |
| 83 | + .$repo(User) |
| 84 | + .with('phone', (query) => { |
| 85 | + query.with('type') |
| 86 | + }) |
| 87 | + .get() |
| 88 | + |
| 89 | + expect(users[0].phone!.type!.id).toBe(1) |
| 90 | + expect(users[1].phone!.type!.id).toBe(2) |
| 91 | + expect(users[2].phone!.type).toBe(null) |
| 92 | + }) |
| 93 | +}) |
0 commit comments