Skip to content

Improve indexes #1918

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 25 commits into
base: main
Choose a base branch
from
Open

Conversation

flevi29
Copy link
Collaborator

@flevi29 flevi29 commented Apr 8, 2025

Pull Request

What does this PR do?

  • refactors index types so that they match the meilisearch rust source code model as much as possible
  • removes index manipulating methods from Index class that don't directly take an index UID parameter, and vice versa for MeiliSearch class
  • removes methods that query and then create Index instances from queried data
  • removes deleteIndexIfExists, this is a flawed function that is no longer required, because the base delete function doesn't throw if the index doesn't exist, so it has the same effect
  • refactors tests for these methods
  • removes tests regarding bad host and wrong permission Simplify URL construction and API error tests #1945

Migration

  • fn getRawIndex -> getIndex
  • type IndexObject -> IndexView
  • fn getRawIndexes -> getIndexes
  • type IndexesResults<IndexObject[]> -> IndexViewList
  • type IndexesQuery -> ListIndexes
  • type IndexOptions -> IndexCreateRequest
- await client.deleteIndexIfExists(uid);
+ const task = await client.index(uid).deleteIndex().waitTask();
+ const indexNotExists = task.error?.code === "index_not_found";
- await client.deleteIndex(uid).waitTask();
- await client.index(uid).delete().waitTask();
+ await client.index(uid).deleteIndex().waitTask();
- await client.updateIndex(...).waitTask();
- await client.index(uid).update(...).waitTask();
+ await client.index(uid).updateIndex(...).waitTask();
- await client.getRawIndex(uid);
- await client.index(uid).getRawInfo();
+ await client.index(uid).getIndex();
- await client.createIndex(uid, { primaryKey }).waitTask();
+ await client.createIndex({ uid, primaryKey }).waitTask();

These are hardly useful, but here's the migration anyway:

- const index = await client.getIndex(uid);
+ const index = client.index(uid);
+ const obj = { details: await index.getIndex(), index };
- const indexes = await client.getIndexes();
+ const indexes = (await client.getIndexes()).results.map((v) => ({
+   details: v,
+   index: client.index(v.uid),
+ }));

Summary by CodeRabbit

  • New Features

    • Introduced new types and method signatures for index management, providing a more consistent and streamlined API for creating, updating, deleting, and retrieving indexes.
  • Refactor

    • Standardized index operations to use object parameters and unified method names (e.g., createIndex({ uid }), getIndex(), deleteIndex()), replacing various legacy and redundant methods.
    • Encapsulated index metadata properties and simplified index class interfaces.
    • Updated pagination and task-related types for improved clarity and alignment with Meilisearch API.
    • Simplified client methods to interact directly with API endpoints, removing wrappers and deprecated calls.
  • Bug Fixes

    • Corrected method argument formats and naming across documentation, code samples, and tests to ensure compatibility with the updated API.
  • Documentation

    • Updated documentation and code samples to reflect new method signatures and usage patterns for index management.
  • Tests

    • Refactored and simplified test suites to use the new API, removing deprecated index management tests and aligning all test code with the updated method calls.
    • Added a new test for index statistics.
    • Added assertion helper for task success verification.
  • Chores

    • Improved internal type organization and exports for better maintainability.

@flevi29 flevi29 added the breaking-change The related changes are breaking for the users label Apr 8, 2025
Copy link

codecov bot commented Apr 8, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 99.92%. Comparing base (77505c0) to head (3d980b1).

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #1918      +/-   ##
==========================================
+ Coverage   99.03%   99.92%   +0.89%     
==========================================
  Files          18       18              
  Lines        1449     1382      -67     
  Branches      305      294      -11     
==========================================
- Hits         1435     1381      -54     
+ Misses         14        1      -13     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@Strift Strift marked this pull request as draft April 9, 2025 02:53
@flevi29 flevi29 mentioned this pull request Apr 9, 2025
8 tasks
@flevi29 flevi29 marked this pull request as ready for review April 9, 2025 15:21
@Strift Strift requested a review from Copilot May 15, 2025 06:46
Copy link

@Copilot Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull Request Overview

This PR refactors the index type handling to align with the MeiliSearch Rust model by renaming and restructuring several index-related methods and types. Key changes include replacing the legacy index methods (e.g. getRawIndex, deleteIndexIfExists) with new ones (getIndex, deleteIndex) and updating the corresponding tests and documentation to match the new API.

Reviewed Changes

Copilot reviewed 41 out of 41 changed files in this pull request and generated 1 comment.

