import type { MediaItem } from './types'; export type FetchMediaOptions = { type: string; query?: string; language?: string; category?: string; playlistType?: string; offset?: number; limit?: number; signal?: AbortSignal; }; export type FetchMediaResult = { items: MediaItem[]; hasMore: boolean; }; function getConfig() { return window.voltaxModalConfig; } function getPageSize() { return getConfig()?.pageSize ?? 50; } function parseItems( type: string, json: Record, query: string, limit: number ): FetchMediaResult { if ( json?.data && typeof json.data === 'object' && 'error' in ( json.data as object ) ) { return { items: [ { payload_id: 'error', error: String( ( json.data as { error: unknown } ).error ), }, ], hasMore: false, }; } if ( type === 'video' ) { const videos = ( json?.data as { videos?: Record } | undefined )?.videos ?? {}; const items = Object.values( videos ).filter( Boolean ) as MediaItem[]; if ( ! items.length && query ) { return { items: [ { payload_id: 'error', error: 'There are no results matching your search. Please try different keywords.', }, ], hasMore: false, }; } return { items, hasMore: items.length >= limit, }; } const rawItems = ( ( json?.data ?? [] ) as MediaItem[] ).filter( Boolean ); const items = rawItems .map( ( item ) => { const payloadId = String( item.payload_id || item.id || '' ).trim(); if ( ! payloadId ) { return null; } return { ...item, payload_id: payloadId, }; } ) .filter( ( item ): item is MediaItem => item !== null ); if ( ! items.length && query ) { return { items: [ { payload_id: 'error', error: 'There are no results matching your search. Please try different keywords.', }, ], hasMore: false, }; } return { items, hasMore: items.length >= limit, }; } export async function fetchMedia( options: FetchMediaOptions ): Promise { const { type, query = '', language = '', category = '', playlistType = '', offset = 0, limit = getPageSize(), signal } = options; const config = getConfig(); if ( ! config ) { return { items: [ { payload_id: 'error', error: 'Modal is not configured.' } ], hasMore: false, }; } const params = new URLSearchParams( { action: 'voltax_get_mm_data', nonce: config.nonce, type, query, offset: String( offset ), limit: String( limit ), cachebust: String( Date.now() ), } ); if ( language ) { params.set( 'language', language ); } if ( category ) { params.set( 'category', category ); } if ( playlistType ) { params.set( 'playlist_type', playlistType ); } const response = await fetch( `${ config.ajaxUrl }?${ params }`, { method: 'GET', credentials: 'same-origin', signal, } ); const json = await response.json(); return parseItems( type, json, query, limit ); }