diff --git a/.code-samples.meilisearch.yaml b/.code-samples.meilisearch.yaml index 5d4788ece..8f3050846 100644 --- a/.code-samples.meilisearch.yaml +++ b/.code-samples.meilisearch.yaml @@ -24,15 +24,15 @@ date_guide_sort_1: |- sort: ['release_timestamp:desc'], }) get_one_index_1: |- - client.index('movies').getRawInfo() + client.index('movies').getIndex() list_all_indexes_1: |- client.getIndexes({ limit: 3 }) create_an_index_1: |- - client.createIndex('movies', { primaryKey: 'id' }) + client.createIndex({ uid: 'movies', primaryKey: 'id' }) update_an_index_1: |- - client.updateIndex('movies', { primaryKey: 'id' }) + client.index('movies').updateIndex({ primaryKey: 'id' }) delete_an_index_1: |- - client.deleteIndex('movies') + client.index('movies').deleteIndex() swap_indexes_1: |- client.swapIndexes([ { 'indexes': ['indexA', 'indexB'] }, @@ -402,11 +402,11 @@ add_movies_json_1: |- const movies = require('./movies.json') client.index('movies').addDocuments(movies).then((res) => console.log(res)) primary_field_guide_update_document_primary_key: |- - client.updateIndex('books', { + client.index('books').updateIndex({ primaryKey: 'title' }) primary_field_guide_create_index_primary_key: |- - client.createIndex('books', { primaryKey: 'reference_number' }) + client.createIndex({ uid: 'books', primaryKey: 'reference_number' }) primary_field_guide_add_document_primary_key: |- client.index('books').addDocuments([ { diff --git a/README.md b/README.md index 3d5e3441f..ffb8caa71 100644 --- a/README.md +++ b/README.md @@ -592,23 +592,17 @@ client.getBatches(parameters: BatchesQuery = {}): Promise ### Indexes -#### [Get all indexes in Index instances](https://www.meilisearch.com/docs/reference/api/indexes#list-all-indexes) - -```ts -client.getIndexes(parameters: IndexesQuery): Promise> -``` - #### [Get all indexes](https://www.meilisearch.com/docs/reference/api/indexes#list-all-indexes) ```ts -client.getRawIndexes(parameters: IndexesQuery): Promise> +client.getIndexes(listIndexes?: ListIndexes): Promise ``` #### [Create a new index](https://www.meilisearch.com/docs/reference/api/indexes#create-an-index) ```ts -client.createIndex(uid: string, options?: IndexOptions): Promise +client.createIndex(indexCreateRequest: IndexCreateRequest): EnqueuedTaskPromise ``` #### Create a local reference to an index @@ -617,48 +611,22 @@ client.createIndex(uid: string, options?: IndexOptions): Promise(uid: string): Index ``` -#### [Get an index instance completed with information fetched from Meilisearch](https://www.meilisearch.com/docs/reference/api/indexes#get-one-index) - -```ts -client.getIndex(uid: string): Promise> -``` - #### [Get the raw index JSON response from Meilisearch](https://www.meilisearch.com/docs/reference/api/indexes#get-one-index) ```ts -client.getRawIndex(uid: string): Promise -``` - -#### [Get an object with information about the index](https://www.meilisearch.com/docs/reference/api/indexes#get-one-index) - -```ts -client.index('myIndex').getRawInfo(): Promise +client.index(uid: string).getIndex(): Promise ``` #### [Update Index](https://www.meilisearch.com/docs/reference/api/indexes#update-an-index) -##### Using the client - -```ts -client.updateIndex(uid: string, options: IndexOptions): Promise -``` - -##### Using the index object - ```ts -client.index('myIndex').update(data: IndexOptions): Promise +client.index(uid: string).updateIndex(updateIndexRequest?: UpdateIndexRequest): EnqueuedTaskPromise ``` #### [Delete index](https://www.meilisearch.com/docs/reference/api/indexes#delete-an-index) -##### Using the client ```ts -client.deleteIndex(uid): Promise -``` - -##### Using the index object -```ts -client.index('myIndex').delete(): Promise +client.index(uid: string).deleteIndex(): EnqueuedTaskPromise ``` #### [Get specific index stats](https://www.meilisearch.com/docs/reference/api/stats#get-stats-of-an-index) @@ -667,18 +635,6 @@ client.index('myIndex').delete(): Promise client.index('myIndex').getStats(): Promise ``` -##### Return Index instance with updated information - -```ts -client.index('myIndex').fetchInfo(): Promise -``` - -##### Get Primary Key of an Index - -```ts -client.index('myIndex').fetchPrimaryKey(): Promise -``` - ##### Swap two indexes ```ts diff --git a/playgrounds/javascript/src/meilisearch.ts b/playgrounds/javascript/src/meilisearch.ts index 0f1818486..4af579f61 100644 --- a/playgrounds/javascript/src/meilisearch.ts +++ b/playgrounds/javascript/src/meilisearch.ts @@ -10,9 +10,9 @@ const index = client.index<{ id: number; title: string; genres: string[] }>( ); export async function addDocuments(): Promise { - await client.deleteIndexIfExists(indexUid); + await client.index(indexUid).deleteIndex().waitTask(); - await client.createIndex(indexUid).waitTask(); + await client.createIndex({ uid: indexUid }).waitTask(); await index .addDocuments([ diff --git a/src/indexes.ts b/src/indexes.ts index a3cc3f020..457174921 100644 --- a/src/indexes.ts +++ b/src/indexes.ts @@ -12,8 +12,6 @@ import type { SearchParams, Filter, SearchRequestGET, - IndexObject, - IndexOptions, IndexStats, DocumentsQuery, DocumentQuery, @@ -50,6 +48,8 @@ import type { PrefixSearch, RecordAny, EnqueuedTaskPromise, + IndexView, + UpdateIndexRequest, } from "./types/index.js"; import { HttpRequests } from "./http-requests.js"; import { @@ -59,10 +59,11 @@ import { } from "./task.js"; export class Index { - uid: string; - primaryKey: string | undefined; - createdAt: Date | undefined; - updatedAt: Date | undefined; + readonly #uid: string; + get uid() { + return this.#uid; + } + httpRequest: HttpRequests; tasks: TaskClient; readonly #httpRequestsWithTask: HttpRequestsWithEnqueuedTaskPromise; @@ -72,9 +73,8 @@ export class Index { * @param uid - UID of the index * @param primaryKey - Primary Key of the index */ - constructor(config: Config, uid: string, primaryKey?: string) { - this.uid = uid; - this.primaryKey = primaryKey; + constructor(config: Config, uid: string) { + this.#uid = uid; this.httpRequest = new HttpRequests(config); this.tasks = new TaskClient(this.httpRequest, config.defaultWaitOptions); this.#httpRequestsWithTask = getHttpRequestsWithEnqueuedTaskPromise( @@ -101,7 +101,7 @@ export class Index { extraRequestInit?: ExtraRequestInit, ): Promise> { return await this.httpRequest.post>({ - path: `indexes/${this.uid}/search`, + path: `indexes/${this.#uid}/search`, body: { q: query, ...options }, extraRequestInit, }); @@ -147,7 +147,7 @@ export class Index { }; return await this.httpRequest.get>({ - path: `indexes/${this.uid}/search`, + path: `indexes/${this.#uid}/search`, params: getParams, extraRequestInit, }); @@ -165,7 +165,7 @@ export class Index { extraRequestInit?: ExtraRequestInit, ): Promise { return await this.httpRequest.post({ - path: `indexes/${this.uid}/facet-search`, + path: `indexes/${this.#uid}/facet-search`, body: params, extraRequestInit, }); @@ -182,7 +182,7 @@ export class Index { S extends SearchParams = SearchParams, >(params: SearchSimilarDocumentsParams): Promise> { return await this.httpRequest.post>({ - path: `indexes/${this.uid}/similar`, + path: `indexes/${this.#uid}/similar`, body: params, }); } @@ -191,86 +191,22 @@ export class Index { /// INDEX /// - /** - * Get index information. - * - * @returns Promise containing index information - */ - async getRawInfo(): Promise { - const res = await this.httpRequest.get({ - path: `indexes/${this.uid}`, - }); - this.primaryKey = res.primaryKey; - this.updatedAt = new Date(res.updatedAt); - this.createdAt = new Date(res.createdAt); - return res; - } - - /** - * Fetch and update Index information. - * - * @returns Promise to the current Index object with updated information - */ - async fetchInfo(): Promise { - await this.getRawInfo(); - return this; - } - - /** - * Get Primary Key. - * - * @returns Promise containing the Primary Key of the index - */ - async fetchPrimaryKey(): Promise { - this.primaryKey = (await this.getRawInfo()).primaryKey; - return this.primaryKey; - } - - /** - * Create an index. - * - * @param uid - Unique identifier of the Index - * @param options - Index options - * @param config - Request configuration options - * @returns Newly created Index object - */ - static create( - uid: string, - options: IndexOptions = {}, - config: Config, - ): EnqueuedTaskPromise { - const httpRequests = new HttpRequests(config); - return getHttpRequestsWithEnqueuedTaskPromise( - httpRequests, - new TaskClient(httpRequests), - ).post({ - path: "indexes", - body: { ...options, uid }, - }); + /** {@link https://www.meilisearch.com/docs/reference/api/indexes#get-one-index} */ + async getIndex(): Promise { + return await this.httpRequest.get({ path: `indexes/${this.#uid}` }); } - /** - * Update an index. - * - * @param data - Data to update - * @returns Promise to the current Index object with updated information - */ - update(data?: IndexOptions): EnqueuedTaskPromise { + /** {@link https://www.meilisearch.com/docs/reference/api/indexes#update-an-index} */ + updateIndex(updateIndexRequest?: UpdateIndexRequest): EnqueuedTaskPromise { return this.#httpRequestsWithTask.patch({ - path: `indexes/${this.uid}`, - body: data, + path: `indexes/${this.#uid}`, + body: updateIndexRequest, }); } - /** - * Delete an index. - * - * @returns Promise which resolves when index is deleted successfully - */ - delete(): EnqueuedTaskPromise { - return this.#httpRequestsWithTask.delete({ - path: `indexes/${this.uid}`, - }); + /** {@link https://www.meilisearch.com/docs/reference/api/indexes#delete-an-index} */ + deleteIndex(): EnqueuedTaskPromise { + return this.#httpRequestsWithTask.delete({ path: `indexes/${this.#uid}` }); } /// @@ -284,7 +220,7 @@ export class Index { */ async getStats(): Promise { return await this.httpRequest.get({ - path: `indexes/${this.uid}/stats`, + path: `indexes/${this.#uid}/stats`, }); } @@ -302,7 +238,7 @@ export class Index { async getDocuments( params?: DocumentsQuery, ): Promise> { - const relativeBaseURL = `indexes/${this.uid}/documents`; + const relativeBaseURL = `indexes/${this.#uid}/documents`; return params?.filter !== undefined ? // In case `filter` is provided, use `POST /documents/fetch` @@ -333,7 +269,7 @@ export class Index { : undefined; return await this.httpRequest.get({ - path: `indexes/${this.uid}/documents/${documentId}`, + path: `indexes/${this.#uid}/documents/${documentId}`, params: { ...parameters, fields }, }); } @@ -347,7 +283,7 @@ export class Index { */ addDocuments(documents: T[], options?: DocumentOptions): EnqueuedTaskPromise { return this.#httpRequestsWithTask.post({ - path: `indexes/${this.uid}/documents`, + path: `indexes/${this.#uid}/documents`, params: options, body: documents, }); @@ -369,7 +305,7 @@ export class Index { queryParams?: RawDocumentAdditionOptions, ): EnqueuedTaskPromise { return this.#httpRequestsWithTask.post({ - path: `indexes/${this.uid}/documents`, + path: `indexes/${this.#uid}/documents`, body: documents, params: queryParams, contentType, @@ -412,7 +348,7 @@ export class Index { options?: DocumentOptions, ): EnqueuedTaskPromise { return this.#httpRequestsWithTask.put({ - path: `indexes/${this.uid}/documents`, + path: `indexes/${this.#uid}/documents`, params: options, body: documents, }); @@ -458,7 +394,7 @@ export class Index { queryParams?: RawDocumentAdditionOptions, ): EnqueuedTaskPromise { return this.#httpRequestsWithTask.put({ - path: `indexes/${this.uid}/documents`, + path: `indexes/${this.#uid}/documents`, body: documents, params: queryParams, contentType, @@ -473,7 +409,7 @@ export class Index { */ deleteDocument(documentId: string | number): EnqueuedTaskPromise { return this.#httpRequestsWithTask.delete({ - path: `indexes/${this.uid}/documents/${documentId}`, + path: `indexes/${this.#uid}/documents/${documentId}`, }); } @@ -499,7 +435,7 @@ export class Index { : "documents/delete-batch"; return this.#httpRequestsWithTask.post({ - path: `indexes/${this.uid}/${endpoint}`, + path: `indexes/${this.#uid}/${endpoint}`, body: params, }); } @@ -511,7 +447,7 @@ export class Index { */ deleteAllDocuments(): EnqueuedTaskPromise { return this.#httpRequestsWithTask.delete({ - path: `indexes/${this.uid}/documents`, + path: `indexes/${this.#uid}/documents`, }); } @@ -531,7 +467,7 @@ export class Index { options: UpdateDocumentsByFunctionOptions, ): EnqueuedTaskPromise { return this.#httpRequestsWithTask.post({ - path: `indexes/${this.uid}/documents/edit`, + path: `indexes/${this.#uid}/documents/edit`, body: options, }); } @@ -547,7 +483,7 @@ export class Index { */ async getSettings(): Promise { return await this.httpRequest.get({ - path: `indexes/${this.uid}/settings`, + path: `indexes/${this.#uid}/settings`, }); } @@ -559,7 +495,7 @@ export class Index { */ updateSettings(settings: Settings): EnqueuedTaskPromise { return this.#httpRequestsWithTask.patch({ - path: `indexes/${this.uid}/settings`, + path: `indexes/${this.#uid}/settings`, body: settings, }); } @@ -571,7 +507,7 @@ export class Index { */ resetSettings(): EnqueuedTaskPromise { return this.#httpRequestsWithTask.delete({ - path: `indexes/${this.uid}/settings`, + path: `indexes/${this.#uid}/settings`, }); } @@ -586,7 +522,7 @@ export class Index { */ async getPagination(): Promise { return await this.httpRequest.get({ - path: `indexes/${this.uid}/settings/pagination`, + path: `indexes/${this.#uid}/settings/pagination`, }); } @@ -598,7 +534,7 @@ export class Index { */ updatePagination(pagination: PaginationSettings): EnqueuedTaskPromise { return this.#httpRequestsWithTask.patch({ - path: `indexes/${this.uid}/settings/pagination`, + path: `indexes/${this.#uid}/settings/pagination`, body: pagination, }); } @@ -610,7 +546,7 @@ export class Index { */ resetPagination(): EnqueuedTaskPromise { return this.#httpRequestsWithTask.delete({ - path: `indexes/${this.uid}/settings/pagination`, + path: `indexes/${this.#uid}/settings/pagination`, }); } @@ -625,7 +561,7 @@ export class Index { */ async getSynonyms(): Promise> { return await this.httpRequest.get>({ - path: `indexes/${this.uid}/settings/synonyms`, + path: `indexes/${this.#uid}/settings/synonyms`, }); } @@ -637,7 +573,7 @@ export class Index { */ updateSynonyms(synonyms: Synonyms): EnqueuedTaskPromise { return this.#httpRequestsWithTask.put({ - path: `indexes/${this.uid}/settings/synonyms`, + path: `indexes/${this.#uid}/settings/synonyms`, body: synonyms, }); } @@ -649,7 +585,7 @@ export class Index { */ resetSynonyms(): EnqueuedTaskPromise { return this.#httpRequestsWithTask.delete({ - path: `indexes/${this.uid}/settings/synonyms`, + path: `indexes/${this.#uid}/settings/synonyms`, }); } @@ -664,7 +600,7 @@ export class Index { */ async getStopWords(): Promise { return await this.httpRequest.get({ - path: `indexes/${this.uid}/settings/stop-words`, + path: `indexes/${this.#uid}/settings/stop-words`, }); } @@ -676,7 +612,7 @@ export class Index { */ updateStopWords(stopWords: StopWords): EnqueuedTaskPromise { return this.#httpRequestsWithTask.put({ - path: `indexes/${this.uid}/settings/stop-words`, + path: `indexes/${this.#uid}/settings/stop-words`, body: stopWords, }); } @@ -688,7 +624,7 @@ export class Index { */ resetStopWords(): EnqueuedTaskPromise { return this.#httpRequestsWithTask.delete({ - path: `indexes/${this.uid}/settings/stop-words`, + path: `indexes/${this.#uid}/settings/stop-words`, }); } @@ -703,7 +639,7 @@ export class Index { */ async getRankingRules(): Promise { return await this.httpRequest.get({ - path: `indexes/${this.uid}/settings/ranking-rules`, + path: `indexes/${this.#uid}/settings/ranking-rules`, }); } @@ -716,7 +652,7 @@ export class Index { */ updateRankingRules(rankingRules: RankingRules): EnqueuedTaskPromise { return this.#httpRequestsWithTask.put({ - path: `indexes/${this.uid}/settings/ranking-rules`, + path: `indexes/${this.#uid}/settings/ranking-rules`, body: rankingRules, }); } @@ -728,7 +664,7 @@ export class Index { */ resetRankingRules(): EnqueuedTaskPromise { return this.#httpRequestsWithTask.delete({ - path: `indexes/${this.uid}/settings/ranking-rules`, + path: `indexes/${this.#uid}/settings/ranking-rules`, }); } @@ -743,7 +679,7 @@ export class Index { */ async getDistinctAttribute(): Promise { return await this.httpRequest.get({ - path: `indexes/${this.uid}/settings/distinct-attribute`, + path: `indexes/${this.#uid}/settings/distinct-attribute`, }); } @@ -757,7 +693,7 @@ export class Index { distinctAttribute: DistinctAttribute, ): EnqueuedTaskPromise { return this.#httpRequestsWithTask.put({ - path: `indexes/${this.uid}/settings/distinct-attribute`, + path: `indexes/${this.#uid}/settings/distinct-attribute`, body: distinctAttribute, }); } @@ -769,7 +705,7 @@ export class Index { */ resetDistinctAttribute(): EnqueuedTaskPromise { return this.#httpRequestsWithTask.delete({ - path: `indexes/${this.uid}/settings/distinct-attribute`, + path: `indexes/${this.#uid}/settings/distinct-attribute`, }); } @@ -784,7 +720,7 @@ export class Index { */ async getFilterableAttributes(): Promise { return await this.httpRequest.get({ - path: `indexes/${this.uid}/settings/filterable-attributes`, + path: `indexes/${this.#uid}/settings/filterable-attributes`, }); } @@ -799,7 +735,7 @@ export class Index { filterableAttributes: FilterableAttributes, ): EnqueuedTaskPromise { return this.#httpRequestsWithTask.put({ - path: `indexes/${this.uid}/settings/filterable-attributes`, + path: `indexes/${this.#uid}/settings/filterable-attributes`, body: filterableAttributes, }); } @@ -811,7 +747,7 @@ export class Index { */ resetFilterableAttributes(): EnqueuedTaskPromise { return this.#httpRequestsWithTask.delete({ - path: `indexes/${this.uid}/settings/filterable-attributes`, + path: `indexes/${this.#uid}/settings/filterable-attributes`, }); } @@ -826,7 +762,7 @@ export class Index { */ async getSortableAttributes(): Promise { return await this.httpRequest.get({ - path: `indexes/${this.uid}/settings/sortable-attributes`, + path: `indexes/${this.#uid}/settings/sortable-attributes`, }); } @@ -841,7 +777,7 @@ export class Index { sortableAttributes: SortableAttributes, ): EnqueuedTaskPromise { return this.#httpRequestsWithTask.put({ - path: `indexes/${this.uid}/settings/sortable-attributes`, + path: `indexes/${this.#uid}/settings/sortable-attributes`, body: sortableAttributes, }); } @@ -853,7 +789,7 @@ export class Index { */ resetSortableAttributes(): EnqueuedTaskPromise { return this.#httpRequestsWithTask.delete({ - path: `indexes/${this.uid}/settings/sortable-attributes`, + path: `indexes/${this.#uid}/settings/sortable-attributes`, }); } @@ -868,7 +804,7 @@ export class Index { */ async getSearchableAttributes(): Promise { return await this.httpRequest.get({ - path: `indexes/${this.uid}/settings/searchable-attributes`, + path: `indexes/${this.#uid}/settings/searchable-attributes`, }); } @@ -883,7 +819,7 @@ export class Index { searchableAttributes: SearchableAttributes, ): EnqueuedTaskPromise { return this.#httpRequestsWithTask.put({ - path: `indexes/${this.uid}/settings/searchable-attributes`, + path: `indexes/${this.#uid}/settings/searchable-attributes`, body: searchableAttributes, }); } @@ -895,7 +831,7 @@ export class Index { */ resetSearchableAttributes(): EnqueuedTaskPromise { return this.#httpRequestsWithTask.delete({ - path: `indexes/${this.uid}/settings/searchable-attributes`, + path: `indexes/${this.#uid}/settings/searchable-attributes`, }); } @@ -910,7 +846,7 @@ export class Index { */ async getDisplayedAttributes(): Promise { return await this.httpRequest.get({ - path: `indexes/${this.uid}/settings/displayed-attributes`, + path: `indexes/${this.#uid}/settings/displayed-attributes`, }); } @@ -925,7 +861,7 @@ export class Index { displayedAttributes: DisplayedAttributes, ): EnqueuedTaskPromise { return this.#httpRequestsWithTask.put({ - path: `indexes/${this.uid}/settings/displayed-attributes`, + path: `indexes/${this.#uid}/settings/displayed-attributes`, body: displayedAttributes, }); } @@ -937,7 +873,7 @@ export class Index { */ resetDisplayedAttributes(): EnqueuedTaskPromise { return this.#httpRequestsWithTask.delete({ - path: `indexes/${this.uid}/settings/displayed-attributes`, + path: `indexes/${this.#uid}/settings/displayed-attributes`, }); } @@ -952,7 +888,7 @@ export class Index { */ async getTypoTolerance(): Promise { return await this.httpRequest.get({ - path: `indexes/${this.uid}/settings/typo-tolerance`, + path: `indexes/${this.#uid}/settings/typo-tolerance`, }); } @@ -965,7 +901,7 @@ export class Index { */ updateTypoTolerance(typoTolerance: TypoTolerance): EnqueuedTaskPromise { return this.#httpRequestsWithTask.patch({ - path: `indexes/${this.uid}/settings/typo-tolerance`, + path: `indexes/${this.#uid}/settings/typo-tolerance`, body: typoTolerance, }); } @@ -977,7 +913,7 @@ export class Index { */ resetTypoTolerance(): EnqueuedTaskPromise { return this.#httpRequestsWithTask.delete({ - path: `indexes/${this.uid}/settings/typo-tolerance`, + path: `indexes/${this.#uid}/settings/typo-tolerance`, }); } @@ -992,7 +928,7 @@ export class Index { */ async getFaceting(): Promise { return await this.httpRequest.get({ - path: `indexes/${this.uid}/settings/faceting`, + path: `indexes/${this.#uid}/settings/faceting`, }); } @@ -1004,7 +940,7 @@ export class Index { */ updateFaceting(faceting: Faceting): EnqueuedTaskPromise { return this.#httpRequestsWithTask.patch({ - path: `indexes/${this.uid}/settings/faceting`, + path: `indexes/${this.#uid}/settings/faceting`, body: faceting, }); } @@ -1016,7 +952,7 @@ export class Index { */ resetFaceting(): EnqueuedTaskPromise { return this.#httpRequestsWithTask.delete({ - path: `indexes/${this.uid}/settings/faceting`, + path: `indexes/${this.#uid}/settings/faceting`, }); } @@ -1031,7 +967,7 @@ export class Index { */ async getSeparatorTokens(): Promise { return await this.httpRequest.get({ - path: `indexes/${this.uid}/settings/separator-tokens`, + path: `indexes/${this.#uid}/settings/separator-tokens`, }); } @@ -1043,7 +979,7 @@ export class Index { */ updateSeparatorTokens(separatorTokens: SeparatorTokens): EnqueuedTaskPromise { return this.#httpRequestsWithTask.put({ - path: `indexes/${this.uid}/settings/separator-tokens`, + path: `indexes/${this.#uid}/settings/separator-tokens`, body: separatorTokens, }); } @@ -1055,7 +991,7 @@ export class Index { */ resetSeparatorTokens(): EnqueuedTaskPromise { return this.#httpRequestsWithTask.delete({ - path: `indexes/${this.uid}/settings/separator-tokens`, + path: `indexes/${this.#uid}/settings/separator-tokens`, }); } @@ -1070,7 +1006,7 @@ export class Index { */ async getNonSeparatorTokens(): Promise { return await this.httpRequest.get({ - path: `indexes/${this.uid}/settings/non-separator-tokens`, + path: `indexes/${this.#uid}/settings/non-separator-tokens`, }); } @@ -1084,7 +1020,7 @@ export class Index { nonSeparatorTokens: NonSeparatorTokens, ): EnqueuedTaskPromise { return this.#httpRequestsWithTask.put({ - path: `indexes/${this.uid}/settings/non-separator-tokens`, + path: `indexes/${this.#uid}/settings/non-separator-tokens`, body: nonSeparatorTokens, }); } @@ -1096,7 +1032,7 @@ export class Index { */ resetNonSeparatorTokens(): EnqueuedTaskPromise { return this.#httpRequestsWithTask.delete({ - path: `indexes/${this.uid}/settings/non-separator-tokens`, + path: `indexes/${this.#uid}/settings/non-separator-tokens`, }); } @@ -1111,7 +1047,7 @@ export class Index { */ async getDictionary(): Promise { return await this.httpRequest.get({ - path: `indexes/${this.uid}/settings/dictionary`, + path: `indexes/${this.#uid}/settings/dictionary`, }); } @@ -1123,7 +1059,7 @@ export class Index { */ updateDictionary(dictionary: Dictionary): EnqueuedTaskPromise { return this.#httpRequestsWithTask.put({ - path: `indexes/${this.uid}/settings/dictionary`, + path: `indexes/${this.#uid}/settings/dictionary`, body: dictionary, }); } @@ -1135,7 +1071,7 @@ export class Index { */ resetDictionary(): EnqueuedTaskPromise { return this.#httpRequestsWithTask.delete({ - path: `indexes/${this.uid}/settings/dictionary`, + path: `indexes/${this.#uid}/settings/dictionary`, }); } @@ -1150,7 +1086,7 @@ export class Index { */ async getProximityPrecision(): Promise { return await this.httpRequest.get({ - path: `indexes/${this.uid}/settings/proximity-precision`, + path: `indexes/${this.#uid}/settings/proximity-precision`, }); } @@ -1165,7 +1101,7 @@ export class Index { proximityPrecision: ProximityPrecision, ): EnqueuedTaskPromise { return this.#httpRequestsWithTask.put({ - path: `indexes/${this.uid}/settings/proximity-precision`, + path: `indexes/${this.#uid}/settings/proximity-precision`, body: proximityPrecision, }); } @@ -1177,7 +1113,7 @@ export class Index { */ resetProximityPrecision(): EnqueuedTaskPromise { return this.#httpRequestsWithTask.delete({ - path: `indexes/${this.uid}/settings/proximity-precision`, + path: `indexes/${this.#uid}/settings/proximity-precision`, }); } @@ -1192,7 +1128,7 @@ export class Index { */ async getEmbedders(): Promise { return await this.httpRequest.get({ - path: `indexes/${this.uid}/settings/embedders`, + path: `indexes/${this.#uid}/settings/embedders`, }); } @@ -1204,7 +1140,7 @@ export class Index { */ updateEmbedders(embedders: Embedders): EnqueuedTaskPromise { return this.#httpRequestsWithTask.patch({ - path: `indexes/${this.uid}/settings/embedders`, + path: `indexes/${this.#uid}/settings/embedders`, body: embedders, }); } @@ -1216,7 +1152,7 @@ export class Index { */ resetEmbedders(): EnqueuedTaskPromise { return this.#httpRequestsWithTask.delete({ - path: `indexes/${this.uid}/settings/embedders`, + path: `indexes/${this.#uid}/settings/embedders`, }); } @@ -1231,7 +1167,7 @@ export class Index { */ async getSearchCutoffMs(): Promise { return await this.httpRequest.get({ - path: `indexes/${this.uid}/settings/search-cutoff-ms`, + path: `indexes/${this.#uid}/settings/search-cutoff-ms`, }); } @@ -1243,7 +1179,7 @@ export class Index { */ updateSearchCutoffMs(searchCutoffMs: SearchCutoffMs): EnqueuedTaskPromise { return this.#httpRequestsWithTask.put({ - path: `indexes/${this.uid}/settings/search-cutoff-ms`, + path: `indexes/${this.#uid}/settings/search-cutoff-ms`, body: searchCutoffMs, }); } @@ -1255,7 +1191,7 @@ export class Index { */ resetSearchCutoffMs(): EnqueuedTaskPromise { return this.#httpRequestsWithTask.delete({ - path: `indexes/${this.uid}/settings/search-cutoff-ms`, + path: `indexes/${this.#uid}/settings/search-cutoff-ms`, }); } @@ -1270,7 +1206,7 @@ export class Index { */ async getLocalizedAttributes(): Promise { return await this.httpRequest.get({ - path: `indexes/${this.uid}/settings/localized-attributes`, + path: `indexes/${this.#uid}/settings/localized-attributes`, }); } @@ -1284,7 +1220,7 @@ export class Index { localizedAttributes: LocalizedAttributes, ): EnqueuedTaskPromise { return this.#httpRequestsWithTask.put({ - path: `indexes/${this.uid}/settings/localized-attributes`, + path: `indexes/${this.#uid}/settings/localized-attributes`, body: localizedAttributes, }); } @@ -1296,7 +1232,7 @@ export class Index { */ resetLocalizedAttributes(): EnqueuedTaskPromise { return this.#httpRequestsWithTask.delete({ - path: `indexes/${this.uid}/settings/localized-attributes`, + path: `indexes/${this.#uid}/settings/localized-attributes`, }); } @@ -1311,7 +1247,7 @@ export class Index { */ async getFacetSearch(): Promise { return await this.httpRequest.get({ - path: `indexes/${this.uid}/settings/facet-search`, + path: `indexes/${this.#uid}/settings/facet-search`, }); } @@ -1323,7 +1259,7 @@ export class Index { */ updateFacetSearch(facetSearch: boolean): EnqueuedTaskPromise { return this.#httpRequestsWithTask.put({ - path: `indexes/${this.uid}/settings/facet-search`, + path: `indexes/${this.#uid}/settings/facet-search`, body: facetSearch, }); } @@ -1335,7 +1271,7 @@ export class Index { */ resetFacetSearch(): EnqueuedTaskPromise { return this.#httpRequestsWithTask.delete({ - path: `indexes/${this.uid}/settings/facet-search`, + path: `indexes/${this.#uid}/settings/facet-search`, }); } @@ -1350,7 +1286,7 @@ export class Index { */ async getPrefixSearch(): Promise { return await this.httpRequest.get({ - path: `indexes/${this.uid}/settings/prefix-search`, + path: `indexes/${this.#uid}/settings/prefix-search`, }); } @@ -1362,7 +1298,7 @@ export class Index { */ updatePrefixSearch(prefixSearch: PrefixSearch): EnqueuedTaskPromise { return this.#httpRequestsWithTask.put({ - path: `indexes/${this.uid}/settings/prefix-search`, + path: `indexes/${this.#uid}/settings/prefix-search`, body: prefixSearch, }); } @@ -1374,7 +1310,7 @@ export class Index { */ resetPrefixSearch(): EnqueuedTaskPromise { return this.#httpRequestsWithTask.delete({ - path: `indexes/${this.uid}/settings/prefix-search`, + path: `indexes/${this.#uid}/settings/prefix-search`, }); } } diff --git a/src/meilisearch.ts b/src/meilisearch.ts index 018e02a0f..08606f6b2 100644 --- a/src/meilisearch.ts +++ b/src/meilisearch.ts @@ -9,18 +9,14 @@ import { Index } from "./indexes.js"; import type { KeyCreation, Config, - IndexOptions, - IndexObject, Key, Health, Stats, Version, KeyUpdate, - IndexesQuery, - IndexesResults, KeysQuery, KeysResults, - IndexSwap, + SwapIndexesPayload, MultiSearchParams, FederatedMultiSearchParams, MultiSearchResponseOrSearchResponse, @@ -28,9 +24,11 @@ import type { ExtraRequestInit, Network, RecordAny, + IndexViewList, + ListIndexes, + IndexCreateRequest, RuntimeTogglableFeatures, } from "./types/index.js"; -import { ErrorStatusCode } from "./types/index.js"; import { HttpRequests } from "./http-requests.js"; import { getHttpRequestsWithEnqueuedTaskPromise, @@ -38,7 +36,6 @@ import { type HttpRequestsWithEnqueuedTaskPromise, } from "./task.js"; import { BatchClient } from "./batch.js"; -import type { MeiliSearchApiError } from "./errors/index.js"; export class MeiliSearch { config: Config; @@ -78,135 +75,36 @@ export class MeiliSearch { } /** - * Return an Index instance + * Get an {@link Index} instance. * - * @param indexUid - The index UID - * @returns Instance of Index + * @param indexUid - The UID of the index + * @returns An instance of {@link Index} */ index(indexUid: string): Index { return new Index(this.config, indexUid); } - /** - * Gather information about an index by calling MeiliSearch and return an - * Index instance with the gathered information - * - * @param indexUid - The index UID - * @returns Promise returning Index instance - */ - async getIndex( - indexUid: string, - ): Promise> { - return new Index(this.config, indexUid).fetchInfo(); - } - - /** - * Gather information about an index by calling MeiliSearch and return the raw - * JSON response - * - * @param indexUid - The index UID - * @returns Promise returning index information - */ - async getRawIndex(indexUid: string): Promise { - return new Index(this.config, indexUid).getRawInfo(); - } - - /** - * Get all the indexes as Index instances. - * - * @param parameters - Parameters to browse the indexes - * @returns Promise returning array of raw index information - */ - async getIndexes( - parameters?: IndexesQuery, - ): Promise> { - const rawIndexes = await this.getRawIndexes(parameters); - const indexes: Index[] = rawIndexes.results.map( - (index) => new Index(this.config, index.uid, index.primaryKey), - ); - return { ...rawIndexes, results: indexes }; - } - - /** - * Get all the indexes in their raw value (no Index instances). - * - * @param parameters - Parameters to browse the indexes - * @returns Promise returning array of raw index information - */ - async getRawIndexes( - parameters?: IndexesQuery, - ): Promise> { - return await this.httpRequest.get>({ + /** {@link https://www.meilisearch.com/docs/reference/api/indexes#list-all-indexes} */ + async getIndexes(listIndexes?: ListIndexes): Promise { + return await this.httpRequest.get({ path: "indexes", - params: parameters, + params: listIndexes, }); } - /** - * Create a new index - * - * @param uid - The index UID - * @param options - Index options - * @returns Promise returning Index instance - */ - createIndex(uid: string, options?: IndexOptions): EnqueuedTaskPromise { - return Index.create(uid, options, this.config); - } - - /** - * Update an index - * - * @param uid - The index UID - * @param options - Index options to update - * @returns Promise returning Index instance after updating - */ - updateIndex(uid: string, options?: IndexOptions): EnqueuedTaskPromise { - return new Index(this.config, uid).update(options); - } - - /** - * Delete an index - * - * @param uid - The index UID - * @returns Promise which resolves when index is deleted successfully - */ - deleteIndex(uid: string): EnqueuedTaskPromise { - return new Index(this.config, uid).delete(); - } - - /** - * Deletes an index if it already exists. - * - * @param uid - The index UID - * @returns Promise which resolves to true when index exists and is deleted - * successfully, otherwise false if it does not exist - */ - async deleteIndexIfExists(uid: string): Promise { - try { - await this.deleteIndex(uid); - return true; - } catch (e) { - if ( - (e as MeiliSearchApiError)?.cause?.code === - ErrorStatusCode.INDEX_NOT_FOUND - ) { - return false; - } - - throw e; - } + /** {@link https://www.meilisearch.com/docs/reference/api/indexes#create-an-index} */ + createIndex(indexCreateRequest: IndexCreateRequest): EnqueuedTaskPromise { + return this.#httpRequestsWithTask.post({ + path: "indexes", + body: indexCreateRequest, + }); } - /** - * Swaps a list of index tuples. - * - * @param params - List of indexes tuples to swap. - * @returns Promise returning object of the enqueued task - */ - swapIndexes(params: IndexSwap[]): EnqueuedTaskPromise { + /** {@link https://www.meilisearch.com/docs/reference/api/indexes#swap-indexes} */ + swapIndexes(swapIndexesPayloads: SwapIndexesPayload[]): EnqueuedTaskPromise { return this.#httpRequestsWithTask.post({ path: "/swap-indexes", - body: params, + body: swapIndexesPayloads, }); } diff --git a/src/types/index.ts b/src/types/index.ts index 8aaa23dba..5a0597ade 100644 --- a/src/types/index.ts +++ b/src/types/index.ts @@ -1,4 +1,5 @@ export * from "./experimental-features.js"; -export * from "./task_and_batch.js"; +export * from "./indexes.js"; +export * from "./task-and-batch.js"; export * from "./token.js"; export * from "./types.js"; diff --git a/src/types/indexes.ts b/src/types/indexes.ts new file mode 100644 index 000000000..9a7640729 --- /dev/null +++ b/src/types/indexes.ts @@ -0,0 +1,47 @@ +import type { PaginationView } from "./shared.js"; + +/** + * {@link https://www.meilisearch.com/docs/reference/api/indexes#query-parameters} + * + * @see `meilisearch::routes::indexes::ListIndexes` + */ +export type ListIndexes = { + offset?: number; + limit?: number; +}; + +/** + * {@link https://www.meilisearch.com/docs/reference/api/indexes#index-object} + * + * @see `meilisearch::routes::indexes::IndexView` + */ +export type IndexView = { + uid: string; + createdAt: string; + updatedAt: string; + primaryKey: string | null; +}; + +/** {@link https://www.meilisearch.com/docs/reference/api/indexes#response} */ +export type IndexViewList = PaginationView; + +/** + * {@link https://www.meilisearch.com/docs/reference/api/indexes#body-1} + * + * @see `meilisearch::routes::indexes::UpdateIndexRequest` + */ +export type UpdateIndexRequest = { primaryKey?: string | null }; + +/** + * {@link https://www.meilisearch.com/docs/reference/api/indexes#body} + * + * @see `meilisearch::routes::indexes::IndexCreateRequest` + */ +export type IndexCreateRequest = UpdateIndexRequest & { uid: string }; + +/** + * {@link https://www.meilisearch.com/docs/reference/api/indexes#body-2} + * + * @see `meilisearch::routes::swap_indexes::SwapIndexesPayload` + */ +export type SwapIndexesPayload = { indexes: [string, string] }; diff --git a/src/types/shared.ts b/src/types/shared.ts index d475d6948..4d0932f54 100644 --- a/src/types/shared.ts +++ b/src/types/shared.ts @@ -1,10 +1,10 @@ import type { RecordAny } from "./types.js"; -export type CursorResults = { +/** @see `meilisearch::routes::PaginationView` */ +export type PaginationView = { results: T[]; + offset: number; limit: number; - from: number; - next: number; total: number; }; diff --git a/src/types/task_and_batch.ts b/src/types/task-and-batch.ts similarity index 92% rename from src/types/task_and_batch.ts rename to src/types/task-and-batch.ts index ea61fbea9..a7278e3fb 100644 --- a/src/types/task_and_batch.ts +++ b/src/types/task-and-batch.ts @@ -1,6 +1,5 @@ -import type { Settings } from "./types.js"; -import type { CursorResults } from "./shared.js"; -import type { MeiliSearchErrorResponse } from "./types.js"; +import type { Settings, MeiliSearchErrorResponse } from "./types.js"; +import type { SwapIndexesPayload } from "./indexes.js"; /** Options for awaiting {@link EnqueuedTask}. */ export type WaitOptions = { @@ -93,9 +92,6 @@ export type EnqueuedTask = { /** Either a number or an {@link EnqueuedTask}. */ export type TaskUidOrEnqueuedTask = EnqueuedTask["taskUid"] | EnqueuedTask; -/** {@link https://www.meilisearch.com/docs/reference/api/tasks#indexswap} */ -export type IndexSwap = { indexes: [string, string] }; - /** {@link https://www.meilisearch.com/docs/reference/api/tasks#details} */ export type TaskDetails = Settings & { receivedDocuments?: number; @@ -111,7 +107,7 @@ export type TaskDetails = Settings & { dumpUid?: string | null; context?: Record | null; function?: string; - swaps?: IndexSwap[]; + swaps?: SwapIndexesPayload[]; }; /** @@ -142,12 +138,20 @@ export type EnqueuedTaskPromise = Promise & { waitTask: (waitOptions?: WaitOptions) => Promise; }; +type Results = { + results: T[]; + total: number; + limit: number; + from: number | null; + next: number | null; +}; + /** * {@link https://www.meilisearch.com/docs/reference/api/tasks#response} * * @see `meilisearch::routes::tasks::AllTasks` at {@link https://github.com/meilisearch/meilisearch} */ -export type TasksResults = CursorResults; +export type TasksResults = Results; /** {@link https://www.meilisearch.com/docs/reference/api/batches#steps} */ type BatchProgressStep = { @@ -193,4 +197,4 @@ export type Batch = { * * @see `meilisearch::routes::batches::AllBatches` at {@link https://github.com/meilisearch/meilisearch} */ -export type BatchesResults = CursorResults; +export type BatchesResults = Results; diff --git a/src/types/types.ts b/src/types/types.ts index 91d29f4b5..a10eed605 100644 --- a/src/types/types.ts +++ b/src/types/types.ts @@ -4,7 +4,7 @@ // Definitions: https://github.com/meilisearch/meilisearch-js // TypeScript Version: ^5.8.2 -import type { WaitOptions } from "./task_and_batch.js"; +import type { WaitOptions } from "./task-and-batch.js"; // eslint-disable-next-line @typescript-eslint/no-explicit-any export type RecordAny = Record; @@ -130,25 +130,6 @@ export type ResourceResults = Pagination & { total: number; }; -/// -/// Indexes -/// - -export type IndexOptions = { - primaryKey?: string; -}; - -export type IndexObject = { - uid: string; - primaryKey?: string; - createdAt: string; - updatedAt: string; -}; - -export type IndexesQuery = ResourceQuery & {}; - -export type IndexesResults = ResourceResults & {}; - /* * SEARCH PARAMETERS */ diff --git a/tests/batch.test.ts b/tests/batch.test.ts index 5deeb6b35..0c6451bfc 100644 --- a/tests/batch.test.ts +++ b/tests/batch.test.ts @@ -5,9 +5,7 @@ import { clearAllIndexes, } from "./utils/meilisearch-test-utils.js"; -const index = { - uid: "batch-test", -}; +const index = { uid: "batch-test" }; afterAll(() => { return clearAllIndexes(config); @@ -18,7 +16,7 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( ({ permission }) => { beforeEach(async () => { const client = await getClient("Master"); - await client.createIndex(index.uid).waitTask(); + await client.createIndex(index).waitTask(); }); test(`${permission} key: Get all batches`, async () => { diff --git a/tests/client.test.ts b/tests/client.test.ts index c1b5b5926..e26baed2a 100644 --- a/tests/client.test.ts +++ b/tests/client.test.ts @@ -8,7 +8,7 @@ import { type MockInstance, beforeAll, } from "vitest"; -import type { Health, Version, Stats, IndexSwap } from "../src/index.js"; +import type { Health, Version, Stats } from "../src/index.js"; import { ErrorStatusCode, MeiliSearchRequestError } from "../src/index.js"; import { PACKAGE_VERSION } from "../src/package-version.js"; import { @@ -22,22 +22,6 @@ import { assert, } from "./utils/meilisearch-test-utils.js"; -const indexNoPk = { - uid: "movies_test", -}; -const indexPk = { - uid: "movies_test2", - primaryKey: "id", -}; - -const index = { - uid: "movies_test", -}; - -const index2 = { - uid: "movies_test2", -}; - afterAll(() => { return clearAllIndexes(config); }); @@ -257,7 +241,7 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( expect(health).toBe(true); - await client.createIndex("test").waitTask(); + await client.createIndex({ uid: "test" }).waitTask(); const { results } = await client.getIndexes(); @@ -278,13 +262,13 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( expect(health).toBe(true); - await client.createIndex("test").waitTask(); + await client.createIndex({ uid: "test" }).waitTask(); const { results } = await client.getIndexes(); expect(results.length).toBe(1); - const index = await client.getIndex("test"); + const index = client.index("test"); await index.addDocuments([{ id: 1, title: "index_2" }]).waitTask(); @@ -367,204 +351,6 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( }); }); - describe("Test on indexes methods", () => { - test(`${permission} key: create with no primary key`, async () => { - const client = await getClient(permission); - await client.createIndex(indexNoPk.uid).waitTask(); - - const newIndex = await client.getIndex(indexNoPk.uid); - expect(newIndex).toHaveProperty("uid", indexNoPk.uid); - expect(newIndex).toHaveProperty("primaryKey", null); - - const rawIndex = await client.index(indexNoPk.uid).getRawInfo(); - expect(rawIndex).toHaveProperty("uid", indexNoPk.uid); - expect(rawIndex).toHaveProperty("primaryKey", null); - expect(rawIndex).toHaveProperty("createdAt", expect.any(String)); - expect(rawIndex).toHaveProperty("updatedAt", expect.any(String)); - - const response = await client.getIndex(indexNoPk.uid); - expect(response.primaryKey).toBe(null); - expect(response.uid).toBe(indexNoPk.uid); - }); - - test(`${permission} key: create with primary key`, async () => { - const client = await getClient(permission); - await client - .createIndex(indexPk.uid, { - primaryKey: indexPk.primaryKey, - }) - .waitTask(); - - const newIndex = await client.getIndex(indexPk.uid); - - expect(newIndex).toHaveProperty("uid", indexPk.uid); - expect(newIndex).toHaveProperty("primaryKey", indexPk.primaryKey); - - const rawIndex = await client.index(indexPk.uid).getRawInfo(); - expect(rawIndex).toHaveProperty("primaryKey", indexPk.primaryKey); - expect(rawIndex).toHaveProperty("createdAt", expect.any(String)); - expect(rawIndex).toHaveProperty("updatedAt", expect.any(String)); - - const response = await client.getIndex(indexPk.uid); - expect(response.primaryKey).toBe(indexPk.primaryKey); - expect(response.uid).toBe(indexPk.uid); - }); - - test(`${permission} key: get all indexes when not empty`, async () => { - const client = await getClient(permission); - - await client.createIndex(indexPk.uid).waitTask(); - - const { results } = await client.getRawIndexes(); - const indexes = results.map((index) => index.uid); - expect(indexes).toEqual(expect.arrayContaining([indexPk.uid])); - expect(indexes.length).toEqual(1); - }); - - test(`${permission} key: Get index that exists`, async () => { - const client = await getClient(permission); - - await client.createIndex(indexPk.uid).waitTask(); - - const response = await client.getIndex(indexPk.uid); - - expect(response).toHaveProperty("uid", indexPk.uid); - }); - - test(`${permission} key: Get index that does not exist`, async () => { - const client = await getClient(permission); - - await expect(client.getIndex("does_not_exist")).rejects.toHaveProperty( - "cause.code", - ErrorStatusCode.INDEX_NOT_FOUND, - ); - }); - - test(`${permission} key: update primary key`, async () => { - const client = await getClient(permission); - await client.createIndex(indexPk.uid).waitTask(); - await client - .updateIndex(indexPk.uid, { - primaryKey: "newPrimaryKey", - }) - .waitTask(); - - const index = await client.getIndex(indexPk.uid); - - expect(index).toHaveProperty("uid", indexPk.uid); - expect(index).toHaveProperty("primaryKey", "newPrimaryKey"); - }); - - test(`${permission} key: update primary key that already exists`, async () => { - const client = await getClient(permission); - await client - .createIndex(indexPk.uid, { - primaryKey: indexPk.primaryKey, - }) - .waitTask(); - await client - .updateIndex(indexPk.uid, { - primaryKey: "newPrimaryKey", - }) - .waitTask(); - - const index = await client.getIndex(indexPk.uid); - - expect(index).toHaveProperty("uid", indexPk.uid); - expect(index).toHaveProperty("primaryKey", "newPrimaryKey"); - }); - - test(`${permission} key: delete index`, async () => { - const client = await getClient(permission); - await client.createIndex(indexNoPk.uid).waitTask(); - - await client.deleteIndex(indexNoPk.uid).waitTask(); - const { results } = await client.getIndexes(); - - expect(results).toHaveLength(0); - }); - - test(`${permission} key: create index with already existing uid should fail`, async () => { - const client = await getClient(permission); - await client.createIndex(indexPk.uid).waitTask(); - - const task = await client.createIndex(indexPk.uid).waitTask(); - - expect(task.status).toBe("failed"); - }); - - test(`${permission} key: delete index with uid that does not exist should fail`, async () => { - const client = await getClient(permission); - const index = client.index(indexNoPk.uid); - const task = await index.delete().waitTask(); - - expect(task.status).toEqual("failed"); - }); - - test(`${permission} key: fetch deleted index should fail`, async () => { - const client = await getClient(permission); - const index = client.index(indexPk.uid); - await expect(index.getRawInfo()).rejects.toHaveProperty( - "cause.code", - ErrorStatusCode.INDEX_NOT_FOUND, - ); - }); - - test(`${permission} key: Swap two indexes`, async () => { - const client = await getClient(permission); - await client - .index(index.uid) - .addDocuments([{ id: 1, title: `index_1` }]); - await client - .index(index2.uid) - .addDocuments([{ id: 1, title: "index_2" }]) - .waitTask(); - const swaps: IndexSwap[] = [{ indexes: [index.uid, index2.uid] }]; - - const resolvedTask = await client.swapIndexes(swaps).waitTask(); - const docIndex1 = await client.index(index.uid).getDocument(1); - const docIndex2 = await client.index(index2.uid).getDocument(1); - - expect(docIndex1.title).toEqual("index_2"); - expect(docIndex2.title).toEqual("index_1"); - expect(resolvedTask.type).toEqual("indexSwap"); - expect(resolvedTask.details!.swaps).toEqual(swaps); - }); - - test(`${permission} key: Swap two indexes with one that does not exist`, async () => { - const client = await getClient(permission); - - await client - .index(index2.uid) - .addDocuments([{ id: 1, title: "index_2" }]) - .waitTask(); - - const swaps: IndexSwap[] = [ - { indexes: ["does_not_exist", index2.uid] }, - ]; - - const resolvedTask = await client.swapIndexes(swaps).waitTask(); - - expect(resolvedTask.type).toEqual("indexSwap"); - expect(resolvedTask.error?.code).toEqual( - ErrorStatusCode.INDEX_NOT_FOUND, - ); - expect(resolvedTask.details!.swaps).toEqual(swaps); - }); - - // Should be fixed by rc1 - test(`${permission} key: Swap two one index with itself`, async () => { - const client = await getClient(permission); - - const swaps: IndexSwap[] = [{ indexes: [index.uid, index.uid] }]; - - await expect(client.swapIndexes(swaps)).rejects.toHaveProperty( - "cause.code", - ErrorStatusCode.INVALID_SWAP_DUPLICATE_INDEX_FOUND, - ); - }); - }); - describe("Test on base routes", () => { test(`${permission} key: get health`, async () => { const client = await getClient(permission); @@ -614,50 +400,6 @@ describe.each([{ permission: "Search" }])( return clearAllIndexes(config); }); - describe("Test on indexes methods", () => { - test(`${permission} key: try to get all indexes and be denied`, async () => { - const client = await getClient(permission); - await expect(client.getIndexes()).rejects.toHaveProperty( - "cause.code", - ErrorStatusCode.INVALID_API_KEY, - ); - }); - - test(`${permission} key: try to create Index with primary key and be denied`, async () => { - const client = await getClient(permission); - await expect( - client.createIndex(indexPk.uid, { - primaryKey: indexPk.primaryKey, - }), - ).rejects.toHaveProperty("cause.code", ErrorStatusCode.INVALID_API_KEY); - }); - - test(`${permission} key: try to create Index with NO primary key and be denied`, async () => { - const client = await getClient(permission); - await expect(client.createIndex(indexNoPk.uid)).rejects.toHaveProperty( - "cause.code", - ErrorStatusCode.INVALID_API_KEY, - ); - }); - - test(`${permission} key: try to delete index and be denied`, async () => { - const client = await getClient(permission); - await expect(client.deleteIndex(indexPk.uid)).rejects.toHaveProperty( - "cause.code", - ErrorStatusCode.INVALID_API_KEY, - ); - }); - - test(`${permission} key: try to update index and be denied`, async () => { - const client = await getClient(permission); - await expect( - client.updateIndex(indexPk.uid, { - primaryKey: indexPk.primaryKey, - }), - ).rejects.toHaveProperty("cause.code", ErrorStatusCode.INVALID_API_KEY); - }); - }); - describe("Test on misc client methods", () => { test(`${permission} key: get health`, async () => { const client = await getClient(permission); @@ -694,56 +436,6 @@ describe.each([{ permission: "No" }])( return clearAllIndexes(config); }); - describe("Test on indexes methods", () => { - test(`${permission} key: try to get all indexes and be denied`, async () => { - const client = await getClient(permission); - await expect(client.getIndexes()).rejects.toHaveProperty( - "cause.code", - ErrorStatusCode.MISSING_AUTHORIZATION_HEADER, - ); - }); - - test(`${permission} key: try to create Index with primary key and be denied`, async () => { - const client = await getClient(permission); - await expect( - client.createIndex(indexPk.uid, { - primaryKey: indexPk.primaryKey, - }), - ).rejects.toHaveProperty( - "cause.code", - ErrorStatusCode.MISSING_AUTHORIZATION_HEADER, - ); - }); - - test(`${permission} key: try to create Index with NO primary key and be denied`, async () => { - const client = await getClient(permission); - await expect(client.createIndex(indexNoPk.uid)).rejects.toHaveProperty( - "cause.code", - ErrorStatusCode.MISSING_AUTHORIZATION_HEADER, - ); - }); - - test(`${permission} key: try to delete index and be denied`, async () => { - const client = await getClient(permission); - await expect(client.deleteIndex(indexPk.uid)).rejects.toHaveProperty( - "cause.code", - ErrorStatusCode.MISSING_AUTHORIZATION_HEADER, - ); - }); - - test(`${permission} key: try to update index and be denied`, async () => { - const client = await getClient(permission); - await expect( - client.updateIndex(indexPk.uid, { - primaryKey: indexPk.primaryKey, - }), - ).rejects.toHaveProperty( - "cause.code", - ErrorStatusCode.MISSING_AUTHORIZATION_HEADER, - ); - }); - }); - describe("Test on misc client methods", () => { test(`${permission} key: get health`, async () => { const client = await getClient(permission); @@ -778,56 +470,6 @@ describe.each([ { host: `${BAD_HOST}/api`, trailing: false }, { host: `${BAD_HOST}/trailing/`, trailing: true }, ])("Tests on url construction", ({ host, trailing }) => { - test(`getIndex route`, async () => { - const route = `indexes/${indexPk.uid}`; - const client = new MeiliSearch({ host }); - const strippedHost = trailing ? host.slice(0, -1) : host; - await expect(client.getIndex(indexPk.uid)).rejects.toHaveProperty( - "message", - `Request to ${strippedHost}/${route} has failed`, - ); - }); - - test(`createIndex route`, async () => { - const route = `indexes`; - const client = new MeiliSearch({ host }); - const strippedHost = trailing ? host.slice(0, -1) : host; - await expect(client.createIndex(indexPk.uid)).rejects.toHaveProperty( - "message", - `Request to ${strippedHost}/${route} has failed`, - ); - }); - - test(`updateIndex route`, async () => { - const route = `indexes/${indexPk.uid}`; - const client = new MeiliSearch({ host }); - const strippedHost = trailing ? host.slice(0, -1) : host; - await expect(client.updateIndex(indexPk.uid)).rejects.toHaveProperty( - "message", - `Request to ${strippedHost}/${route} has failed`, - ); - }); - - test(`deleteIndex route`, async () => { - const route = `indexes/${indexPk.uid}`; - const client = new MeiliSearch({ host }); - const strippedHost = trailing ? host.slice(0, -1) : host; - await expect(client.deleteIndex(indexPk.uid)).rejects.toHaveProperty( - "message", - `Request to ${strippedHost}/${route} has failed`, - ); - }); - - test(`get indexes route`, async () => { - const route = `indexes`; - const client = new MeiliSearch({ host }); - const strippedHost = trailing ? host.slice(0, -1) : host; - await expect(client.getIndexes()).rejects.toHaveProperty( - "message", - `Request to ${strippedHost}/${route} has failed`, - ); - }); - test(`getKeys route`, async () => { const route = `keys`; const client = new MeiliSearch({ host }); diff --git a/tests/displayed_attributes.test.ts b/tests/displayed_attributes.test.ts index b2779437d..389cf22b1 100644 --- a/tests/displayed_attributes.test.ts +++ b/tests/displayed_attributes.test.ts @@ -74,7 +74,7 @@ describe.each([{ permission: "Search" }])( beforeEach(async () => { await clearAllIndexes(config); const client = await getClient("Master"); - await client.createIndex(index.uid).waitTask(); + await client.createIndex({ uid: index.uid }).waitTask(); }); test(`${permission} key: try to get displayed attributes and be denied`, async () => { @@ -106,7 +106,7 @@ describe.each([{ permission: "No" }])( beforeEach(async () => { await clearAllIndexes(config); const client = await getClient("Master"); - await client.createIndex(index.uid).waitTask(); + await client.createIndex({ uid: index.uid }).waitTask(); }); test(`${permission} key: try to get displayed attributes and be denied`, async () => { diff --git a/tests/documents.test.ts b/tests/documents.test.ts index e9c958761..ef79ff25c 100644 --- a/tests/documents.test.ts +++ b/tests/documents.test.ts @@ -32,9 +32,10 @@ describe("Documents tests", () => { beforeEach(async () => { await clearAllIndexes(config); const client = await getClient("Master"); - await client.createIndex(indexNoPk.uid).waitTask(); + await client.createIndex({ uid: indexNoPk.uid }).waitTask(); await client - .createIndex(indexPk.uid, { + .createIndex({ + uid: indexPk.uid, primaryKey: indexPk.primaryKey, }) .waitTask(); @@ -410,7 +411,7 @@ describe("Documents tests", () => { }; await client.index(indexNoPk.uid).addDocuments([doc]).waitTask(); - const index = await client.index(indexNoPk.uid).fetchInfo(); + const index = await client.index(indexNoPk.uid).getIndex(); expect(index).toHaveProperty("primaryKey", "_id"); }); @@ -423,7 +424,7 @@ describe("Documents tests", () => { }; await client.index(indexNoPk.uid).addDocuments([doc]).waitTask(); - const index = await client.index(indexNoPk.uid).fetchInfo(); + const index = await client.index(indexNoPk.uid).getIndex(); expect(index).toHaveProperty("primaryKey", "findmeid"); }); @@ -439,7 +440,7 @@ describe("Documents tests", () => { .index(indexNoPk.uid) .addDocuments([doc]) .waitTask(); - const index = await client.index(indexNoPk.uid).fetchInfo(); + const index = await client.index(indexNoPk.uid).getIndex(); expect(task.error?.code).toEqual( "index_primary_key_multiple_candidates_found", @@ -457,7 +458,7 @@ describe("Documents tests", () => { .index(indexNoPk.uid) .addDocuments([doc]) .waitTask(); - const index = await client.index(indexNoPk.uid).fetchInfo(); + const index = await client.index(indexNoPk.uid).getIndex(); expect(task.error?.code).toEqual( "index_primary_key_no_candidate_found", @@ -559,7 +560,7 @@ describe("Documents tests", () => { test(`${permission} key: Delete some documents should trigger error with a hint on a MeilisearchApiError`, async () => { const client = await getClient(permission); - await client.createIndex(indexPk.uid).waitTask(); + await client.createIndex({ uid: indexPk.uid }).waitTask(); await assert.rejects( client.index(indexPk.uid).deleteDocuments({ filter: "" }), @@ -627,14 +628,14 @@ describe("Documents tests", () => { }, ]; const pkIndex = "update_pk"; - await client.createIndex(pkIndex).waitTask(); + await client.createIndex({ uid: pkIndex }).waitTask(); await client .index(pkIndex) .addDocuments(docs, { primaryKey: "unique" }) .waitTask(); - const response = await client.index(pkIndex).getRawInfo(); + const response = await client.index(pkIndex).getIndex(); expect(response).toHaveProperty("uid", pkIndex); expect(response).toHaveProperty("primaryKey", "unique"); }); @@ -670,7 +671,7 @@ describe("Documents tests", () => { ]) .waitTask(); - const index = await client.index(indexNoPk.uid).getRawInfo(); + const index = await client.index(indexNoPk.uid).getIndex(); expect(index.uid).toEqual(indexNoPk.uid); expect(index.primaryKey).toEqual(null); diff --git a/tests/embedders.test.ts b/tests/embedders.test.ts index 63d6f09ad..9dfc78e23 100644 --- a/tests/embedders.test.ts +++ b/tests/embedders.test.ts @@ -57,7 +57,7 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( await clearAllIndexes(config); const client = await getClient(permission); - await client.createIndex(index.uid).waitTask(); + await client.createIndex({ uid: index.uid }).waitTask(); }); test(`${permission} key: Get default embedders`, async () => { diff --git a/tests/env/browser/index.html b/tests/env/browser/index.html index 933050d4b..9a40ccb49 100644 --- a/tests/env/browser/index.html +++ b/tests/env/browser/index.html @@ -23,11 +23,11 @@ host: 'http://localhost:7700', apiKey: 'masterKey', }) - await client.createIndex(UID).waitTask() + await client.createIndex({ uid: UID }).waitTask() await client.index(UID).addDocuments([{ id: 1, title: "wonder woman" }]).waitTask() - const index = await client.index(UID).getRawInfo() + const index = await client.index(UID).getIndex() // Create dynamic element to wait on with puppeteer const indexDiv = document.createElement("div"); @@ -41,7 +41,7 @@ searchDiv.innerHTML = JSON.stringify(search) document.body.insertBefore(searchDiv, document.querySelector("#content")); - await client.index(UID).delete().waitTask() + await client.index(UID).deleteIndex().waitTask() } catch (e) { console.error(e); } diff --git a/tests/env/express/public/headers.html b/tests/env/express/public/headers.html index 58d4a96e3..c79999229 100644 --- a/tests/env/express/public/headers.html +++ b/tests/env/express/public/headers.html @@ -23,7 +23,7 @@ let error = 'NO ERRORS' try { - await client.createIndex(UID).waitTask() + await client.createIndex({ uid: UID }).waitTask() await fetch(`http://localhost:7700/indexes/${UID}/documents`, { method: 'POST', headers: { @@ -40,7 +40,7 @@ errorDiv.innerHTML = error document.body.insertBefore(errorDiv, document.querySelector("#content")); - await client.index(UID).delete().waitTask() + await client.index(UID).deleteIndex().waitTask() })() diff --git a/tests/env/express/public/index.html b/tests/env/express/public/index.html index 32dad5380..4c451dacd 100644 --- a/tests/env/express/public/index.html +++ b/tests/env/express/public/index.html @@ -26,11 +26,11 @@ const UID = "testIndex" try { - await client.createIndex(UID).waitTask() + await client.createIndex({ uid: UID }).waitTask() await client.index(UID).addDocuments([{ id: 1, title: "wonder woman" }]).waitTask() - const index = await client.index(UID).getRawInfo() + const index = await client.index(UID).getIndex() // Create dynamic element to wait on with puppeteer const indexDiv = document.createElement("div"); @@ -48,6 +48,6 @@ } searchDiv.innerHTML = content document.body.insertBefore(searchDiv, document.querySelector("#content")); - await client.index(UID).delete().waitTask() + await client.index(UID).deleteIndex().waitTask() })() diff --git a/tests/env/node/search_example.cjs b/tests/env/node/search_example.cjs index ed84b227c..968a1c462 100644 --- a/tests/env/node/search_example.cjs +++ b/tests/env/node/search_example.cjs @@ -10,8 +10,8 @@ const client = new MeiliSearch(config) const indexUid = 'movies' const addDataset = async () => { - await client.deleteIndex(indexUid) - await client.createIndex(indexUid).waitTask() + await client.index(indexUid).deleteIndex().waitTask() + await client.createIndex({ uid: indexUid }).waitTask() const index = client.index(indexUid) diff --git a/tests/env/typescript-browser/src/index.ts b/tests/env/typescript-browser/src/index.ts index 67ec1d0a2..83d588357 100644 --- a/tests/env/typescript-browser/src/index.ts +++ b/tests/env/typescript-browser/src/index.ts @@ -1,4 +1,4 @@ -import { MeiliSearch, type IndexObject } from '../../../../src/index.js' +import { MeiliSearch } from '../../../../src/index.js' import { generateTenantToken } from '../../../../src/token.js' const config = { @@ -14,9 +14,9 @@ function greeter(person: string) { } ;(async () => { - const indexes = await client.getRawIndexes() + const indexes = await client.getIndexes() console.log({ indexes }, 'hello') - const uids = indexes.results.map((index: IndexObject) => index.uid) + const uids = indexes.results.map((index) => index.uid) document.body.innerHTML = `${greeter( user )} this is the list of all your indexes: \n ${uids.join(', ')}` diff --git a/tests/env/typescript-node/src/index.ts b/tests/env/typescript-node/src/index.ts index 495723c13..07b57e952 100644 --- a/tests/env/typescript-node/src/index.ts +++ b/tests/env/typescript-node/src/index.ts @@ -2,7 +2,6 @@ import { MeiliSearch, } from '../../../../src/index.js' import type { - IndexObject, SearchResponse, Hits, Hit, @@ -28,12 +27,12 @@ const client = new MeiliSearch(config) const indexUid = "movies" ;(async () => { - await client.deleteIndex(indexUid).waitTask() - await client.createIndex(indexUid).waitTask() + await client.index(indexUid).deleteIndex().waitTask() + await client.createIndex({ uid: indexUid }).waitTask() const index = client.index(indexUid) - const indexes = await client.getRawIndexes() - indexes.results.map((index: IndexObject) => { + const indexes = await client.getIndexes() + indexes.results.map((index) => { console.log(index.uid) // console.log(index.something) -> ERROR }) @@ -44,7 +43,7 @@ const indexUid = "movies" attributesToHighlight: ['title'], // test: true -> ERROR Test does not exist on type SearchParams } - indexes.results.map((index: IndexObject) => index.uid) + indexes.results.map((index) => index.uid) const res: SearchResponse = await index.search( 'avenger', searchParams @@ -63,5 +62,5 @@ const indexUid = "movies" console.log(await generateTenantToken({ apiKey: config.apiKey, apiKeyUid: 'e489fe16-3381-431b-bee3-00430192915d' })) - await index.delete() + await client.index(indexUid).deleteIndex().waitTask() })() diff --git a/tests/facet_search.test.ts b/tests/facet_search.test.ts index 1c27f10e7..6e5e3a331 100644 --- a/tests/facet_search.test.ts +++ b/tests/facet_search.test.ts @@ -41,7 +41,7 @@ describe.each([ await clearAllIndexes(config); const client = await getClient("Master"); const newFilterableAttributes = ["genres", "title"]; - await client.createIndex(index.uid); + await client.createIndex({ uid: index.uid }); await client.index(index.uid).updateSettings({ filterableAttributes: newFilterableAttributes, }); diff --git a/tests/facet_search_settings.test.ts b/tests/facet_search_settings.test.ts index d1bb67dbe..f79a5b80c 100644 --- a/tests/facet_search_settings.test.ts +++ b/tests/facet_search_settings.test.ts @@ -59,7 +59,7 @@ describe.each([{ permission: "Search" }])( beforeEach(async () => { await clearAllIndexes(config); const client = await getClient("Master"); - await client.createIndex(index.uid).waitTask(); + await client.createIndex({ uid: index.uid }).waitTask(); }); test(`${permission} key: try to get facet search settings and be denied`, async () => { @@ -91,7 +91,7 @@ describe.each([{ permission: "No" }])( beforeEach(async () => { await clearAllIndexes(config); const client = await getClient("Master"); - await client.createIndex(index.uid).waitTask(); + await client.createIndex({ uid: index.uid }).waitTask(); }); test(`${permission} key: try to get facet search settings and be denied`, async () => { diff --git a/tests/faceting.test.ts b/tests/faceting.test.ts index dc942b810..471fe8c28 100644 --- a/tests/faceting.test.ts +++ b/tests/faceting.test.ts @@ -30,7 +30,7 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( beforeEach(async () => { await clearAllIndexes(config); const client = await getClient("Master"); - await client.createIndex(index.uid).waitTask(); + await client.createIndex({ uid: index.uid }).waitTask(); await client.index(index.uid).addDocuments(dataset).waitTask(); }); @@ -89,7 +89,7 @@ describe.each([{ permission: "Search" }])( ({ permission }) => { beforeEach(async () => { const client = await getClient("Master"); - await client.createIndex(index.uid).waitTask(); + await client.createIndex({ uid: index.uid }).waitTask(); }); test(`${permission} key: try to get faceting and be denied`, async () => { @@ -118,7 +118,7 @@ describe.each([{ permission: "Search" }])( describe.each([{ permission: "No" }])("Test on faceting", ({ permission }) => { beforeAll(async () => { const client = await getClient("Master"); - await client.createIndex(index.uid).waitTask(); + await client.createIndex({ uid: index.uid }).waitTask(); }); test(`${permission} key: try to get faceting and be denied`, async () => { diff --git a/tests/filterable_attributes.test.ts b/tests/filterable_attributes.test.ts index c59c87942..b1bdc4c82 100644 --- a/tests/filterable_attributes.test.ts +++ b/tests/filterable_attributes.test.ts @@ -90,7 +90,7 @@ describe.each([{ permission: "Search" }])( ({ permission }) => { beforeEach(async () => { const client = await getClient("Master"); - await client.createIndex(index.uid).waitTask(); + await client.createIndex({ uid: index.uid }).waitTask(); }); test(`${permission} key: try to get attributes for filtering and be denied`, async () => { @@ -121,7 +121,7 @@ describe.each([{ permission: "No" }])( ({ permission }) => { beforeEach(async () => { const client = await getClient("Master"); - await client.createIndex(index.uid).waitTask(); + await client.createIndex({ uid: index.uid }).waitTask(); }); test(`${permission} key: try to get attributes for filtering and be denied`, async () => { diff --git a/tests/get_search.test.ts b/tests/get_search.test.ts index 3a6771b1d..ccbaa43cd 100644 --- a/tests/get_search.test.ts +++ b/tests/get_search.test.ts @@ -84,8 +84,8 @@ describe.each([ beforeAll(async () => { await clearAllIndexes(config); const client = await getClient("Master"); - await client.createIndex(index.uid).waitTask(); - await client.createIndex(emptyIndex.uid).waitTask(); + await client.createIndex({ uid: index.uid }).waitTask(); + await client.createIndex({ uid: emptyIndex.uid }).waitTask(); const newFilterableAttributes = ["genre", "title", "id", "author"]; await client @@ -546,7 +546,7 @@ describe.each([ test(`${permission} key: Try to search on deleted index and fail`, async () => { const client = await getClient(permission); const masterClient = await getClient("Master"); - await masterClient.index(index.uid).delete().waitTask(); + await masterClient.index(index.uid).deleteIndex().waitTask(); await expect( client.index(index.uid).searchGet("prince"), ).rejects.toHaveProperty("cause.code", ErrorStatusCode.INDEX_NOT_FOUND); diff --git a/tests/index-stats.test.ts b/tests/index-stats.test.ts new file mode 100644 index 000000000..22bd8ac49 --- /dev/null +++ b/tests/index-stats.test.ts @@ -0,0 +1,41 @@ +import { randomUUID } from "node:crypto"; +import { afterAll, test } from "vitest"; +import { assert, getClient } from "./utils/meilisearch-test-utils.js"; + +const INDEX_UID = randomUUID(); +const ms = await getClient("Master"); +const index = ms.index(INDEX_UID); + +afterAll(async () => { + const task = await ms.index(INDEX_UID).deleteIndex().waitTask(); + assert.isTaskSuccessful(task); +}); + +test(`${index.getStats.name} method`, async () => { + const task = await index + .addDocuments([ + { id: 1, liberté: true }, + { id: 2, égalité: true }, + { id: 3, fraternité: true }, + ]) + .waitTask(); + + assert.isTaskSuccessful(task); + + const stats = await index.getStats(); + + assert.deepEqual(stats, { + avgDocumentSize: 1357, + fieldDistribution: { + fraternité: 1, + id: 3, + liberté: 1, + égalité: 1, + }, + isIndexing: false, + numberOfDocuments: 3, + numberOfEmbeddedDocuments: 0, + numberOfEmbeddings: 0, + rawDocumentDbSize: 4096, + }); +}); diff --git a/tests/index.test.ts b/tests/index.test.ts index faea55881..a0ea0915a 100644 --- a/tests/index.test.ts +++ b/tests/index.test.ts @@ -1,544 +1,101 @@ -import { expect, test, describe, beforeEach, afterAll } from "vitest"; -import { ErrorStatusCode } from "../src/types/index.js"; -import { - clearAllIndexes, - config, - BAD_HOST, - MeiliSearch, - getClient, -} from "./utils/meilisearch-test-utils.js"; - -const indexNoPk = { - uid: "movies_test", -}; -const indexPk = { - uid: "movies_test2", - primaryKey: "id", -}; - -afterAll(() => clearAllIndexes(config)); - -describe.each([{ permission: "Master" }, { permission: "Admin" }])( - "Test on indexes w/ master and admin key", - ({ permission }) => { - beforeEach(() => { - return clearAllIndexes(config); - }); - - test(`${permission} key: create index with NO primary key`, async () => { - const client = await getClient(permission); - await client.createIndex(indexNoPk.uid).waitTask(); - - const newIndex = await client.getIndex(indexNoPk.uid); - - expect(newIndex).toHaveProperty("uid", indexNoPk.uid); - expect(newIndex).toHaveProperty("primaryKey", null); - - const rawIndex = await client.index(indexNoPk.uid).getRawInfo(); - - expect(rawIndex).toHaveProperty("uid", indexNoPk.uid); - expect(rawIndex).toHaveProperty("primaryKey", null); - expect(rawIndex).toHaveProperty("createdAt", expect.any(String)); - expect(rawIndex).toHaveProperty("updatedAt", expect.any(String)); - }); - - test(`${permission} key: create index with primary key`, async () => { - const client = await getClient(permission); - await client - .createIndex(indexPk.uid, { - primaryKey: indexPk.primaryKey, - }) - .waitTask(); - - const newIndex = await client.getIndex(indexPk.uid); - - expect(newIndex).toHaveProperty("uid", indexPk.uid); - expect(newIndex).toHaveProperty("primaryKey", indexPk.primaryKey); - - const rawIndex = await client.index(indexPk.uid).getRawInfo(); - - expect(rawIndex).toHaveProperty("uid", indexPk.uid); - expect(rawIndex).toHaveProperty("primaryKey", indexPk.primaryKey); - expect(rawIndex).toHaveProperty("createdAt", expect.any(String)); - expect(rawIndex).toHaveProperty("updatedAt", expect.any(String)); - }); - - test(`${permission} key: Get raw index that exists`, async () => { - const client = await getClient(permission); - await client.createIndex(indexPk.uid).waitTask(); - - const response = await client.getRawIndex(indexPk.uid); - - expect(response).toHaveProperty("uid", indexPk.uid); - }); - - test(`${permission} key: Get all indexes in Index instances`, async () => { - const client = await getClient(permission); - await client.createIndex(indexPk.uid).waitTask(); - - const { results } = await client.getRawIndexes(); - - expect(results.length).toEqual(1); - expect(results[0].uid).toEqual(indexPk.uid); - }); - - test(`${permission} key: Get index that does not exist`, async () => { - const client = await getClient(permission); - await expect(client.getIndex("does_not_exist")).rejects.toHaveProperty( - "cause.code", - ErrorStatusCode.INDEX_NOT_FOUND, - ); - }); - - test(`${permission} key: Get raw index that does not exist`, async () => { - const client = await getClient(permission); - await expect(client.getRawIndex("does_not_exist")).rejects.toHaveProperty( - "cause.code", - ErrorStatusCode.INDEX_NOT_FOUND, - ); - }); - - test(`${permission} key: Get raw index info through client with primary key`, async () => { - const client = await getClient(permission); - await client - .createIndex(indexPk.uid, { primaryKey: indexPk.primaryKey }) - .waitTask(); - - const response = await client.getRawIndex(indexPk.uid); - - expect(response).toHaveProperty("uid", indexPk.uid); - expect(response).toHaveProperty("primaryKey", indexPk.primaryKey); - }); - - test(`${permission} key: Get raw index info through client with NO primary key`, async () => { - const client = await getClient(permission); - await client.createIndex(indexNoPk.uid).waitTask(); - - const response = await client.getRawIndex(indexNoPk.uid); - - expect(response).toHaveProperty("uid", indexNoPk.uid); - expect(response).toHaveProperty("primaryKey", null); - }); - - test(`${permission} key: Get raw index info with primary key`, async () => { - const client = await getClient(permission); - await client - .createIndex(indexPk.uid, { primaryKey: indexPk.primaryKey }) - .waitTask(); - - const response = await client.index(indexPk.uid).getRawInfo(); - - expect(response).toHaveProperty("uid", indexPk.uid); - expect(response).toHaveProperty("primaryKey", indexPk.primaryKey); - }); - - test(`${permission} key: Get raw index info with NO primary key`, async () => { - const client = await getClient(permission); - await client.createIndex(indexNoPk.uid).waitTask(); - - const response = await client.index(indexNoPk.uid).getRawInfo(); - - expect(response).toHaveProperty("uid", indexNoPk.uid); - expect(response).toHaveProperty("primaryKey", null); - }); - - test(`${permission} key: fetch index with primary key`, async () => { - const client = await getClient(permission); - await client - .createIndex(indexPk.uid, { - primaryKey: indexPk.primaryKey, - }) - .waitTask(); - - const index = client.index(indexPk.uid); - const response = await index.fetchInfo(); - - expect(response).toHaveProperty("uid", indexPk.uid); - expect(response).toHaveProperty("primaryKey", indexPk.primaryKey); - }); - - test(`${permission} key: fetch primary key on an index with primary key`, async () => { - const client = await getClient(permission); - await client - .createIndex(indexPk.uid, { - primaryKey: indexPk.primaryKey, - }) - .waitTask(); - - const index = client.index(indexPk.uid); - const response: string | undefined = await index.fetchPrimaryKey(); - - expect(response).toBe(indexPk.primaryKey); - }); - - test(`${permission} key: fetch primary key on an index with NO primary key`, async () => { - const client = await getClient(permission); - await client.createIndex(indexNoPk.uid).waitTask(); - - const index = client.index(indexNoPk.uid); - const response: string | undefined = await index.fetchPrimaryKey(); - - expect(response).toBe(null); - }); - - test(`${permission} key: fetch index with primary key`, async () => { - const client = await getClient(permission); - await client - .createIndex(indexPk.uid, { - primaryKey: indexPk.primaryKey, - }) - .waitTask(); - - const index = client.index(indexPk.uid); - const response = await index.fetchInfo(); - - expect(response).toHaveProperty("uid", indexPk.uid); - expect(response).toHaveProperty("primaryKey", indexPk.primaryKey); - }); - - test(`${permission} key: fetch index with NO primary key`, async () => { - const client = await getClient(permission); - await client.createIndex(indexNoPk.uid).waitTask(); - - const index = client.index(indexNoPk.uid); - const response = await index.fetchInfo(); - - expect(response).toHaveProperty("uid", indexNoPk.uid); - expect(response).toHaveProperty("primaryKey", null); - }); - - test(`${permission} key: get all indexes`, async () => { - const client = await getClient(permission); - await client.createIndex(indexNoPk.uid).waitTask(); - await client.createIndex(indexPk.uid).waitTask(); - - const indexes = await client.getIndexes(); - - expect(indexes.results.length).toEqual(2); - }); - - test(`${permission} key: get all indexes with filters`, async () => { - const client = await getClient(permission); - await client.createIndex(indexNoPk.uid).waitTask(); - await client.createIndex(indexPk.uid).waitTask(); - - const indexes = await client.getIndexes({ limit: 1, offset: 1 }); - - expect(indexes.results.length).toEqual(1); - expect(indexes.results[0].uid).toEqual(indexPk.uid); - }); - - test(`${permission} key: update primary key on an index that has no primary key already`, async () => { - const client = await getClient(permission); - await client.createIndex(indexNoPk.uid).waitTask(); - await client - .index(indexNoPk.uid) - .update({ primaryKey: "newPrimaryKey" }) - .waitTask(); - - const index = await client.getIndex(indexNoPk.uid); - - expect(index).toHaveProperty("uid", indexNoPk.uid); - expect(index).toHaveProperty("primaryKey", "newPrimaryKey"); - }); - - test(`${permission} key: update primary key on an index that has NO primary key already through client`, async () => { - const client = await getClient(permission); - await client.createIndex(indexNoPk.uid).waitTask(); - await client - .updateIndex(indexNoPk.uid, { - primaryKey: indexPk.primaryKey, - }) - .waitTask(); - - const index = await client.getIndex(indexNoPk.uid); - - expect(index).toHaveProperty("uid", indexNoPk.uid); - expect(index).toHaveProperty("primaryKey", indexPk.primaryKey); - }); - - test(`${permission} key: update primary key on an index that has already a primary key and fail through client`, async () => { - const client = await getClient(permission); - await client - .createIndex(indexPk.uid, { - primaryKey: indexPk.primaryKey, - }) - .waitTask(); - await client - .updateIndex(indexPk.uid, { - primaryKey: "newPrimaryKey", - }) - .waitTask(); - - const index = await client.getIndex(indexPk.uid); - - expect(index).toHaveProperty("uid", indexPk.uid); - expect(index).toHaveProperty("primaryKey", "newPrimaryKey"); - }); - - test(`${permission} key: update primary key on an index that has already a primary key and fail`, async () => { - const client = await getClient(permission); - await client - .createIndex(indexPk.uid, { primaryKey: indexPk.primaryKey }) - .waitTask(); - await client - .index(indexPk.uid) - .update({ primaryKey: "newPrimaryKey" }) - .waitTask(); - - const index = await client.getIndex(indexPk.uid); - - expect(index).toHaveProperty("uid", indexPk.uid); - expect(index).toHaveProperty("primaryKey", "newPrimaryKey"); - }); - - test(`${permission} key: delete index`, async () => { - const client = await getClient(permission); - await client.createIndex(indexNoPk.uid).waitTask(); - await client.index(indexNoPk.uid).delete().waitTask(); - - const { results } = await client.getIndexes(); - - expect(results).toHaveLength(0); - }); - - test(`${permission} key: delete index using client`, async () => { - const client = await getClient(permission); - await client.createIndex(indexPk.uid); - await client.deleteIndex(indexPk.uid).waitTask(); - - const { results } = await client.getIndexes(); - - expect(results).toHaveLength(0); - }); - - test(`${permission} key: fetch deleted index should fail`, async () => { - const client = await getClient(permission); - const index = client.index(indexNoPk.uid); - await expect(index.getRawInfo()).rejects.toHaveProperty( - "cause.code", - ErrorStatusCode.INDEX_NOT_FOUND, - ); - }); - - test(`${permission} key: get deleted raw index should fail through client`, async () => { - const client = await getClient(permission); - await expect(client.getRawIndex(indexNoPk.uid)).rejects.toHaveProperty( - "cause.code", - ErrorStatusCode.INDEX_NOT_FOUND, - ); - }); - - test(`${permission} key: delete index with uid that does not exist should fail`, async () => { - const client = await getClient(permission); - const index = client.index(indexNoPk.uid); - const task = await index.delete().waitTask(); - - expect(task.status).toBe("failed"); - }); - - test(`${permission} key: get stats of an index`, async () => { - const client = await getClient(permission); - await client.createIndex(indexNoPk.uid).waitTask(); - - const response = await client.index(indexNoPk.uid).getStats(); - - expect(response).toHaveProperty("numberOfDocuments", 0); - expect(response).toHaveProperty("isIndexing", false); - expect(response).toHaveProperty("fieldDistribution", {}); - expect(response).toHaveProperty("numberOfEmbeddedDocuments", 0); - expect(response).toHaveProperty("numberOfEmbeddings", 0); - expect(response).toHaveProperty("rawDocumentDbSize", 0); - expect(response).toHaveProperty("avgDocumentSize", 0); - }); - - test(`${permission} key: Get updatedAt and createdAt through fetch info`, async () => { - const client = await getClient(permission); - await client.createIndex(indexPk.uid).waitTask(); - - const index = await client.index(indexPk.uid).fetchInfo(); - - expect(index.createdAt).toBeInstanceOf(Date); - expect(index.updatedAt).toBeInstanceOf(Date); - }); - - test(`${permission} key: Get updatedAt and createdAt index through getRawInfo`, async () => { - const client = await getClient(permission); - await client.createIndex(indexPk.uid).waitTask(); - - const index = client.index(indexPk.uid); +import { randomUUID } from "node:crypto"; +import { test, afterAll } from "vitest"; +import { getClient, assert } from "./utils/meilisearch-test-utils.js"; +import { Index, type SwapIndexesPayload } from "../src/index.js"; + +const INDEX_UID_ONE = randomUUID(); +const INDEX_UID_TWO = randomUUID(); +const ms = await getClient("Master"); +const index = ms.index(INDEX_UID_ONE); + +test(`${ms.index.name} method`, () => { + const myIndex = ms.index(INDEX_UID_ONE); + assert.instanceOf(myIndex, Index); + assert.strictEqual(myIndex.uid, INDEX_UID_ONE); +}); - expect(index.createdAt).toBe(undefined); - expect(index.updatedAt).toBe(undefined); +afterAll(async () => { + await Promise.all( + [INDEX_UID_ONE, INDEX_UID_TWO].map(async (i) => { + const task = await ms.index(i).deleteIndex().waitTask(); + assert.isTaskSuccessful(task); + }), + ); +}); - await index.getRawInfo(); +test(`${ms.createIndex.name} and ${index.getIndex.name} method`, async () => { + const primaryKey = "cléPrimaire"; + const task = await ms + .createIndex({ uid: INDEX_UID_ONE, primaryKey }) + .waitTask(); - expect(index.createdAt).toBeInstanceOf(Date); - expect(index.updatedAt).toBeInstanceOf(Date); - }); - }, -); + assert.isTaskSuccessful(task); + assert.strictEqual(task.indexUid, INDEX_UID_ONE); + assert.deepEqual(task.details, { primaryKey }); + assert.strictEqual(task.type, "indexCreation"); -describe.each([{ permission: "Search" }])( - "Test on routes with search key", - ({ permission }) => { - beforeEach(() => { - return clearAllIndexes(config); - }); + const { createdAt, updatedAt, ...myIndex } = await index.getIndex(); - test(`${permission} key: try to get index info and be denied`, async () => { - const client = await getClient(permission); - await expect( - client.index(indexNoPk.uid).getRawInfo(), - ).rejects.toHaveProperty("cause.code", ErrorStatusCode.INVALID_API_KEY); - }); + assert.deepEqual(myIndex, { + primaryKey, + uid: INDEX_UID_ONE, + }); + assert.typeOf(createdAt, "string"); + assert.typeOf(updatedAt, "string"); +}); - test(`${permission} key: try to get raw index and be denied`, async () => { - const client = await getClient(permission); - await expect(client.getRawIndex(indexNoPk.uid)).rejects.toHaveProperty( - "cause.code", - ErrorStatusCode.INVALID_API_KEY, - ); - }); +test(`${index.updateIndex.name} and ${index.getIndex.name} method`, async () => { + const primaryKey = "id"; + const task = await index.updateIndex({ primaryKey }).waitTask(); - test(`${permission} key: try to delete index and be denied`, async () => { - const client = await getClient(permission); - await expect(client.index(indexPk.uid).delete()).rejects.toHaveProperty( - "cause.code", - ErrorStatusCode.INVALID_API_KEY, - ); - }); + assert.isTaskSuccessful(task); + assert.strictEqual(task.indexUid, INDEX_UID_ONE); + assert.deepEqual(task.details, { primaryKey }); + assert.strictEqual(task.type, "indexUpdate"); - test(`${permission} key: try to update index and be denied`, async () => { - const client = await getClient(permission); - await expect( - client.index(indexPk.uid).update({ primaryKey: indexPk.primaryKey }), - ).rejects.toHaveProperty("cause.code", ErrorStatusCode.INVALID_API_KEY); - }); + const { createdAt, updatedAt, ...myIndex } = await index.getIndex(); - test(`${permission} key: try to get stats and be denied`, async () => { - const client = await getClient(permission); - await expect(client.index(indexPk.uid).getStats()).rejects.toHaveProperty( - "cause.code", - ErrorStatusCode.INVALID_API_KEY, - ); - }); - }, -); + assert.typeOf(createdAt, "string"); + assert.typeOf(updatedAt, "string"); -describe.each([{ permission: "No" }])( - "Test on routes without an API key", - ({ permission }) => { - beforeEach(() => { - return clearAllIndexes(config); - }); + assert.deepEqual(myIndex, { + primaryKey, + uid: INDEX_UID_ONE, + }); +}); - test(`${permission} key: try to get all indexes and be denied`, async () => { - const client = await getClient(permission); - await expect(client.getIndexes()).rejects.toHaveProperty( - "cause.code", - ErrorStatusCode.MISSING_AUTHORIZATION_HEADER, - ); - }); +test(`${index.deleteIndex.name} method`, async () => { + const task = await index.deleteIndex().waitTask(); - test(`${permission} key: try to get index info and be denied`, async () => { - const client = await getClient(permission); - await expect( - client.index(indexNoPk.uid).getRawInfo(), - ).rejects.toHaveProperty( - "cause.code", - ErrorStatusCode.MISSING_AUTHORIZATION_HEADER, - ); - }); + assert.isTaskSuccessful(task); + assert.strictEqual(task.indexUid, INDEX_UID_ONE); + assert.deepEqual(task.details, { deletedDocuments: 0 }); + assert.strictEqual(task.type, "indexDeletion"); +}); - test(`${permission} key: try to get raw index and be denied`, async () => { - const client = await getClient(permission); - await expect(client.getRawIndex(indexNoPk.uid)).rejects.toHaveProperty( - "cause.code", - ErrorStatusCode.MISSING_AUTHORIZATION_HEADER, - ); - }); +test(`${ms.swapIndexes.name} method`, async () => { + const otherIndex = ms.index(INDEX_UID_TWO); - test(`${permission} key: try to delete index and be denied`, async () => { - const client = await getClient(permission); - await expect(client.index(indexPk.uid).delete()).rejects.toHaveProperty( - "cause.code", - ErrorStatusCode.MISSING_AUTHORIZATION_HEADER, - ); - }); + const doc1 = { id: 1, title: "index_un" }; + const doc2 = { id: 1, title: "index_deux" }; - test(`${permission} key: try to update index and be denied`, async () => { - const client = await getClient(permission); - await expect( - client.index(indexPk.uid).update({ primaryKey: indexPk.primaryKey }), - ).rejects.toHaveProperty( - "cause.code", - ErrorStatusCode.MISSING_AUTHORIZATION_HEADER, - ); - }); - }, -); + await index.addDocuments([doc1]).waitTask(); + await otherIndex.addDocuments([doc2]).waitTask(); -describe.each([ - { host: BAD_HOST, trailing: false }, - { host: `${BAD_HOST}/api`, trailing: false }, - { host: `${BAD_HOST}/trailing/`, trailing: true }, -])("Tests on url construction", ({ host, trailing }) => { - test(`getStats route`, async () => { - const route = `indexes/${indexPk.uid}/stats`; - const client = new MeiliSearch({ host }); - const strippedHost = trailing ? host.slice(0, -1) : host; - await expect(client.index(indexPk.uid).getStats()).rejects.toHaveProperty( - "message", - `Request to ${strippedHost}/${route} has failed`, - ); - }); + const swaps: SwapIndexesPayload[] = [ + { indexes: [INDEX_UID_ONE, INDEX_UID_TWO] }, + ]; - test(`getRawInfo route`, async () => { - const route = `indexes/${indexPk.uid}`; - const client = new MeiliSearch({ host }); - const strippedHost = trailing ? host.slice(0, -1) : host; - await expect(client.index(indexPk.uid).getRawInfo()).rejects.toHaveProperty( - "message", - `Request to ${strippedHost}/${route} has failed`, - ); - await expect(client.index(indexPk.uid).getRawInfo()).rejects.toHaveProperty( - "name", - "MeiliSearchRequestError", - ); - }); + const task = await ms.swapIndexes(swaps).waitTask(); - test(`getRawIndex route`, async () => { - const route = `indexes/${indexPk.uid}`; - const client = new MeiliSearch({ host }); - const strippedHost = trailing ? host.slice(0, -1) : host; - await expect(client.getRawIndex(indexPk.uid)).rejects.toHaveProperty( - "message", - `Request to ${strippedHost}/${route} has failed`, - ); - await expect(client.getRawIndex(indexPk.uid)).rejects.toHaveProperty( - "name", - "MeiliSearchRequestError", - ); - }); + assert.isTaskSuccessful(task); + assert.strictEqual(task.indexUid, null); + assert.deepEqual(task.details, { swaps }); + assert.strictEqual(task.type, "indexSwap"); - test(`updateIndex route`, async () => { - const route = `indexes/${indexPk.uid}`; - const client = new MeiliSearch({ host }); - const strippedHost = trailing ? host.slice(0, -1) : host; - await expect(client.index(indexPk.uid).getRawInfo()).rejects.toHaveProperty( - "message", - `Request to ${strippedHost}/${route} has failed`, - ); - }); + const docIndex = await index.getDocument(doc2.id); + const docOtherIndex = await otherIndex.getDocument(doc1.id); - test(`delete index route`, async () => { - const route = `indexes/${indexPk.uid}`; - const client = new MeiliSearch({ host }); - const strippedHost = trailing ? host.slice(0, -1) : host; - await expect(client.index(indexPk.uid).getRawInfo()).rejects.toHaveProperty( - "message", - `Request to ${strippedHost}/${route} has failed`, - ); - }); + assert.deepEqual(doc1, docOtherIndex); + assert.deepEqual(doc2, docIndex); }); diff --git a/tests/keys.test.ts b/tests/keys.test.ts index a1e305d07..9a9f30920 100644 --- a/tests/keys.test.ts +++ b/tests/keys.test.ts @@ -136,7 +136,7 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( }); const newClient = new MeiliSearch({ host: HOST, apiKey: key.key }); - await newClient.createIndex("wildcard_keys_permission"); // test index creation + await newClient.createIndex({ uid: "wildcard_keys_permission" }); // test index creation const task = await newClient .index("wildcard_keys_permission") .addDocuments([{ id: 1 }]) diff --git a/tests/localized_attributes.test.ts b/tests/localized_attributes.test.ts index 963f406be..4b8c9e5d7 100644 --- a/tests/localized_attributes.test.ts +++ b/tests/localized_attributes.test.ts @@ -108,7 +108,7 @@ describe.each([{ permission: "Search" }])( ({ permission }) => { beforeEach(async () => { const client = await getClient("Master"); - await client.createIndex(index.uid).waitTask(); + await client.createIndex({ uid: index.uid }).waitTask(); }); test(`${permission} key: try to get localizedAttributes and be denied`, async () => { @@ -139,7 +139,7 @@ describe.each([{ permission: "No" }])( ({ permission }) => { beforeAll(async () => { const client = await getClient("Master"); - await client.createIndex(index.uid).waitTask(); + await client.createIndex({ uid: index.uid }).waitTask(); }); test(`${permission} key: try to get localizedAttributes and be denied`, async () => { diff --git a/tests/pagination.test.ts b/tests/pagination.test.ts index f8736bf53..87888f17d 100644 --- a/tests/pagination.test.ts +++ b/tests/pagination.test.ts @@ -84,7 +84,7 @@ describe.each([{ permission: "Search" }])( ({ permission }) => { beforeEach(async () => { const client = await getClient("Master"); - await client.createIndex(index.uid).waitTask(); + await client.createIndex({ uid: index.uid }).waitTask(); }); test(`${permission} key: try to get pagination and be denied`, async () => { @@ -115,7 +115,7 @@ describe.each([{ permission: "No" }])( ({ permission }) => { beforeAll(async () => { const client = await getClient("Master"); - await client.createIndex(index.uid).waitTask(); + await client.createIndex({ uid: index.uid }).waitTask(); }); test(`${permission} key: try to get pagination and be denied`, async () => { diff --git a/tests/prefix_search_settings.test.ts b/tests/prefix_search_settings.test.ts index 77685c5fc..438b5cfe4 100644 --- a/tests/prefix_search_settings.test.ts +++ b/tests/prefix_search_settings.test.ts @@ -59,7 +59,7 @@ describe.each([{ permission: "Search" }])( beforeEach(async () => { await clearAllIndexes(config); const client = await getClient("Master"); - await client.createIndex(index.uid).waitTask(); + await client.createIndex({ uid: index.uid }).waitTask(); }); test(`${permission} key: try to get prefix search settings and be denied`, async () => { @@ -91,7 +91,7 @@ describe.each([{ permission: "No" }])( beforeEach(async () => { await clearAllIndexes(config); const client = await getClient("Master"); - await client.createIndex(index.uid).waitTask(); + await client.createIndex({ uid: index.uid }).waitTask(); }); test(`${permission} key: try to get prefix search settings and be denied`, async () => { diff --git a/tests/search.test.ts b/tests/search.test.ts index 8cacb0e6b..0bf881272 100644 --- a/tests/search.test.ts +++ b/tests/search.test.ts @@ -126,8 +126,8 @@ describe.each([ beforeAll(async () => { await clearAllIndexes(config); const client = await getClient("Master"); - await client.createIndex(index.uid); - await client.createIndex(emptyIndex.uid); + await client.createIndex({ uid: index.uid }); + await client.createIndex({ uid: emptyIndex.uid }); const newFilterableAttributes = ["genre", "title", "id", "author"]; await client @@ -285,7 +285,7 @@ describe.each([ const masterClient = await getClient("Master"); // Setup to have a new "movies" index - await masterClient.createIndex("movies"); + await masterClient.createIndex({ uid: "movies" }); const newFilterableAttributes = ["title", "id"]; await masterClient .index("movies") @@ -363,7 +363,7 @@ describe.each([ const masterClient = await getClient("Master"); // Setup to have a new "movies" index - await masterClient.createIndex("movies"); + await masterClient.createIndex({ uid: "movies" }); const newFilterableAttributes = ["title", "id"]; await masterClient .index("movies") @@ -1240,7 +1240,7 @@ describe.each([ test(`${permission} key: Try to search on deleted index and fail`, async () => { const client = await getClient(permission); const masterClient = await getClient("Master"); - await masterClient.index(index.uid).delete().waitTask(); + await masterClient.index(index.uid).deleteIndex().waitTask(); await expect( client.index(index.uid).search("prince", {}), @@ -1253,7 +1253,7 @@ describe.each([{ permission: "No" }])( ({ permission }) => { beforeAll(async () => { const client = await getClient("Master"); - await client.createIndex(index.uid).waitTask(); + await client.createIndex({ uid: index.uid }).waitTask(); }); test(`${permission} key: Try Basic search and be denied`, async () => { @@ -1282,7 +1282,7 @@ describe.each([{ permission: "Master" }])( beforeEach(async () => { await clearAllIndexes(config); const client = await getClient("Master"); - await client.createIndex(index.uid); + await client.createIndex({ uid: index.uid }); await client.index(index.uid).addDocuments(datasetWithNests).waitTask(); }); @@ -1356,7 +1356,7 @@ describe.each([ beforeAll(async () => { const client = await getClient("Master"); await clearAllIndexes(config); - await client.createIndex(index.uid).waitTask(); + await client.createIndex({ uid: index.uid }).waitTask(); }); test(`${permission} key: search on index and abort`, async () => { diff --git a/tests/search_cutoff_ms.test.ts b/tests/search_cutoff_ms.test.ts index 7c96faa04..4fdbbe825 100644 --- a/tests/search_cutoff_ms.test.ts +++ b/tests/search_cutoff_ms.test.ts @@ -101,7 +101,7 @@ describe.each([{ permission: "Search" }])( ({ permission }) => { beforeEach(async () => { const client = await getClient("Master"); - await client.createIndex(index.uid).waitTask(); + await client.createIndex({ uid: index.uid }).waitTask(); }); test(`${permission} key: try to get searchCutoffMs and be denied`, async () => { @@ -132,7 +132,7 @@ describe.each([{ permission: "No" }])( ({ permission }) => { beforeAll(async () => { const client = await getClient("Master"); - await client.createIndex(index.uid).waitTask(); + await client.createIndex({ uid: index.uid }).waitTask(); }); test(`${permission} key: try to get searchCutoffMs and be denied`, async () => { diff --git a/tests/searchable_attributes.test.ts b/tests/searchable_attributes.test.ts index 8a1b1030f..421506cab 100644 --- a/tests/searchable_attributes.test.ts +++ b/tests/searchable_attributes.test.ts @@ -78,7 +78,7 @@ describe.each([{ permission: "Search" }])( ({ permission }) => { beforeEach(async () => { const client = await getClient("Master"); - await client.createIndex(index.uid).waitTask(); + await client.createIndex({ uid: index.uid }).waitTask(); }); test(`${permission} key: try to get searchable attributes and be denied`, async () => { @@ -109,7 +109,7 @@ describe.each([{ permission: "No" }])( ({ permission }) => { beforeAll(async () => { const client = await getClient("Master"); - await client.createIndex(index.uid).waitTask(); + await client.createIndex({ uid: index.uid }).waitTask(); }); test(`${permission} key: try to get searchable attributes and be denied`, async () => { diff --git a/tests/sortable_attributes.test.ts b/tests/sortable_attributes.test.ts index 814c7f7f0..acdcdaefb 100644 --- a/tests/sortable_attributes.test.ts +++ b/tests/sortable_attributes.test.ts @@ -29,7 +29,7 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( ({ permission }) => { beforeEach(async () => { const client = await getClient("Master"); - await client.createIndex(index.uid).waitTask(); + await client.createIndex({ uid: index.uid }).waitTask(); await client.index(index.uid).addDocuments(dataset).waitTask(); }); @@ -79,7 +79,7 @@ describe.each([{ permission: "Search" }])( ({ permission }) => { beforeEach(async () => { const client = await getClient("Master"); - await client.createIndex(index.uid).waitTask(); + await client.createIndex({ uid: index.uid }).waitTask(); }); test(`${permission} key: try to get sortable attributes and be denied`, async () => { @@ -110,7 +110,7 @@ describe.each([{ permission: "No" }])( ({ permission }) => { beforeAll(async () => { const client = await getClient("Master"); - await client.createIndex(index.uid).waitTask(); + await client.createIndex({ uid: index.uid }).waitTask(); }); test(`${permission} key: try to get sortable attributes and be denied`, async () => { diff --git a/tests/task.test.ts b/tests/task.test.ts index 2032e9747..b939ff608 100644 --- a/tests/task.test.ts +++ b/tests/task.test.ts @@ -31,7 +31,7 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( ({ permission }) => { beforeEach(async () => { const client = await getClient("Master"); - await client.createIndex(index.uid).waitTask(); + await client.createIndex({ uid: index.uid }).waitTask(); }); test(`${permission} key: Get one enqueued task`, async () => { @@ -92,7 +92,7 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( const client = await getClient(permission); await client.index(index.uid).addDocuments([{ id: 1 }]); await client.index(index.uid).deleteDocument(1); - await client.createIndex(index2.uid); + await client.createIndex({ uid: index2.uid }); const tasks = await client.tasks.getTasks({ types: ["documentAdditionOrUpdate", "documentDeletion"], diff --git a/tests/token.test.ts b/tests/token.test.ts index 349c95037..bd410dfdf 100644 --- a/tests/token.test.ts +++ b/tests/token.test.ts @@ -83,7 +83,7 @@ describe.each([{ permission: "Admin" }])( ({ permission }) => { beforeEach(async () => { const client = await getClient("Master"); - await client.index(UID).delete(); + await client.index(UID).deleteIndex().waitTask(); await client.index(UID).addDocuments(dataset).waitTask(); const keys = await client.getKeys(); diff --git a/tests/typed_search.test.ts b/tests/typed_search.test.ts index a34381989..d2d9502ae 100644 --- a/tests/typed_search.test.ts +++ b/tests/typed_search.test.ts @@ -113,8 +113,8 @@ describe.each([ const client = await getClient("Master"); await clearAllIndexes(config); - await client.createIndex(index.uid).waitTask(); - await client.createIndex(emptyIndex.uid).waitTask(); + await client.createIndex({ uid: index.uid }).waitTask(); + await client.createIndex({ uid: emptyIndex.uid }).waitTask(); const newFilterableAttributes = ["genre", "title"]; await client @@ -393,7 +393,7 @@ describe.each([ test(`${permission} key: Try to Search on deleted index and fail`, async () => { const client = await getClient(permission); const masterClient = await getClient("Master"); - await masterClient.index(index.uid).delete().waitTask(); + await masterClient.index(index.uid).deleteIndex().waitTask(); await expect( client.index(index.uid).search("prince"), @@ -407,7 +407,7 @@ describe.each([{ permission: "Master" }])( beforeEach(async () => { await clearAllIndexes(config); const client = await getClient("Master"); - await client.createIndex(index.uid); + await client.createIndex({ uid: index.uid }); await client.index(index.uid).addDocuments(datasetWithNests).waitTask(); }); diff --git a/tests/utils/meilisearch-test-utils.ts b/tests/utils/meilisearch-test-utils.ts index e9faf9510..dadd88678 100644 --- a/tests/utils/meilisearch-test-utils.ts +++ b/tests/utils/meilisearch-test-utils.ts @@ -1,6 +1,6 @@ import { assert as vitestAssert } from "vitest"; import { MeiliSearch, Index } from "../../src/index.js"; -import type { Config } from "../../src/types/index.js"; +import type { Config, Task } from "../../src/types/index.js"; // testing const MASTER_KEY = "masterKey"; @@ -79,11 +79,11 @@ async function getClient(permission: string): Promise { const clearAllIndexes = async (config: Config): Promise => { const client = new MeiliSearch(config); - const { results } = await client.getRawIndexes(); + const { results } = await client.getIndexes(); await Promise.all( results.map((v) => - client.index(v.uid).delete().waitTask({ timeout: 60_000 }), + client.index(v.uid).deleteIndex().waitTask({ timeout: 60_000 }), ), ); }; @@ -127,6 +127,10 @@ const source = { "expected value to not resolve", ); }, + isTaskSuccessful(task: Task) { + vitestAssert.isNull(task.error); + vitestAssert.strictEqual(task.status, "succeeded"); + }, }; export const assert: typeof vitestAssert & typeof source = Object.assign( vitestAssert, diff --git a/tests/wait_for_task.test.ts b/tests/wait_for_task.test.ts index 95c33ff08..52c54c4c6 100644 --- a/tests/wait_for_task.test.ts +++ b/tests/wait_for_task.test.ts @@ -19,7 +19,7 @@ describe.each([{ permission: "Master" }, { permission: "Admin" }])( ({ permission }) => { beforeEach(async () => { const client = await getClient("Master"); - await client.createIndex(index.uid).waitTask(); + await client.createIndex({ uid: index.uid }).waitTask(); }); // Client Wait for task