Skip to content

Child relations fail when only one related record exists #379

@jakobrosenberg

Description

@jakobrosenberg

When using RelationMany with a where clause like [['branch_id', '=', '$id']], the relation works as expected if multiple related records exist. However, when only a single related record exists, it resolves to an empty array.

import { Schema as S, TriplitClient } from '@triplit/client'
import { createServer, createTriplitStorageProvider } from '@triplit/server'
import jwt from 'jsonwebtoken'

const jwtSecret = 'test'
const token = jwt.sign({ 'x-triplit-token-type': 'secret' }, jwtSecret)

const schema = S.Collections({
  branches: {
    schema: S.Schema({
      id: S.String(),
      branch_id: S.String({ nullable: true }),
    }),
    relationships: {
      branches: S.RelationMany('branches', { where: [['branch_id', '=', '$id']] }),
    },
  },
})

const client = new TriplitClient({ serverUrl: 'http://localhost:1235', token, schema })

beforeAll(async () => {
  const startServer = await createServer({
    storage: await createTriplitStorageProvider('memory'),
    jwtSecret,
    dbOptions: { schema: { collections: schema } },
  })
  startServer(1235)
})

beforeEach(() => client.http.deleteAll('branches'))

describe('Child relations', async () => {
  test('can see two child relations', async () => {
    await client.http.bulkInsert({
      branches: [
        { id: 'a', branch_id: null },
        { id: 'b', branch_id: 'a' },
        { id: 'c', branch_id: 'a' },
      ],
    })
    const result = await client.http.fetchOne(client.query('branches').Id('a').Include('branches'))
    expect(result.branches.length).toBe(2)
  })

  // BROKEN
  test('can see one child relation', async () => {
    await client.http.bulkInsert({
      branches: [
        { id: 'a', branch_id: null },
        { id: 'b', branch_id: 'a' },
        // { id: 'c', branch_id: 'a' }, // leaving only one child breaks child relations
      ],
    })
    const result = await client.http.fetchOne(client.query('branches').Id('a').Include('branches'))
    expect(result.branches.length).toBe(1) // should be 1, is 0
  })
})

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions