Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions __tests__/withPlannings.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import type { HitV1 } from '@ttab/elephant-api/index'
import type { Session } from 'next-auth'
import type { Index } from '@/shared/Index'

const { fetchMock } = vi.hoisted(() => ({ fetchMock: vi.fn() }))

vi.mock('@/hooks/index/useDocuments/lib/fetch', () => ({ fetch: fetchMock }))

const { withPlannings } = await import('@/hooks/index/useDocuments/lib/withPlannings')

const session = {} as Session
const index = {} as unknown as Index
const hit = (id: string): HitV1 => ({ id, fields: {} }) as unknown as HitV1

describe('withPlannings', () => {
beforeEach(() => {
vi.clearAllMocks()
})

it('does not query the index when there are no events (avoids an empty-values terms query -> 500)', async () => {
const result = await withPlannings({ hits: [], session, index })

expect(fetchMock).not.toHaveBeenCalled()
expect(result).toEqual([])
})

it('queries related plannings with the event ids when events exist', async () => {
fetchMock.mockResolvedValue([])

await withPlannings({ hits: [hit('e1'), hit('e2')], session, index })

expect(fetchMock).toHaveBeenCalledTimes(1)

// The event ids must be passed as the terms `values`.
type TermsQuery = {
conditions: { bool: { must: Array<{ conditions: { terms: { values: string[] } } }> } }
}
const [arg] = fetchMock.mock.calls[0] as [{ query: TermsQuery }]
expect(arg.query.conditions.bool.must[0].conditions.terms.values).toEqual(['e1', 'e2'])
})
})
9 changes: 8 additions & 1 deletion src/hooks/index/useDocuments/lib/withPlannings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,14 @@ export async function withPlannings<T extends HitV1>({ hits, session, index }: {
}): Promise<T[]> {
if (!session || !index) return hits

const eventIDs: string[] = hits.map((hit) => hit.id)
const eventIDs: string[] = hits.map((hit) => hit.id).filter(Boolean)

// No events means there are no related plannings to look up. Skip the query:
// a `terms` query with an empty `values` is serialized without `values` at
// all, which the index rejects with a 500 (seen on dates that have no events).
if (eventIDs.length === 0) {
return hits
}

const plannings = await fetch<HitV1, withPlanningsFields>({
documentType: 'core/planning-item',
Expand Down
Loading