Show a summary per file
File Description
tests/env/typescript-browser/src/index.ts Updated index creation and fetching methods to use new API.
tests/env/node/search_example.cjs Updated deletion and creation of indexes to use the new API methods.
tests/env/express/public/index.html and headers.html Replaced getRawInfo and delete with getIndex and deleteIndex calls.
tests/embedders.test.ts, documents.test.ts, displayed_attributes.test.ts, client.test.ts, batch.test.ts Updated test files to match method renaming and new argument signatures.
src/types/*.ts Renamed and refactored types to align with the updated index model.
src/meilisearch.ts, src/indexes.ts Refactored index-related methods and replaced deprecated calls with the new API.
playgrounds/javascript/src/meilisearch.ts, README.md, .code-samples.meilisearch.yaml Updated code samples and documentation to reflect the migration changes.
Comments suppressed due to low confidence (1)

README.md:605

  • Verify that all method signature updates in the documentation and code samples completely reflect the migration (e.g. replacing getRawIndex with getIndex and ensuring correct usage of waitTask where applicable) to avoid confusion among users.
client.createIndex({ uid: 'movies', primaryKey: 'id' })

Copy link

coderabbitai bot commented May 15, 2025

Walkthrough

This update refactors the Meilisearch client and its related codebase to modernize and standardize index management APIs. Method signatures for creating, updating, retrieving, and deleting indexes now use object parameters and return unified types. Deprecated or redundant methods are removed, and corresponding documentation, tests, and type definitions are updated to match the new API structure.

Changes

File(s) Change Summary
.code-samples.meilisearch.yaml, README.md Updated code samples and documentation to reflect new API signatures, parameter formats, and return types for index management methods.
src/indexes.ts Refactored the Index class: made uid private with a getter, removed public metadata fields, added getIndex, renamed and updated update/delete methods, and removed deprecated methods.
src/meilisearch.ts Simplified and modernized index management API: removed deprecated methods, updated method signatures, and aligned client methods with Meilisearch REST API endpoints.
src/types/index.ts, src/types/indexes.ts, src/types/shared.ts, src/types/types.ts Added new types for index operations, refactored pagination types, removed deprecated index-related types, and updated exports for new/renamed modules.
src/types/task-and-batch.ts Updated types to use new index swap payloads, introduced a generic paginated results type, and updated related type usages.
playgrounds/javascript/src/meilisearch.ts, tests/**/*.test.ts, `tests/env/**/*.html ts
tests/client.test.ts, tests/index.test.ts Removed and replaced extensive index management tests with a streamlined suite focusing on core index operations and swaps, using new API methods and types.
tests/utils/meilisearch-test-utils.ts Updated helper functions to use new index API and added a utility to assert task success.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant MeiliSearch
    participant Index

    Client->>MeiliSearch: createIndex({ uid: "movies" })
    MeiliSearch-->>Client: EnqueuedTaskPromise

    Client->>MeiliSearch: getIndexes()
    MeiliSearch-->>Client: IndexViewList

    Client->>MeiliSearch: index("movies")
    MeiliSearch-->>Client: Index instance

    Client->>Index: getIndex()
    Index-->>Client: IndexView

    Client->>Index: updateIndex({ primaryKey: "id" })
    Index-->>Client: EnqueuedTaskPromise

    Client->>Index: deleteIndex()
    Index-->>Client: EnqueuedTaskPromise
Loading

Poem

In the warren of code, we’ve tidied our nest,
Indexes now sparkle, their APIs at their best.
With objects and promises, we hop right along,
Out with the old, in with the strong!
🐇✨
So here’s to clean signatures, types crisp and neat—
This rabbit’s heart thumps for code that’s complete!


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Lite
Cache: Disabled due to data retention organization setting
Knowledge Base: Disabled due to data retention organization setting

📥 Commits

Reviewing files that changed from the base of the PR and between db83046 and 3d980b1.

📒 Files selected for processing (2)
  • tests/index-stats.test.ts (1 hunks)
  • tests/index.test.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • tests/index-stats.test.ts
🔇 Additional comments (8)
tests/index.test.ts (8)

1-10: Well-structured test setup with good practices!

Using random UUIDs for test indexes is excellent for preventing test collisions and dependencies. The test setup is clean and follows modern testing best practices with proper imports and client initialization.


11-15: Good verification of the index instance creation

This test correctly validates that the index method returns a proper Index instance with the expected uid. This aligns with the PR objective of refactoring index types to better match the Rust model.


17-24: Excellent test cleanup implementation

The cleanup logic ensures all test indexes are deleted after the test suite completes, preventing test pollution. Using Promise.all for parallel deletion is an efficient approach, and the verification that each deletion task succeeds is thorough.


26-45: Test correctly implements the new index creation API pattern

This test validates the refactored API structure described in the PR objectives:

  1. Using object parameters ({ uid: INDEX_UID_ONE, primaryKey })
  2. Validating task properties including type and details
  3. Using the new instance method .getIndex() instead of older client-level methods

The test also correctly destructures the response to verify date fields separately from the stable index data fields.


47-65: Update index test aligns with new API patterns

The test appropriately uses the instance method index.updateIndex({ primaryKey }) with object parameters as described in the PR objectives, and correctly validates both the task response and the updated index state.


67-74: Delete index test follows the new API pattern

This test demonstrates the new approach to deleting indexes from an instance rather than a client-level method. The assertions thoroughly verify the deletion task was successful, properly identifying the affected index and checking task details.


76-101: Swap indexes test provides good coverage of multi-index operations

This test effectively validates that the swapIndexes functionality works correctly by:

  1. Creating documents in two separate indexes
  2. Performing the swap operation
  3. Verifying the documents were properly exchanged between indexes

The test follows the new API pattern using SwapIndexesPayload[] type and includes comprehensive verification of both the task details and the actual document state after the swap.


1-101: Overall test suite aligns well with PR objectives

The entire test suite successfully implements and validates the refactored index API described in the PR objectives. The tests:

  1. Use object parameters instead of string UIDs
  2. Utilize instance methods instead of client-level methods
  3. Verify proper task responses and index states
  4. Include comprehensive cleanup logic
  5. Cover all core index operations (create, get, update, delete, swap)

This provides appropriate test coverage for the API changes while maintaining a clean, focused test structure.


🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

♻️ Duplicate comments (1)
tests/env/node/search_example.cjs (1)

13-13: Consistency issue: Missing .waitTask() after deleteIndex()

The deletion operation should also wait for task completion like the create operation on line 14 does.

-  await client.index(indexUid).deleteIndex()
+  await client.index(indexUid).deleteIndex().waitTask()
🧹 Nitpick comments (3)
src/types/task-and-batch.ts (1)

141-147: Added generic Results type for better reusability

A new generic Results<T> type has been introduced to represent paginated results in a consistent way. This improves code reusability and standardizes the response format across different endpoints.

Consider adding a JSDoc comment for the Results<T> type to document its purpose and structure, similar to the documentation provided for other types in this file.

+/**
+ * A generic type for paginated results.
+ */
type Results<T> = {
  results: T[];
  total: number;
  limit: number;
  from: number | null;
  next: number | null;
};
tests/index.test.ts (1)

36-43: Consider testing the timestamp fields more explicitly.

While the current destructuring approach works, consider adding explicit type checks for the timestamp fields to ensure they're properly formatted ISO strings or Date objects. This would provide more complete test coverage of the API response structure.

  const { createdAt, updatedAt, ...myIndex } = await index.getIndex();

  assert.deepEqual(myIndex, {
    primaryKey,
    uid: INDEX_UID_ONE,
  });
  assert.typeOf(createdAt, "string");
  assert.typeOf(updatedAt, "string");
+  assert.match(createdAt, /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?Z$/);
+  assert.match(updatedAt, /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?Z$/);
src/meilisearch.ts (1)

102-108: Keep endpoint paths consistent & validate input for swapIndexes

  1. Other endpoints (indexes, dumps, snapshots, …) omit a leading /.
    Staying consistent simplifies any future refactors in the URL builder.

  2. A quick guard against an empty array (or malformed payloads) shields the server from pointless calls and provides immediate feedback.

-  swapIndexes(swapIndexesPayloads: SwapIndexesPayload[]): EnqueuedTaskPromise {
-    return this.#httpRequestsWithTask.post({
-      path: "/swap-indexes",
-      body: swapIndexesPayloads,
-    });
+  swapIndexes(swapIndexesPayloads: SwapIndexesPayload[]): EnqueuedTaskPromise {
+    if (!Array.isArray(swapIndexesPayloads) || swapIndexesPayloads.length === 0) {
+      throw new Error("swapIndexes payload must contain at least one item.")
+    }
+    return this.#httpRequestsWithTask.post({
+      path: "swap-indexes", // remove leading slash for consistency
+      body: swapIndexesPayloads,
+    })
   }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
Cache: Disabled due to data retention organization setting
Knowledge Base: Disabled due to data retention organization setting

📥 Commits

Reviewing files that changed from the base of the PR and between 438da05 and 7437efe.

📒 Files selected for processing (41)
  • .code-samples.meilisearch.yaml (2 hunks)
  • README.md (2 hunks)
  • playgrounds/javascript/src/meilisearch.ts (1 hunks)
  • src/indexes.ts (82 hunks)
  • src/meilisearch.ts (2 hunks)
  • src/types/index.ts (1 hunks)
  • src/types/indexes.ts (1 hunks)
  • src/types/shared.ts (1 hunks)
  • src/types/task-and-batch.ts (4 hunks)
  • src/types/types.ts (1 hunks)
  • tests/batch.test.ts (2 hunks)
  • tests/client.test.ts (3 hunks)
  • tests/displayed_attributes.test.ts (2 hunks)
  • tests/documents.test.ts (8 hunks)
  • tests/embedders.test.ts (1 hunks)
  • tests/env/browser/index.html (2 hunks)
  • tests/env/express/public/headers.html (2 hunks)
  • tests/env/express/public/index.html (2 hunks)
  • tests/env/node/search_example.cjs (1 hunks)
  • tests/env/typescript-browser/src/index.ts (2 hunks)
  • tests/env/typescript-node/src/index.ts (3 hunks)
  • tests/facet_search.test.ts (1 hunks)
  • tests/facet_search_settings.test.ts (2 hunks)
  • tests/faceting.test.ts (3 hunks)
  • tests/filterable_attributes.test.ts (2 hunks)
  • tests/get_search.test.ts (2 hunks)
  • tests/index-stats.test.ts (1 hunks)
  • tests/index.test.ts (1 hunks)
  • tests/keys.test.ts (1 hunks)
  • tests/localized_attributes.test.ts (2 hunks)
  • tests/pagination.test.ts (2 hunks)
  • tests/prefix_search_settings.test.ts (2 hunks)
  • tests/search.test.ts (7 hunks)
  • tests/search_cutoff_ms.test.ts (2 hunks)
  • tests/searchable_attributes.test.ts (2 hunks)
  • tests/sortable_attributes.test.ts (3 hunks)
  • tests/task.test.ts (2 hunks)
  • tests/token.test.ts (1 hunks)
  • tests/typed_search.test.ts (3 hunks)
  • tests/utils/meilisearch-test-utils.ts (3 hunks)
  • tests/wait_for_task.test.ts (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (12)
tests/faceting.test.ts (1)
src/meilisearch.ts (1)
  • index (82-84)
playgrounds/javascript/src/meilisearch.ts (1)
tests/env/esm/src/index.js (1)
  • client (4-4)
tests/env/typescript-browser/src/index.ts (2)
tests/env/esm/src/index.js (1)
  • client (4-4)
src/meilisearch.ts (1)
  • index (82-84)
tests/facet_search.test.ts (1)
src/meilisearch.ts (1)
  • index (82-84)
tests/task.test.ts (2)
tests/env/esm/src/index.js (1)
  • client (4-4)
src/meilisearch.ts (1)
  • index (82-84)
tests/token.test.ts (1)
tests/env/esm/src/index.js (1)
  • client (4-4)
tests/sortable_attributes.test.ts (1)
src/meilisearch.ts (1)
  • index (82-84)
tests/env/typescript-node/src/index.ts (2)
tests/env/esm/src/index.js (1)
  • client (4-4)
src/meilisearch.ts (1)
  • index (82-84)
src/types/task-and-batch.ts (2)
src/types/indexes.ts (1)
  • SwapIndexesPayload (47-47)
src/http-requests.ts (1)
  • T (199-264)
tests/index-stats.test.ts (2)
tests/utils/meilisearch-test-utils.ts (2)
  • getClient (262-262)
  • assert (135-138)
src/meilisearch.ts (1)
  • index (82-84)
src/types/indexes.ts (1)
src/types/shared.ts (1)
  • PaginationView (4-9)
src/meilisearch.ts (5)
src/http-requests.ts (1)
  • T (199-264)
src/types/types.ts (1)
  • RecordAny (10-10)
src/indexes.ts (1)
  • Index (61-1316)
src/types/indexes.ts (4)
  • ListIndexes (8-11)
  • IndexViewList (26-26)
  • IndexCreateRequest (40-40)
  • SwapIndexesPayload (47-47)
src/types/task-and-batch.ts (1)
  • EnqueuedTaskPromise (133-139)
🔇 Additional comments (106)
tests/token.test.ts (1)

86-86: API usage updated correctly for index deletion.

The code now properly uses the new deleteIndex() method instead of the old delete() method, and correctly awaits the task completion with waitTask(). This aligns with the broader API refactoring to standardize index manipulation methods.

tests/search_cutoff_ms.test.ts (2)

104-104: Index creation API updated correctly.

The code now uses the object parameter format { uid: index.uid } instead of passing the UID string directly, aligning with the renamed IndexCreateRequest type mentioned in the PR objectives.


135-135: Index creation API updated correctly.

The code now uses the object parameter format { uid: index.uid } instead of passing the UID string directly, aligning with the renamed IndexCreateRequest type mentioned in the PR objectives.

tests/sortable_attributes.test.ts (3)

32-32: Index creation API updated correctly.

The code now uses the object parameter format { uid: index.uid } instead of passing the UID string directly, aligning with the renamed IndexCreateRequest type mentioned in the PR objectives.


82-82: Index creation API updated correctly.

The code now uses the object parameter format { uid: index.uid } instead of passing the UID string directly, aligning with the renamed IndexCreateRequest type mentioned in the PR objectives.


113-113: Index creation API updated correctly.

The code now uses the object parameter format { uid: index.uid } instead of passing the UID string directly, aligning with the renamed IndexCreateRequest type mentioned in the PR objectives.

tests/prefix_search_settings.test.ts (2)

62-62: Proper update to createIndex API

The code correctly uses the new object parameter format for the createIndex method, which is part of the API refactoring to better align with the MeiliSearch Rust source code model.


94-94: Properly implemented createIndex API update

The change correctly implements the new signature format for createIndex, passing an object with a uid property instead of a string parameter.

tests/batch.test.ts (2)

8-8: Good direct object declaration for index

The simplification of declaring the index as an object literal follows good JavaScript practices and prepares it to be directly passed to the createIndex method.


19-19: Correctly uses object parameter for createIndex

The update properly passes the index object to createIndex, aligning with the API refactoring to standardize index creation methods.

tests/keys.test.ts (1)

139-139: API-compliant index creation

The createIndex call correctly implements the new object parameter format, aligning with the standardized index management API refactoring.

tests/filterable_attributes.test.ts (2)

93-93: Proper update to createIndex method signature

This change correctly implements the new object parameter format for createIndex, consistent with the API standardization across the codebase.


124-124: Consistent implementation of createIndex API

The update correctly uses the object parameter format for index creation, maintaining consistency with the refactored API design.

tests/searchable_attributes.test.ts (2)

81-81: Correctly updated to use object parameter for index creation.

The method call has been updated to use the new API signature where createIndex expects an object parameter with a uid property, instead of a direct string UID. This aligns with the refactored index management API.


112-112: Correctly updated to use object parameter for index creation.

The method call has been updated to use the new API signature where createIndex expects an object parameter with a uid property, instead of a direct string UID. This aligns with the refactored index management API.

tests/pagination.test.ts (2)

87-87: Correctly updated to use object parameter for index creation.

The method call has been updated to use the new API signature where createIndex expects an object parameter with a uid property, instead of a direct string UID. This aligns with the refactored index management API.


118-118: Correctly updated to use object parameter for index creation.

The method call has been updated to use the new API signature where createIndex expects an object parameter with a uid property, instead of a direct string UID. This aligns with the refactored index management API.

tests/faceting.test.ts (3)

33-33: Correctly updated to use object parameter for index creation.

The method call has been updated to use the new API signature where createIndex expects an object parameter with a uid property, instead of a direct string UID. This aligns with the refactored index management API.


92-92: Correctly updated to use object parameter for index creation.

The method call has been updated to use the new API signature where createIndex expects an object parameter with a uid property, instead of a direct string UID. This aligns with the refactored index management API.


121-121: Correctly updated to use object parameter for index creation.

The method call has been updated to use the new API signature where createIndex expects an object parameter with a uid property, instead of a direct string UID. This aligns with the refactored index management API.

tests/wait_for_task.test.ts (1)

22-22: Correctly updated to use object parameter for index creation.

The method call has been updated to use the new API signature where createIndex expects an object parameter with a uid property, instead of a direct string UID. This aligns with the refactored index management API.

tests/env/node/search_example.cjs (1)

14-14: LGTM: Properly updated to new API format

The createIndex call has been correctly updated to use the new object parameter format, and it properly chains waitTask() for task completion.

tests/localized_attributes.test.ts (2)

111-111: LGTM: Properly updated to new API format

The createIndex call has been correctly updated to use the new object parameter format with the uid property, and it properly chains waitTask() for task completion.


142-142: LGTM: Properly updated to new API format

The createIndex call has been correctly updated to use the new object parameter format with the uid property, and it properly chains waitTask() for task completion.

tests/search.test.ts (7)

129-130: LGTM: Properly updated to new API format

The createIndex calls have been correctly updated to use the new object parameter format with the uid property. In this case, waitTask() isn't chained since it's not needed for the specific test scenario.


295-295: LGTM: Properly updated to new API format

The createIndex call has been correctly updated to use the new object parameter format with the uid property.


373-373: LGTM: Properly updated to new API format

The createIndex call has been correctly updated to use the new object parameter format with the uid property.


1250-1250: LGTM: Properly updated method name

The index deletion method has been correctly renamed from delete() to deleteIndex() to better reflect its purpose, following the API changes outlined in the PR.


1263-1263: LGTM: Properly updated to new API format

The createIndex call has been correctly updated to use the new object parameter format with the uid property, and it properly chains waitTask() for task completion.


1292-1292: LGTM: Properly updated to new API format

The createIndex call has been correctly updated to use the new object parameter format with the uid property.


1366-1366: LGTM: Properly updated to new API format

The createIndex call has been correctly updated to use the new object parameter format with the uid property, and it properly chains waitTask() for task completion.

tests/embedders.test.ts (1)

61-61: LGTM: Properly updated to new API format

The createIndex call has been correctly updated to use the new object parameter format with the uid property, and it properly chains waitTask() for task completion.

tests/typed_search.test.ts (3)

116-117: API signature update for createIndex

The code has been updated to use the new index creation API which now accepts an object with uid property instead of a string parameter. This aligns with the objective to standardize index-related methods across the codebase.


396-396: Index deletion method renamed for improved consistency

Changed from using .delete() to .deleteIndex() on the index instance. This provides a clearer API by explicitly stating the operation being performed.


410-410: API signature update for createIndex

Updated to use the new object-based parameter style with the uid property, consistent with other index creation calls in the file.

tests/task.test.ts (2)

34-34: API signature update for createIndex

Modified to use the new object parameter format with a uid property instead of passing the index UID as a string. This change aligns with the refactored index API.


95-95: API signature update for createIndex

Updated index creation call to use the object parameter format with uid property, consistent with the changes throughout the codebase.

tests/displayed_attributes.test.ts (2)

77-77: API signature update for createIndex

Changed index creation to use the new object parameter format with a uid property for the "Search" permission test suite, consistent with the updated API.


109-109: API signature update for createIndex

Updated index creation call for the "No" permission test suite to use the new object parameter format, maintaining consistency across the codebase.

tests/facet_search_settings.test.ts (2)

62-62: API signature update for createIndex

Changed index creation to use the new object parameter format with a uid property for the "Search" permission test suite, consistent with the refactored index API.


94-94: API signature update for createIndex

Updated index creation call for the "No" permission test suite to use the new object parameter format, maintaining consistency across the codebase.

src/types/index.ts (1)

1-2: LGTM: Updated exports to reflect new type organization.

The changes properly export the new index-related types from the dedicated module and update the path format to a consistent hyphenated style for task and batch types.

tests/env/express/public/headers.html (2)

26-26: Updated API usage with object parameter pattern.

The method call has been properly updated to match the new API signature, using an object with a uid property instead of a direct string parameter.


43-43: Updated to new index deletion API.

The index deletion method has been properly changed to use the new deleteIndex() method and includes proper task handling with waitTask().

tests/env/browser/index.html (3)

26-26: Updated index creation to use object parameter pattern.

The method call has been properly updated to match the new API signature, using an object with a uid property instead of a direct string parameter, and includes proper task handling.


30-30: Updated to use the new index information retrieval method.

The method to retrieve index information has been properly updated from the deprecated getRawInfo() to the new getIndex() method, aligning with the API changes.


44-44: Updated to new index deletion API.

The index deletion method has been properly changed to use the new deleteIndex() method name and includes proper task handling with waitTask().

src/types/types.ts (2)

7-7: LGTM: Updated import path to consistent format.

The import path for WaitOptions has been updated to use the hyphenated format, ensuring consistency across the codebase.


1-1108:

✅ Verification successful

Verify that index-related types have been moved to the new dedicated module.

The import path has been updated, but I notice that the PR objectives mentioned removing several index-related types (like IndexOptions, IndexObject, etc.) from this file and moving them to a dedicated module. Let's verify that these types are properly defined in the new module.


🏁 Script executed:

#!/bin/bash
# Description: Verify that index-related types have been moved from types.ts to the dedicated indexes.ts file.

# Check that the indexes.ts file exists and contains the expected types
echo "Checking that the indexes.ts file exists and contains the expected types:"
grep -e "IndexView" -e "IndexViewList" -e "ListIndexes" -e "UpdateIndexRequest" -e "IndexCreateRequest" src/types/indexes.ts

# Verify that no references to old types remain in the codebase
echo "Verifying that no references to old types remain in the codebase:"
rg "IndexOptions|IndexObject|IndexesQuery|IndexesResults" --type ts

Length of output: 949


Index-related types have been moved to src/types/indexes.ts

  • Confirmed ListIndexes, IndexView, IndexViewList, UpdateIndexRequest, and IndexCreateRequest are defined in src/types/indexes.ts.
  • No remaining references to the old types (IndexOptions, IndexObject, IndexesQuery, IndexesResults) were found in the codebase.

No further action required.

tests/utils/meilisearch-test-utils.ts (4)

3-3: Added Task type import to support new task validation functionality.

The Task type import is now included alongside Config to support the new isTaskSuccessful assertion helper.


82-82: Updated to use new index API method name.

The method call has been updated from getRawIndexes() to getIndexes() to align with the refactored API structure described in the PR objectives.


86-86: Updated index deletion to use the new method name.

The index deletion operation now uses deleteIndex() instead of delete(), reflecting the standardized naming convention in the refactored API.


130-133: Added helpful task status validation utility.

The new isTaskSuccessful helper method provides a convenient way to assert that a task has completed successfully, checking both for null error and a "succeeded" status.

tests/get_search.test.ts (2)

87-88: Updated index creation to use new object parameter signature.

The createIndex method calls now use an object with a uid property instead of a direct string parameter, aligning with the refactored API structure.


549-549: Updated index deletion to use the new method name.

The index deletion operation now uses deleteIndex() instead of delete(), reflecting the standardized naming convention in the refactored API.

tests/env/express/public/index.html (3)

29-29: Updated index creation to use new object parameter signature.

The createIndex method call now uses an object with a uid property instead of a direct string parameter, aligning with the refactored API structure.


33-33: Updated to use new index information retrieval method.

The method call has been updated from getRawInfo() to getIndex() to align with the refactored API structure described in the PR objectives.


51-51: Updated index deletion to use the new method name.

The index deletion operation now uses deleteIndex() instead of delete(), reflecting the standardized naming convention in the refactored API.

tests/env/typescript-browser/src/index.ts (3)

1-1: Simplified imports by removing unnecessary type.

Removed the explicit import of IndexObject type, which has been renamed to IndexView according to the PR objectives.


17-17: Updated to use new index listing method.

The method call has been updated from getRawIndexes() to getIndexes() to align with the refactored API structure described in the PR objectives.


19-19: Removed explicit type annotation in mapping function.

The type annotation for the index parameter in the mapping function has been removed, as it previously referenced the now-renamed IndexObject type.

playgrounds/javascript/src/meilisearch.ts (2)

13-13: Updated index deletion to use new API pattern

The code now uses the more explicit chain client.index(indexUid).deleteIndex().waitTask() instead of the deprecated deleteIndexIfExists(indexUid) method. This change aligns with the PR objective of removing index manipulation methods that don't directly take an index UID parameter.


15-15: Updated index creation to use object parameter

The code now uses createIndex({ uid: indexUid }) instead of passing the UID directly as a string parameter. This change follows the new API convention that standardizes method signatures using object parameters, as described in the PR objectives.

tests/documents.test.ts (7)

35-35: Updated index creation to use object parameter

The code now uses createIndex({ uid: indexNoPk.uid }) instead of passing the UID directly as a string parameter, aligning with the updated API.


37-39: Updated index creation with primaryKey to use object parameter

The code now uses an object with uid and primaryKey properties for index creation, following the standardized API pattern outlined in the PR objectives.


414-414: Updated method to get index information

Changed from using the deprecated method fetchInfo() to the new getIndex() method, which follows the refactored API design.


427-427: Updated method to get index information

Changed from using the deprecated method fetchInfo() to the new getIndex() method, which follows the refactored API design.


443-443: Updated method to get index information

Changed from using the deprecated method fetchInfo() to the new getIndex() method, which follows the refactored API design.


461-461: Updated method to get index information

Changed from using the deprecated method fetchInfo() to the new getIndex() method, which follows the refactored API design.


563-563: Updated index creation to use object parameter

The code now uses createIndex({ uid: indexPk.uid }) instead of passing the UID directly as a string parameter, maintaining consistency with the updated API.

src/types/shared.ts (2)

3-4: Renamed and documented type to align with Rust implementation

Renamed CursorResults<T> to PaginationView<T> and added a JSDoc reference to the corresponding Rust type meilisearch::routes::PaginationView. This change directly aligns with the PR objective of refactoring types to match the Rust source code model.


5-7: Updated pagination properties

Changed pagination properties by replacing from and next with an offset: number property. This modification is part of the standardization effort to more closely match the Rust implementation's pagination model.

tests/index-stats.test.ts (2)

8-11: Using the new deleteIndex API in test cleanup

The test correctly uses the new API pattern ms.index(INDEX_UID).deleteIndex().waitTask() for index deletion in the cleanup code, consistent with the refactored index API.


13-40: Well-structured test for index statistics

This test properly validates the getStats method on an index, including verification of important statistics like document count, field distribution, and database size. The test follows good practices by:

  1. Setting up test data with unique fields
  2. Waiting for and verifying task completion
  3. Making specific assertions about the returned statistics

The implementation aligns with the overall API refactoring objectives of the PR.

tests/env/typescript-node/src/index.ts (4)

30-31: API usage updated to follow new pattern for index operations

The code now correctly uses the new index manipulation pattern where:

  1. Index-specific operations are performed on an index instance obtained via client.index(indexUid)
  2. Index creation now accepts an object parameter with a uid property

These changes align with the PR's objective to refactor index handling to match the MeiliSearch Rust source code model.


34-38: Method renamed from getRawIndexes to getIndexes

The code now uses the renamed getIndexes() method instead of the deprecated getRawIndexes(), correctly implementing the migration described in the PR objectives.


46-46: Simplified index mapping operation

The code properly uses the results directly without needing to specify the return type, which is consistent with the removal of IndexObject type in favor of IndexView.


65-65: Consistent use of new index deletion pattern

The code correctly uses the refactored pattern for deleting an index, which aligns with the PR's goal of removing index manipulation methods from the MeiliSearch class that don't directly take an index UID parameter.

.code-samples.meilisearch.yaml (6)

27-27: Updated method name from getRawInfo to getIndex

The code sample correctly uses the renamed getIndex() method instead of the deprecated getRawInfo(), which aligns with the API changes outlined in the PR migration guide.


31-31: Updated index creation to use object parameter

The code sample now properly uses an object parameter with uid and primaryKey properties instead of passing them as separate arguments, reflecting the standardized method signature.


33-33: Updated index update method to use index instance

The code correctly uses the new pattern where index-specific operations are performed on an index instance, and the method name has been updated to updateIndex.


35-35: Updated index deletion to use index instance

The code sample now uses the index instance method deleteIndex() instead of the client-level method, which is consistent with the overall refactoring approach.


405-407: Consistent usage of updated index instance method

The code example correctly uses the index instance and the renamed updateIndex method with an object parameter, maintaining consistency with other similar operations.


409-409: Consistent index creation with object parameter

This code sample maintains consistency with the updated index creation approach using an object with uid and primaryKey properties.

src/types/task-and-batch.ts (4)

1-2: Updated imports with cleaner structure

The imports now correctly use the new types structure, importing SwapIndexesPayload from "./indexes.js" instead of using a locally defined type. This aligns with the PR's goal of refactoring index types to match the Rust source code model.


110-110: Updated type reference for swaps property

The swaps property now correctly uses the imported SwapIndexesPayload[] type instead of the old IndexSwap[] type, ensuring consistency with the new type system.


154-154: Simplified TasksResults type definition

The TasksResults type now correctly uses the new generic Results<Task> type, simplifying the type definition and ensuring consistency with other similar types.


200-200: Simplified BatchesResults type definition

Similar to TasksResults, the BatchesResults type now uses the generic Results<Batch> type, maintaining consistency in how paginated results are typed throughout the codebase.

tests/client.test.ts (4)

11-11: Simplified imports by removing unused index-related types

The imports have been properly updated to remove index-related types that are no longer used in this file after the removal of index management tests.


244-244: Updated index creation to use object parameter

The test correctly uses the new index creation pattern with an object parameter { uid: "test" } instead of a string.


265-265: Consistent usage of updated index creation pattern

This test also correctly uses the new index creation pattern with an object parameter, maintaining consistency throughout the test file.


271-271: Updated to use new index access pattern

The test now correctly uses client.index("test") to get an index instance rather than the deprecated client.getIndex("test") method, aligning with the new API design.

src/types/indexes.ts (1)

1-48: Well-organized type definitions with clear documentation links.

The new type definitions are well-structured and properly documented with links to the Meilisearch API documentation and references to the corresponding Rust implementation. The types align well with the PR's objective of better matching the Rust source code model.

Each type has a clear purpose:

  • ListIndexes for pagination parameters
  • IndexView replaces the previous IndexObject
  • IndexViewList for paginated results
  • UpdateIndexRequest and IndexCreateRequest for mutation operations
  • SwapIndexesPayload for index swapping operations

The types are properly exported and have well-defined properties with correct types.

tests/index.test.ts (1)

1-100: Tests appropriately updated to match the new API.

The test suite has been effectively simplified to focus on core index lifecycle operations, using a consistent pattern for testing creation, retrieval, updating, deletion, and swapping of indexes. The tests properly use the new method signatures and patterns, such as:

  • ms.createIndex({ uid }) instead of the old signature
  • index.getIndex() replacing the deprecated getRawInfo()
  • index.updateIndex() and index.deleteIndex() methods

The cleanup in afterAll is a good practice to ensure tests don't leave artifacts behind.

src/indexes.ts (6)

61-65: Good encapsulation of the uid property.

Converting the uid from a public property to a private field with a getter improves encapsulation and prevents accidental mutation. This is a good practice to ensure the integrity of the index identity.


76-78: Constructor simplified correctly.

The constructor has been simplified by removing the optional primaryKey parameter, which is appropriate since index properties are now fetched via the getIndex() method rather than being stored in the instance.


194-197: Well-defined replacement for getRawInfo().

The new getIndex() method provides a cleaner API for fetching index information. The method is properly documented with a link to the Meilisearch API documentation and returns the new IndexView type.


199-205: Method renaming improves clarity.

Renaming update to updateIndex makes the method's purpose more explicit and consistent with other method names. The parameter type has been updated to use the new UpdateIndexRequest type, which aligns with the Rust model.


207-210: Method renaming improves clarity.

Renaming delete to deleteIndex makes the method's purpose more explicit and consistent with other method names. This change helps avoid confusion with JavaScript's built-in delete operator.


1-1316: All API paths updated consistently.

All HTTP request paths have been updated to use the private #uid field, ensuring consistent encapsulation throughout the codebase. This is a comprehensive change that touches all methods in the class.

README.md (5)

598-598: Updated method signature aligns with code changes.

The getIndexes method signature has been updated to use the new ListIndexes type and return IndexViewList, matching the implementation changes.


605-605: Updated method signature aligns with code changes.

The createIndex method signature has been updated to accept an IndexCreateRequest object, correctly reflecting the new implementation that uses object parameters instead of separate arguments.


617-617: Updated API reference for index retrieval.

The method for getting index information has been correctly updated to use getIndex() returning an IndexView, replacing the previous getRawIndex.


623-623: Updated method signature for updateIndex.

The method signature for updating an index has been correctly updated to use updateIndex with an optional UpdateIndexRequest parameter.


629-629: Updated method signature for deleteIndex.

The method signature for deleting an index has been correctly updated to use deleteIndex, replacing the previous delete method.

src/meilisearch.ts (1)

94-100: Add a quick client-side check for the uid field before firing the request

createIndex blindly forwards the payload to the HTTP layer.
Fail-fast validation keeps the error surface closer to the caller and avoids an unnecessary network round-trip (saves latency & bandwidth and produces clearer stack traces).

   createIndex(indexCreateRequest: IndexCreateRequest): EnqueuedTaskPromise {
+    if (!indexCreateRequest?.uid) {
+      throw new Error(
+        "Index creation payload must include a non-empty `uid` property."
+      )
+    }
     return this.#httpRequestsWithTask.post({
       path: "indexes",
       body: indexCreateRequest,
     })
   }

[ suggest_optional_refactor ]

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🔭 Outside diff range comments (1)
src/meilisearch.ts (1)

1-377: 💡 Verification agent

🧩 Analysis chain

Verify that removed methods are correctly documented in migration guide

The PR objectives mention several removed methods (getIndex, getRawIndex, getRawIndexes, updateIndex, deleteIndex, deleteIndexIfExists). These removals align with the PR's goal of simplifying the API and removing redundancy.


🏁 Script executed:

#!/bin/bash
# Check if removed methods are properly documented in migration guide

# Look for migration guide files
echo "Looking for migration guide files:"
fd --type file migration_guide -x echo "Found: {}"

# Check if the migration guide contains the removed method names
echo "\nChecking if removed methods are documented in migration guides:"
methods=("getIndex" "getRawIndex" "getRawIndexes" "updateIndex" "deleteIndex" "deleteIndexIfExists")
for method in "${methods[@]}"; do
  echo "\nSearching for documentation of removed method: $method"
  rg "$method" --context 2 --glob "*.md"
done

# Also check if README or other documentation was updated
echo "\nChecking if README or other documentation was updated:"
rg -i "migration|api changes|breaking change" --glob "*.md" --context 2

Length of output: 2367


Add a migration guide and update outdated docs

It looks like there isn’t a dedicated migration guide in the repo, and the README still shows calls to methods that were removed (getIndex, updateIndex, deleteIndex, etc.). We need to:

  • Create a MIGRATION.md (or similar) detailing the removal of:
    • getIndex → use client.index(uid).getRawInfo() / getStats()
    • getRawIndex / getRawIndexes
    • updateIndex → use client.index(uid).update()
    • deleteIndex → use client.index(uid).delete()
    • deleteIndexIfExists → use client.index(uid).deleteIfExists()
  • In README.md, remove or replace these outdated examples:
    client.index(uid: string).getIndex(): Promise<IndexView>
    client.index(uid: string).updateIndex(...): EnqueuedTaskPromise
    client.index(uid: string).deleteIndex(): EnqueuedTaskPromise
  • Reference the migration guide in README to help users upgrade.

Please add this documentation before merging.

🧹 Nitpick comments (1)
src/meilisearch.ts (1)

95-101: Improved index creation API

The createIndex method now accepts a single IndexCreateRequest object parameter instead of separate parameters, which follows modern API design patterns and provides better extensibility.

Consider adding a code sample in the JSDoc to demonstrate how to use this method with the new parameter structure.

 /** {@link https://www.meilisearch.com/docs/reference/api/indexes#create-an-index} */
 createIndex(indexCreateRequest: IndexCreateRequest): EnqueuedTaskPromise {
+  /**
+   * @example
+   * ```ts
+   * // Create an index with only a UID
+   * client.createIndex({ uid: 'movies' });
+   * 
+   * // Create an index with UID and primaryKey
+   * client.createIndex({ uid: 'movies', primaryKey: 'movie_id' });
+   * ```
+   */
   return this.#httpRequestsWithTask.post({
     path: "indexes",
     body: indexCreateRequest,
   });
 }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Lite
Cache: Disabled due to data retention organization setting
Knowledge Base: Disabled due to data retention organization setting

📥 Commits

Reviewing files that changed from the base of the PR and between 4219bd3 and db83046.

📒 Files selected for processing (5)
  • src/meilisearch.ts (2 hunks)
  • src/types/index.ts (1 hunks)
  • tests/documents.test.ts (8 hunks)
  • tests/embedders.test.ts (1 hunks)
  • tests/search.test.ts (7 hunks)
✅ Files skipped from review due to trivial changes (2)
  • tests/search.test.ts
  • tests/documents.test.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • tests/embedders.test.ts
  • src/types/index.ts
🔇 Additional comments (4)
src/meilisearch.ts (4)

19-19: Types renamed for improved consistency

The type renames align with the PR objective to make index-related types match the MeiliSearch Rust source code model, improving consistency across the codebase.

Also applies to: 27-29


78-81: Documentation updated to reflect refactored index API

The updated JSDoc comments correctly describe the index method's purpose and return value, which is part of the new API structure.


87-93: Simplified index listing implementation

The getIndexes method has been properly refactored to return raw index data (IndexViewList) directly from the API rather than transforming results into Index instances. This aligns with the goal of separating index details from index instances.


104-108: Updated type for swapIndexes method

The swapIndexesPayload parameter type has been correctly updated to match the renamed type, maintaining consistency with other renamed types in this PR.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
breaking-change The related changes are breaking for the users
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants