import { MeiliSearchTimeOutError } from '../errors' ; import { Config , Task , WaitOptions , TaskStatus , Result } from '../types' ; import { HttpRequests } from './http-requests' ; import { sleep } from './utils' ; class TaskClient { httpRequest : HttpRequests ; constructor ( config ) { this . httpRequest = new HttpRequests ( config ) ; } async getClientTask ( uid ) { const url = `tasks/${ uid }` ; return await this . httpRequest . get < Task > ( url ) ; } async getClientTasks ( ) { const url = `tasks` ; return await this . httpRequest . get < Result < Task [ ] > > ( url ) ; } async getIndexTask ( indexUid , taskId ) { const url = `indexes/${ indexUid }/tasks/${ taskId }` ; return await this . httpRequest . get < Task > ( url ) ; } async getIndexTasks ( indexUid ) { const url = `indexes/${ indexUid }/tasks` ; return await this . httpRequest . get < Result < Task [ ] > > ( url ) ; } param { number } uid param { WaitOptions } options returns { Promise < Task > } async waitForClientTask ( taskId , { timeOutMs = 5000 , intervalMs = 50 } = { } ) { const startingTime = Date . now ( ) ; while ( Date . now ( ) - startingTime < timeOutMs ) { const response = await this . getClientTask ( taskId ) ; if ( ! [ TaskStatus . TASK_ENQUEUED , TaskStatus . TASK_PROCESSING ] . includes ( response . status ) ) return response ; await sleep ( intervalMs ) ; } throw new MeiliSearchTimeOutError ( `timeout of ${ timeOutMs }ms has exceeded on process ${ taskId } when waiting a task to be resolved.` ) ; } param { number } taskIds param { WaitOptions } options returns { Promise < Result < Task [ ] > > } async waitForClientTasks ( taskIds , { timeOutMs = 5000 , intervalMs = 50 } = { } ) { const tasks = [ ] ; for ( const taskId of taskIds ) { const task = await this . waitForClientTask ( taskId , { timeOutMs , intervalMs } ) ; tasks . push ( task ) ; } return { results : tasks } ; } param { number } taskId param { WaitOptions } options returns { Promise < Task > } async waitForIndexTask ( indexUid , taskId , { timeOutMs = 5000 , intervalMs = 50 } = { } ) { const startingTime = Date . now ( ) ; while ( Date . now ( ) - startingTime < timeOutMs ) { const response = await this . getIndexTask ( indexUid , taskId ) ; if ( ! [ TaskStatus . TASK_ENQUEUED , TaskStatus . TASK_PROCESSING ] . includes ( response . status ) ) return response ; await sleep ( intervalMs ) ; } throw new MeiliSearchTimeOutError ( `timeout of ${ timeOutMs }ms has exceeded on process ${ taskId } when waiting for pending update to resolve.` ) ; } } export { TaskClient } ;