Meilisearch JavaScript Client

repository·main·Indexed 21 days ago

https://github.com/meilisearch/meilisearch-js

The official API client for interacting with the Meilisearch search engine from JavaScript environments, including Node.js and the browser. Version 0.60.0 provides full TypeScript support and features for managing search indexes, performing typo-tolerant searches with filters and highlighting, and handling batch operations. It includes specialized support for React Native and Deno, as well as experimental ChatWorkspace features for streaming chat completions.

Tokens
16.2K
Snippets
72
Records
91
Agent score
73%

What's inside meilisearch-js

  1. Initialize the Meilisearch client

    main

    To use the SDK, import Meilisearch and instantiate it with a host and an apiKey. You can use either CommonJS require or ES modules import syntax.

    const { Meilisearch } = require("meilisearch");
    // Or if you are in a ES environment
    import { Meilisearch } from "meilisearch";
    
    const client = new Meilisearch({
      host: "http://127.0.0.1:7700",
      apiKey: "masterKey",
    });
  2. Install the Meilisearch JavaScript client

    main

    Install the meilisearch package via npm to use the official Meilisearch API client in your JavaScript project.

    Note: Node.js LTS and Maintenance versions are officially supported and tested. While other runtimes like Deno and Bun are not explicitly tested, they may work.

    npm i meilisearch
  3. Manage and monitor asynchronous tasks with TaskClient

    main

    The TaskClient class is used to interact with Meilisearch's task API. It allows you to retrieve task statuses, fetch task documents, and manage the lifecycle of asynchronous operations (like adding documents or updating settings) that Meilisearch processes in the background.

    Key capabilities include:

    • Retrieving tasks: Get a single task by its uid or list multiple tasks.
    • Polling for completion: Use waitForTask or waitForTasks to poll the Meilisearch API until a task reaches a terminal state (not enqueued or processing).
    • Managing task documents: Retrieve the documents associated with a specific task.
    • Canceling or deleting tasks: Stop pending tasks or remove them from the queue.

    When initializing TaskClient, you can provide WaitOptions to set default timeout and interval values for polling operations.

    import { TaskClient } from './task.js';
    
    // Assuming httpRequest is already configured
    const taskClient = new TaskClient(httpRequest, {
      timeout: 10_000,
      interval: 100
    });
  4. Define search rules for Tenant Tokens

    main

    Tenant tokens use TokenSearchRules to restrict what a user can search. This can be defined in two ways:

    1. An array of strings: A simple list of rules.
    2. A record of index rules: An object where keys are index names and values are TokenIndexRules (which contain an optional filter).

    TokenIndexRules structure:

    • filter: An optional Filter applied to the index.

    TokenSearchRules type definition:

    export type TokenSearchRules = Record<string, TokenIndexRules | null> | string[];
  5. Understand the SearchResponse structure

    main

    A search request returns a SearchResponse<T>, which contains the results and metadata.

    Fields include:

    • hits: An array of Hit<T> objects containing the actual documents.
    • processingTimeMs: Time taken to process the query.
    • query: The original query string.
    • facetDistribution: A mapping of facet values to their counts.
    • facetStats: Statistics for facets (min/max values).
    • totalHits: Total number of matching documents (if using finite pagination).
    • totalPages: Total number of pages (if using finite pagination).
    // Example response shape
    const response: SearchResponse<MyDocument> = {
      hits: [{ id: 1, title: 'Result' }],
      processingTimeMs: 5,
      query: 'term',
      totalHits: 100,
      hitsPerPage: 10,
      page: 0,
      totalPages: 10
    };
  6. Use the waitTask() method on EnqueuedTaskPromise

    main

    When an operation returns an EnqueuedTaskPromise (like cancelTasks or deleteTasks), you can call .waitTask(options?) directly on that promise. This is a convenient way to await the completion of the task that was just enqueued without manually managing the uid or using taskClient.waitForTask() separately.

    // Example of using the convenience .waitTask() method
    const enqueuedTaskPromise = taskClient.cancelTasks({ /* params */ });
    
    // The promise is augmented with the waitTask method
    const task = await enqueuedTaskPromise.waitTask({ timeout: 10000 });
    console.log('Task completed:', task.status);
  7. Awaiting an EnqueuedTask via EnqueuedTaskPromise

    main

    When you perform an asynchronous operation in Meilisearch (like adding documents), the client returns an EnqueuedTaskPromise. This is a Promise that resolves to an EnqueuedTask, but it also includes a special .waitTask() method.

    Calling .waitTask() will poll the Meilisearch server until the task reaches a terminal state (succeeded, failed, or canceled), at which point it resolves to a full Task object containing details and errors.

    // The returned promise from an async operation
    const enqueuedTask = await client.addDocuments('movies', documents);
    
    // Await the actual completion of the task
    const task = await enqueuedTask.waitTask({ timeout: 10000 });
    
    if (task.error) {
      console.error('Task failed:', task.error);
    } else {
      console.log('Task succeeded:', task.uid);
    }
  8. Configure custom request settings and proxies

    main

    If Meilisearch is behind a proxy, you can customize the request behavior via the Meilisearch constructor.

    Custom Headers and Credentials: Use requestConfig to pass headers or set credentials (e.g., 'include').

    Custom HTTP Client: Provide an httpClient function to use a different library like axios. The function receives url and opts (containing body, headers, and method) and must return the response data.

    // Custom request config
    const client: Meilisearch = new Meilisearch({
      host: "http://localhost:3000/api/meilisearch/proxy",
      requestConfig: {
        headers: {
          Authorization: AUTH_TOKEN,
        },
        // OR
        credentials: "include",
      },
    });
    
    // Custom http client
    const client: Meilisearch = new Meilisearch({
      host: "http://localhost:3000/api/meilisearch/proxy",
      httpClient: async (url, opts) => {
        const response = await $axios.request({
          url,
          data: opts?.body,
          headers: opts?.headers,
          method: (opts?.method?.toLocaleUpperCase() as Method) ?? "GET",
        });
    
        return response.data;
      },
    });
  9. Apply oxlint overrides for specific files

    main

    The overrides array allows you to apply different rules, plugins, or settings to specific file patterns. Each override object can contain:

    • files: A glob pattern matching the files to which the override applies.
    • rules: A set of rules specific to these files.
    • jsPlugins: JavaScript plugins to load (e.g., eslint-plugin-tsdoc).
    • plugins: Additional plugins (e.g., vitest).
    overrides: [
      {
        files: ["src/**/*.ts"],
        jsPlugins: ["eslint-plugin-tsdoc"],
        rules: {
          "tsdoc/syntax": "error",
        },
      },
      {
        files: ["tests/**/*.test.ts"],
        plugins: ["vitest"],
        rules: {
          "vitest/expect-expect": "error",
        },
      }
    ]