Skip to content

Instantly share code, notes, and snippets.

@brunos3d
Created July 2, 2023 22:55
Show Gist options
  • Save brunos3d/462f2bfffb9cbecaf63c3984a1047701 to your computer and use it in GitHub Desktop.
Save brunos3d/462f2bfffb9cbecaf63c3984a1047701 to your computer and use it in GitHub Desktop.
Wait for Meilisearch Task
import MeiliSearch from 'meilisearch';
export type WaitForTaskOptions = {
client: MeiliSearch;
taskUid: number;
retries?: number;
retryDelay?: number;
customErrorMessage?: string;
};
export async function waitForTask(options: WaitForTaskOptions) {
const {
client,
taskUid,
retries = 5,
retryDelay = 1000,
customErrorMessage = 'Task Failed',
} = options;
const task = await client.getTask(taskUid);
const { status } = task;
if (status === 'failed') throw new Error(customErrorMessage);
if (status === 'enqueued' || status === 'processing') {
await new Promise((resolve) => setTimeout(resolve, retryDelay));
return await waitForTask({ client, taskUid, retries: retries - 1 });
}
return task;
}
export default waitForTask;

Wait For Meilisearch Task

Usage example

import MeiliSearch from 'meilisearch';

import { waitForTask } from './wait-for-task';

export type InitIndexOptions = {
  client: MeiliSearch;
  indexName: string;
};

export async function initIndex({ client, indexName }: InitIndexOptions) {
  try {
    return await client.getIndex(indexName);
  } catch (error) {
    const task = await client.createIndex(indexName, {
      primaryKey: 'id',
    });

    await waitForTask({
      client,
      taskUid: task.taskUid,
      customErrorMessage: 'Failed to create index',
    });

    return await client.getIndex(indexName);
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment