import type { ApiCollection, MessageResource } from '../../../types' import { anchoredPageParam, isBehindLiveEdge, livePageParam, markLiveIfCaughtUp, MessagesWindow, newestFirst, } from '../messages_window' const page = (meta: Partial['meta']> = {}) => ({ data: [], links: {}, meta: { count: 0, totalCount: 0, ...meta }, }) const window = ( pageParam: MessagesWindow['pageParams'][number], meta?: Partial['meta']> ): MessagesWindow => ({ pages: [page(meta)], pageParams: [pageParam] }) describe('isBehindLiveEdge', () => { it('is behind while the first page reports newer messages', () => { expect(isBehindLiveEdge(window(anchoredPageParam('A'), { prev: { idGt: 'A' } }))).toBe(true) }) it('is live otherwise', () => { expect(isBehindLiveEdge(window(livePageParam))).toBe(false) expect(isBehindLiveEdge(window(anchoredPageParam('A')))).toBe(false) expect(isBehindLiveEdge(undefined)).toBe(false) }) }) describe('markLiveIfCaughtUp', () => { it('turns an anchored window with no newer side into the live window', () => { const data = window(anchoredPageParam('A')) expect(markLiveIfCaughtUp(data)?.pageParams).toEqual([livePageParam]) }) it('turns a window topped by a newer page into the live window once it catches up', () => { const data = window({ where: { id_gt: 'A' }, order: 'asc' }) expect(markLiveIfCaughtUp(data)?.pageParams).toEqual([livePageParam]) }) it('leaves an anchored window that is still behind untouched', () => { const data = window(anchoredPageParam('A'), { prev: { idGt: 'A' } }) expect(markLiveIfCaughtUp(data)).toBe(data) }) it('leaves a live window untouched', () => { const data = window(livePageParam) expect(markLiveIfCaughtUp(data)).toBe(data) }) }) describe('newestFirst', () => { const row = (id: string) => ({ id, type: 'Message' }) as MessageResource const ascPage = { ...page({ next: { idGt: 'E' } }), data: [row('D'), row('E')], } it('stores a newer page newest first, linking newer onward and back to older rows', () => { const result = newestFirst(ascPage, { where: { id_gt: 'C' }, order: 'asc' }) expect(result.data.map(m => m.id)).toEqual(['E', 'D']) expect(result.meta.prev).toEqual({ idGt: 'E' }) expect(result.meta.next).toEqual({ idLt: 'D' }) }) it('leaves newest-first pages alone', () => { expect(newestFirst(ascPage, anchoredPageParam('A'))).toBe(ascPage) }) })