From 77fa8e12b5ab434e084be8c31790e8d67f02d8be Mon Sep 17 00:00:00 2001 From: "F. Levi" <55688616+flevi29@users.noreply.github.com> Date: Tue, 21 May 2024 14:30:07 +0300 Subject: [PATCH 1/9] Improved errors and error handling in http-requests --- src/errors/http-error-handler.ts | 44 --------------- src/errors/meilisearch-api-error.ts | 32 +++-------- src/errors/meilisearch-communication-error.ts | 46 ++-------------- src/errors/meilisearch-error.ts | 17 ++---- src/errors/meilisearch-timeout-error.ts | 15 +---- src/http-requests.ts | 55 +++++++++---------- src/indexes.ts | 6 +- src/types/types.ts | 7 ++- 8 files changed, 53 insertions(+), 169 deletions(-) delete mode 100644 src/errors/http-error-handler.ts diff --git a/src/errors/http-error-handler.ts b/src/errors/http-error-handler.ts deleted file mode 100644 index 63efaf1a1..000000000 --- a/src/errors/http-error-handler.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { MeiliSearchCommunicationError } from './meilisearch-communication-error' -import { MeiliSearchApiError } from './meilisearch-api-error' -import { FetchError } from '../types' - -async function httpResponseErrorHandler(response: Response): Promise { - if (!response.ok) { - let responseBody - try { - // If it is not possible to parse the return body it means there is none - // In which case it is a communication error with the Meilisearch instance - responseBody = await response.json() - } catch (e: any) { - // Not sure on how to test this part of the code. - throw new MeiliSearchCommunicationError( - response.statusText, - response, - response.url - ) - } - // If the body is parsable, then it means Meilisearch returned a body with - // information on the error. - throw new MeiliSearchApiError(responseBody, response.status) - } - - return response -} - -function httpErrorHandler( - response: FetchError, - stack?: string, - url?: string -): Promise { - if (response.name !== 'MeiliSearchApiError') { - throw new MeiliSearchCommunicationError( - response.message, - response, - url, - stack - ) - } - throw response -} - -export { httpResponseErrorHandler, httpErrorHandler } diff --git a/src/errors/meilisearch-api-error.ts b/src/errors/meilisearch-api-error.ts index 7a8b45a9e..1dc78b1c4 100644 --- a/src/errors/meilisearch-api-error.ts +++ b/src/errors/meilisearch-api-error.ts @@ -1,30 +1,12 @@ -import { MeiliSearchErrorInfo } from '../types' +import { MeiliSearchErrorInfo as MeiliSearchErrorResponse } from '../types' import { MeiliSearchError } from './meilisearch-error' -const MeiliSearchApiError = class extends MeiliSearchError { - httpStatus: number - code: string - link: string - type: string - stack?: string +export class MeiliSearchApiError extends MeiliSearchError { + override name = 'MeiliSearchApiError' + override cause: MeiliSearchErrorResponse & { response: Response } - constructor(error: MeiliSearchErrorInfo, status: number) { - super(error.message) - - // Make errors comparison possible. ex: error instanceof MeiliSearchApiError. - Object.setPrototypeOf(this, MeiliSearchApiError.prototype) - - this.name = 'MeiliSearchApiError' - - this.code = error.code - this.type = error.type - this.link = error.link - this.message = error.message - this.httpStatus = status - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, MeiliSearchApiError) - } + constructor(responseBody: MeiliSearchErrorResponse, response: Response) { + super(responseBody.message) + this.cause = { response, ...responseBody } } } -export { MeiliSearchApiError } diff --git a/src/errors/meilisearch-communication-error.ts b/src/errors/meilisearch-communication-error.ts index edf6bd3e9..87d9fac94 100644 --- a/src/errors/meilisearch-communication-error.ts +++ b/src/errors/meilisearch-communication-error.ts @@ -1,47 +1,9 @@ -import { FetchError } from '../types' import { MeiliSearchError } from './meilisearch-error' -class MeiliSearchCommunicationError extends MeiliSearchError { - statusCode?: number - errno?: string - code?: string - stack?: string +export class MeiliSearchRequestError extends MeiliSearchError { + override name = 'MeiliSearchRequestError' - constructor( - message: string, - body: Response | FetchError, - url?: string, - stack?: string - ) { - super(message) - - // Make errors comparison possible. ex: error instanceof MeiliSearchCommunicationError. - Object.setPrototypeOf(this, MeiliSearchCommunicationError.prototype) - - this.name = 'MeiliSearchCommunicationError' - - if (body instanceof Response) { - this.message = body.statusText - this.statusCode = body.status - } - if (body instanceof Error) { - this.errno = body.errno - this.code = body.code - } - if (stack) { - this.stack = stack - this.stack = this.stack?.replace(/(TypeError|FetchError)/, this.name) - this.stack = this.stack?.replace( - 'Failed to fetch', - `request to ${url} failed, reason: connect ECONNREFUSED` - ) - this.stack = this.stack?.replace('Not Found', `Not Found: ${url}`) - } else { - if (Error.captureStackTrace) { - Error.captureStackTrace(this, MeiliSearchCommunicationError) - } - } + constructor(cause: unknown) { + super("Request to Meilisearch endpoint has failed", { cause }) } } - -export { MeiliSearchCommunicationError } diff --git a/src/errors/meilisearch-error.ts b/src/errors/meilisearch-error.ts index 517fc6b1a..b601c2add 100644 --- a/src/errors/meilisearch-error.ts +++ b/src/errors/meilisearch-error.ts @@ -1,16 +1,7 @@ -class MeiliSearchError extends Error { - constructor(message: string) { - super(message) +export class MeiliSearchError extends Error { + override name = 'MeiliSearchError' - // Make errors comparison possible. ex: error instanceof MeiliSearchError. - Object.setPrototypeOf(this, MeiliSearchError.prototype) - - this.name = 'MeiliSearchError' - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, MeiliSearchError) - } + constructor(...params: ConstructorParameters) { + super(...params) } } - -export { MeiliSearchError } diff --git a/src/errors/meilisearch-timeout-error.ts b/src/errors/meilisearch-timeout-error.ts index 9e114e5c4..fdfc5d3d4 100644 --- a/src/errors/meilisearch-timeout-error.ts +++ b/src/errors/meilisearch-timeout-error.ts @@ -1,18 +1,9 @@ import { MeiliSearchError } from './meilisearch-error' -class MeiliSearchTimeOutError extends MeiliSearchError { +export class MeiliSearchTimeOutError extends MeiliSearchError { + override name = 'MeiliSearchTimeOutError' + constructor(message: string) { super(message) - - // Make errors comparison possible. ex: error instanceof MeiliSearchTimeOutError. - Object.setPrototypeOf(this, MeiliSearchTimeOutError.prototype) - - this.name = 'MeiliSearchTimeOutError' - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, MeiliSearchTimeOutError) - } } } - -export { MeiliSearchTimeOutError } diff --git a/src/http-requests.ts b/src/http-requests.ts index df91d38e1..beebb7967 100644 --- a/src/http-requests.ts +++ b/src/http-requests.ts @@ -1,10 +1,10 @@ -import { Config, EnqueuedTaskObject } from './types' +import { Config, EnqueuedTaskObject, MeiliSearchErrorInfo } from './types' import { PACKAGE_VERSION } from './package-version' import { MeiliSearchError, - httpResponseErrorHandler, - httpErrorHandler, + MeiliSearchApiError, + MeiliSearchRequestError, } from './errors' import { addTrailingSlash, addProtocolIfNotPresent } from './utils' @@ -143,35 +143,34 @@ class HttpRequests { } const headers = { ...this.headers, ...config.headers } + const responsePromise = this.fetchWithTimeout( + constructURL.toString(), + { + ...config, + ...this.requestConfig, + method, + body, + headers, + }, + this.requestTimeout + ) - try { - const result = this.fetchWithTimeout( - constructURL.toString(), - { - ...config, - ...this.requestConfig, - method, - body, - headers, - }, - this.requestTimeout - ) - - // When using a custom HTTP client, the response is returned to allow the user to parse/handle it as they see fit - if (this.httpClient) { - return await result - } + const response = await responsePromise.catch((error: unknown) => { + throw new MeiliSearchRequestError(error) + }) + + // When using a custom HTTP client, the response is returned to allow the user to parse/handle it as they see fit + if (this.httpClient !== undefined) { + return response + } - const response = await result.then((res: any) => - httpResponseErrorHandler(res) - ) - const parsedBody = await response.json().catch(() => undefined) + const parsedResponseBody = await response.json() - return parsedBody - } catch (e: any) { - const stack = e.stack - httpErrorHandler(e, stack, constructURL.toString()) + if (!response.ok) { + throw new MeiliSearchApiError(parsedResponseBody, response) } + + return parsedResponseBody } async fetchWithTimeout( diff --git a/src/indexes.ts b/src/indexes.ts index 1690402db..ba0dc7ff9 100644 --- a/src/indexes.ts +++ b/src/indexes.ts @@ -9,7 +9,7 @@ import { MeiliSearchError, - MeiliSearchCommunicationError, + MeiliSearchRequestError, versionErrorHintMessage, MeiliSearchApiError, } from './errors' @@ -360,7 +360,7 @@ class Index = Record> { Promise> >(url, parameters) } catch (e) { - if (e instanceof MeiliSearchCommunicationError) { + if (e instanceof MeiliSearchRequestError) { e.message = versionErrorHintMessage(e.message, 'getDocuments') } else if (e instanceof MeiliSearchApiError) { e.message = versionErrorHintMessage(e.message, 'getDocuments') @@ -586,7 +586,7 @@ class Index = Record> { return new EnqueuedTask(task) } catch (e) { if ( - e instanceof MeiliSearchCommunicationError && + e instanceof MeiliSearchRequestError && isDocumentsDeletionQuery ) { e.message = versionErrorHintMessage(e.message, 'deleteDocuments') diff --git a/src/types/types.ts b/src/types/types.ts index 46b59835a..9bf63a77d 100644 --- a/src/types/types.ts +++ b/src/types/types.ts @@ -656,12 +656,15 @@ export interface FetchError extends Error { } export type MeiliSearchErrorInfo = { - code: string - link: string message: string + // @TODO: Could be typed, but will it be kept updated? https://www.meilisearch.com/docs/reference/errors/error_codes + code: string + // @TODO: Could be typed https://www.meilisearch.com/docs/reference/errors/overview#errors type: string + link: string } +// @TODO: This doesn't seem to be updated, and its usefullness comes into question. export const ErrorStatusCode = { /** @see https://www.meilisearch.com/docs/reference/errors/error_codes#index_creation_failed */ INDEX_CREATION_FAILED: 'index_creation_failed', From 66a6c02e6d3accb49b66c1d290d03f30a77f0c58 Mon Sep 17 00:00:00 2001 From: "F. Levi" <55688616+flevi29@users.noreply.github.com> Date: Tue, 21 May 2024 15:42:13 +0300 Subject: [PATCH 2/9] Adapted tests in client.test.ts, added more metadata to errors --- jest-disable-built-in-fetch.js | 5 - jest.config.js | 45 ++++---- src/errors/index.ts | 1 - src/errors/meilisearch-communication-error.ts | 4 +- src/http-requests.ts | 2 +- tests/client.test.ts | 105 +++++++----------- 6 files changed, 65 insertions(+), 97 deletions(-) delete mode 100644 jest-disable-built-in-fetch.js diff --git a/jest-disable-built-in-fetch.js b/jest-disable-built-in-fetch.js deleted file mode 100644 index e3a010195..000000000 --- a/jest-disable-built-in-fetch.js +++ /dev/null @@ -1,5 +0,0 @@ -module.exports = function () { - // This is required for tests to work with "cross-fetch" on newer node versions, - // otherwise "cross-fetch" won't replace the builtin `fetch` - globalThis.fetch = undefined -} diff --git a/jest.config.js b/jest.config.js index baf3bfede..167e81ed4 100644 --- a/jest.config.js +++ b/jest.config.js @@ -1,42 +1,43 @@ /** @type {import('jest').Config} */ const config = { - rootDir: '.', - testMatch: ['/tests/**/*.ts?(x)'], + rootDir: ".", + testMatch: ["/tests/**/*.ts?(x)"], verbose: true, - testPathIgnorePatterns: ['meilisearch-test-utils', 'env'], + testPathIgnorePatterns: ["meilisearch-test-utils", "env"], collectCoverage: true, coverageThreshold: { global: { - 'ts-jest': { - tsConfig: '/tsconfig.json', + "ts-jest": { + tsConfig: "/tsconfig.json", }, }, }, watchPlugins: [ - 'jest-watch-typeahead/filename', - 'jest-watch-typeahead/testname', + "jest-watch-typeahead/filename", + "jest-watch-typeahead/testname", ], - globalSetup: './jest-disable-built-in-fetch.js', projects: [ { - preset: 'ts-jest', - displayName: 'browser', - testEnvironment: 'jsdom', - testMatch: ['/tests/**/*.ts?(x)'], + preset: "ts-jest", + displayName: "browser", + testEnvironment: "jsdom", + testMatch: ["/tests/**/*.ts?(x)"], testPathIgnorePatterns: [ - 'meilisearch-test-utils', - 'env/', - 'token.test.ts', + "meilisearch-test-utils", + "env/", + "token.test.ts", ], + // make sure built-in Node.js fetch doesn't get replaced for consistency + globals: { fetch: global.fetch }, }, { - preset: 'ts-jest', - displayName: 'node', - testEnvironment: 'node', - testMatch: ['/tests/**/*.ts?(x)'], - testPathIgnorePatterns: ['meilisearch-test-utils', 'env/'], + preset: "ts-jest", + displayName: "node", + testEnvironment: "node", + testMatch: ["/tests/**/*.ts?(x)"], + testPathIgnorePatterns: ["meilisearch-test-utils", "env/"], }, ], -} +}; -module.exports = config +module.exports = config; diff --git a/src/errors/index.ts b/src/errors/index.ts index 65d6af148..f23081e89 100644 --- a/src/errors/index.ts +++ b/src/errors/index.ts @@ -1,4 +1,3 @@ -export * from './http-error-handler' export * from './meilisearch-api-error' export * from './meilisearch-communication-error' export * from './meilisearch-error' diff --git a/src/errors/meilisearch-communication-error.ts b/src/errors/meilisearch-communication-error.ts index 87d9fac94..89984a253 100644 --- a/src/errors/meilisearch-communication-error.ts +++ b/src/errors/meilisearch-communication-error.ts @@ -3,7 +3,7 @@ import { MeiliSearchError } from './meilisearch-error' export class MeiliSearchRequestError extends MeiliSearchError { override name = 'MeiliSearchRequestError' - constructor(cause: unknown) { - super("Request to Meilisearch endpoint has failed", { cause }) + constructor(url: string, cause: unknown) { + super(`Request to ${url} has failed`, { cause }) } } diff --git a/src/http-requests.ts b/src/http-requests.ts index beebb7967..86b0db5ba 100644 --- a/src/http-requests.ts +++ b/src/http-requests.ts @@ -156,7 +156,7 @@ class HttpRequests { ) const response = await responsePromise.catch((error: unknown) => { - throw new MeiliSearchRequestError(error) + throw new MeiliSearchRequestError(constructURL.toString(), error) }) // When using a custom HTTP client, the response is returned to allow the user to parse/handle it as they see fit diff --git a/tests/client.test.ts b/tests/client.test.ts index 7e3ab3e4e..f0f72df0b 100644 --- a/tests/client.test.ts +++ b/tests/client.test.ts @@ -56,11 +56,11 @@ describe.each([ apiKey: key, requestConfig: { headers: { - Expect: '200-OK', + 'Hello-There!': 'General Kenobi', }, }, }) - expect(client.httpRequest.headers['Expect']).toBe('200-OK') + expect(client.httpRequest.headers['Hello-There!']).toBe('General Kenobi') const health = await client.isHealthy() expect(health).toBe(true) }) @@ -71,10 +71,10 @@ describe.each([ ...config, apiKey: key, requestConfig: { - headers: [['Expect', '200-OK']], + headers: [['Hello-There!', 'General Kenobi']], }, }) - expect(client.httpRequest.headers['Expect']).toBe('200-OK') + expect(client.httpRequest.headers['Hello-There!']).toBe('General Kenobi') const health = await client.isHealthy() expect(health).toBe(true) }) @@ -82,7 +82,7 @@ describe.each([ test(`${permission} key: Create client with custom headers (Headers)`, async () => { const key = await getKey(permission) const headers = new Headers() - headers.append('Expect', '200-OK') + headers.append('Hello-There!', 'General Kenobi') const client = new MeiliSearch({ ...config, apiKey: key, @@ -90,7 +90,7 @@ describe.each([ headers, }, }) - expect(client.httpRequest.headers.expect).toBe('200-OK') + expect(client.httpRequest.headers['hello-there!']).toBe('General Kenobi') const health = await client.isHealthy() expect(health).toBe(true) }) @@ -107,7 +107,7 @@ describe.each([ expect(health).toBe(false) // Left here to trigger failed test if error is not thrown } catch (e: any) { expect(e.message).toMatch(`${BAD_HOST}/api/health`) - expect(e.name).toBe('MeiliSearchCommunicationError') + expect(e.name).toBe('MeiliSearchRequestError') } }) @@ -123,7 +123,7 @@ describe.each([ expect(health).toBe(false) // Left here to trigger failed test if error is not thrown } catch (e: any) { expect(e.message).toMatch(`${BAD_HOST}/api/health`) - expect(e.name).toBe('MeiliSearchCommunicationError') + expect(e.name).toBe('MeiliSearchRequestError') } }) @@ -139,7 +139,7 @@ describe.each([ expect(health).toBe(false) // Left here to trigger failed test if error is not thrown } catch (e: any) { expect(e.message).toMatch(`${BAD_HOST}//health`) - expect(e.name).toBe('MeiliSearchCommunicationError') + expect(e.name).toBe('MeiliSearchRequestError') } }) @@ -155,7 +155,7 @@ describe.each([ expect(health).toBe(false) // Left here to trigger failed test if error is not thrown } catch (e: any) { expect(e.message).toMatch(`${BAD_HOST}/health`) - expect(e.name).toBe('MeiliSearchCommunicationError') + expect(e.name).toBe('MeiliSearchRequestError') } }) @@ -164,7 +164,7 @@ describe.each([ try { await client.health() } catch (e: any) { - expect(e.name).toEqual('MeiliSearchCommunicationError') + expect(e.name).toEqual('MeiliSearchRequestError') } }) @@ -203,12 +203,12 @@ describe.each([{ permission: 'Master' }, { permission: 'Admin' }])( apiKey: key, requestConfig: { headers: { - Expect: '200-OK', + 'Hello-There!': 'General Kenobi', }, }, }) expect(client.config.requestConfig?.headers).toStrictEqual({ - Expect: '200-OK', + 'Hello-There!': 'General Kenobi', }) const health = await client.isHealthy() @@ -365,7 +365,7 @@ describe.each([{ permission: 'Master' }, { permission: 'Admin' }])( const client = await getClient(permission) await expect(client.getIndex('does_not_exist')).rejects.toHaveProperty( - 'code', + 'cause.code', ErrorStatusCode.INDEX_NOT_FOUND ) }) @@ -439,7 +439,7 @@ describe.each([{ permission: 'Master' }, { permission: 'Admin' }])( const client = await getClient(permission) const index = client.index(indexPk.uid) await expect(index.getRawInfo()).rejects.toHaveProperty( - 'code', + 'cause.code', ErrorStatusCode.INDEX_NOT_FOUND ) }) @@ -505,7 +505,7 @@ describe.each([{ permission: 'Master' }, { permission: 'Admin' }])( ] await expect(client.swapIndexes(swaps)).rejects.toHaveProperty( - 'code', + 'cause.code', ErrorStatusCode.INVALID_SWAP_DUPLICATE_INDEX_FOUND ) }) @@ -563,7 +563,7 @@ describe.each([{ permission: 'Search' }])( test(`${permission} key: try to get all indexes and be denied`, async () => { const client = await getClient(permission) await expect(client.getIndexes()).rejects.toHaveProperty( - 'code', + 'cause.code', ErrorStatusCode.INVALID_API_KEY ) }) @@ -574,13 +574,13 @@ describe.each([{ permission: 'Search' }])( client.createIndex(indexPk.uid, { primaryKey: indexPk.primaryKey, }) - ).rejects.toHaveProperty('code', ErrorStatusCode.INVALID_API_KEY) + ).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( - 'code', + 'cause.code', ErrorStatusCode.INVALID_API_KEY ) }) @@ -588,7 +588,7 @@ describe.each([{ permission: 'Search' }])( test(`${permission} key: try to delete index and be denied`, async () => { const client = await getClient(permission) await expect(client.deleteIndex(indexPk.uid)).rejects.toHaveProperty( - 'code', + 'cause.code', ErrorStatusCode.INVALID_API_KEY ) }) @@ -599,7 +599,7 @@ describe.each([{ permission: 'Search' }])( client.updateIndex(indexPk.uid, { primaryKey: indexPk.primaryKey, }) - ).rejects.toHaveProperty('code', ErrorStatusCode.INVALID_API_KEY) + ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY) }) }) @@ -616,7 +616,7 @@ describe.each([{ permission: 'Search' }])( test(`${permission} key: try to get version and be denied`, async () => { const client = await getClient(permission) await expect(client.getVersion()).rejects.toHaveProperty( - 'code', + 'cause.code', ErrorStatusCode.INVALID_API_KEY ) }) @@ -624,7 +624,7 @@ describe.each([{ permission: 'Search' }])( test(`${permission} key: try to get /stats information and be denied`, async () => { const client = await getClient(permission) await expect(client.getStats()).rejects.toHaveProperty( - 'code', + 'cause.code', ErrorStatusCode.INVALID_API_KEY ) }) @@ -643,7 +643,7 @@ describe.each([{ permission: 'No' }])( test(`${permission} key: try to get all indexes and be denied`, async () => { const client = await getClient(permission) await expect(client.getIndexes()).rejects.toHaveProperty( - 'code', + 'cause.code', ErrorStatusCode.MISSING_AUTHORIZATION_HEADER ) }) @@ -655,7 +655,7 @@ describe.each([{ permission: 'No' }])( primaryKey: indexPk.primaryKey, }) ).rejects.toHaveProperty( - 'code', + 'cause.code', ErrorStatusCode.MISSING_AUTHORIZATION_HEADER ) }) @@ -663,7 +663,7 @@ describe.each([{ permission: 'No' }])( 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( - 'code', + 'cause.code', ErrorStatusCode.MISSING_AUTHORIZATION_HEADER ) }) @@ -671,7 +671,7 @@ describe.each([{ permission: 'No' }])( test(`${permission} key: try to delete index and be denied`, async () => { const client = await getClient(permission) await expect(client.deleteIndex(indexPk.uid)).rejects.toHaveProperty( - 'code', + 'cause.code', ErrorStatusCode.MISSING_AUTHORIZATION_HEADER ) }) @@ -683,7 +683,7 @@ describe.each([{ permission: 'No' }])( primaryKey: indexPk.primaryKey, }) ).rejects.toHaveProperty( - 'code', + 'cause.code', ErrorStatusCode.MISSING_AUTHORIZATION_HEADER ) }) @@ -702,7 +702,7 @@ describe.each([{ permission: 'No' }])( test(`${permission} key: try to get version and be denied`, async () => { const client = await getClient(permission) await expect(client.getVersion()).rejects.toHaveProperty( - 'code', + 'cause.code', ErrorStatusCode.MISSING_AUTHORIZATION_HEADER ) }) @@ -710,7 +710,7 @@ describe.each([{ permission: 'No' }])( test(`${permission} key: try to get /stats information and be denied`, async () => { const client = await getClient(permission) await expect(client.getStats()).rejects.toHaveProperty( - 'code', + 'cause.code', ErrorStatusCode.MISSING_AUTHORIZATION_HEADER ) }) @@ -729,10 +729,7 @@ describe.each([ const strippedHost = trailing ? host.slice(0, -1) : host await expect(client.getIndex(indexPk.uid)).rejects.toHaveProperty( 'message', - `request to ${strippedHost}/${route} failed, reason: connect ECONNREFUSED ${BAD_HOST.replace( - 'http://', - '' - )}` + `Request to ${strippedHost}/${route} has failed` ) }) @@ -742,10 +739,7 @@ describe.each([ const strippedHost = trailing ? host.slice(0, -1) : host await expect(client.createIndex(indexPk.uid)).rejects.toHaveProperty( 'message', - `request to ${strippedHost}/${route} failed, reason: connect ECONNREFUSED ${BAD_HOST.replace( - 'http://', - '' - )}` + `Request to ${strippedHost}/${route} has failed` ) }) @@ -755,10 +749,7 @@ describe.each([ const strippedHost = trailing ? host.slice(0, -1) : host await expect(client.updateIndex(indexPk.uid)).rejects.toHaveProperty( 'message', - `request to ${strippedHost}/${route} failed, reason: connect ECONNREFUSED ${BAD_HOST.replace( - 'http://', - '' - )}` + `Request to ${strippedHost}/${route} has failed` ) }) @@ -768,10 +759,7 @@ describe.each([ const strippedHost = trailing ? host.slice(0, -1) : host await expect(client.deleteIndex(indexPk.uid)).rejects.toHaveProperty( 'message', - `request to ${strippedHost}/${route} failed, reason: connect ECONNREFUSED ${BAD_HOST.replace( - 'http://', - '' - )}` + `Request to ${strippedHost}/${route} has failed` ) }) @@ -781,10 +769,7 @@ describe.each([ const strippedHost = trailing ? host.slice(0, -1) : host await expect(client.getIndexes()).rejects.toHaveProperty( 'message', - `request to ${strippedHost}/${route} failed, reason: connect ECONNREFUSED ${BAD_HOST.replace( - 'http://', - '' - )}` + `Request to ${strippedHost}/${route} has failed` ) }) @@ -794,10 +779,7 @@ describe.each([ const strippedHost = trailing ? host.slice(0, -1) : host await expect(client.getKeys()).rejects.toHaveProperty( 'message', - `request to ${strippedHost}/${route} failed, reason: connect ECONNREFUSED ${BAD_HOST.replace( - 'http://', - '' - )}` + `Request to ${strippedHost}/${route} has failed` ) }) @@ -807,10 +789,7 @@ describe.each([ const strippedHost = trailing ? host.slice(0, -1) : host await expect(client.health()).rejects.toHaveProperty( 'message', - `request to ${strippedHost}/${route} failed, reason: connect ECONNREFUSED ${BAD_HOST.replace( - 'http://', - '' - )}` + `Request to ${strippedHost}/${route} has failed` ) }) @@ -820,10 +799,7 @@ describe.each([ const strippedHost = trailing ? host.slice(0, -1) : host await expect(client.getStats()).rejects.toHaveProperty( 'message', - `request to ${strippedHost}/${route} failed, reason: connect ECONNREFUSED ${BAD_HOST.replace( - 'http://', - '' - )}` + `Request to ${strippedHost}/${route} has failed` ) }) @@ -833,10 +809,7 @@ describe.each([ const strippedHost = trailing ? host.slice(0, -1) : host await expect(client.getVersion()).rejects.toHaveProperty( 'message', - `request to ${strippedHost}/${route} failed, reason: connect ECONNREFUSED ${BAD_HOST.replace( - 'http://', - '' - )}` + `Request to ${strippedHost}/${route} has failed` ) }) }) From 778bd061663e0c72711f77e6d6970cc73fbde1c9 Mon Sep 17 00:00:00 2001 From: "F. Levi" <55688616+flevi29@users.noreply.github.com> Date: Tue, 21 May 2024 19:56:59 +0300 Subject: [PATCH 3/9] Adapted most tests to changes --- package.json | 1 - src/errors/index.ts | 2 +- src/errors/meilisearch-api-error.ts | 16 ++-- ...-error.ts => meilisearch-request-error.ts} | 0 src/http-requests.ts | 10 ++- src/types/types.ts | 4 +- tests/dictionary.test.ts | 15 +--- tests/displayed_attributes.test.ts | 27 ++---- tests/distinct_attribute.test.ts | 27 ++---- tests/documents.test.ts | 67 +++++--------- tests/dump.test.ts | 9 +- tests/embedders.test.ts | 17 +--- tests/errors.test.ts | 35 ++++---- tests/facet_search.test.ts | 1 + tests/faceting.test.ts | 27 ++---- tests/filterable_attributes.test.ts | 27 ++---- tests/get_search.test.ts | 51 ++++++----- tests/index.test.ts | 57 +++++------- tests/keys.test.ts | 8 +- tests/non_separator_tokens.test.ts | 15 +--- tests/pagination.test.ts | 27 ++---- tests/proximity_precision.test.ts | 15 +--- tests/ranking_rules.test.ts | 27 ++---- tests/search.test.ts | 88 +++++++++++-------- tests/searchCutoffMs.ts | 29 +++--- tests/searchable_attributes.test.ts | 27 ++---- tests/separator_tokens.test.ts | 15 +--- tests/settings.test.ts | 27 ++---- tests/snapshots.test.ts | 9 +- tests/sortable_attributes.test.ts | 27 ++---- tests/stop_words.test.ts | 27 ++---- tests/synonyms.test.ts | 27 ++---- tests/task.test.ts | 32 +++---- tests/token.test.ts | 4 +- tests/typed_search.test.ts | 17 ++-- tests/typo_tolerance.test.ts | 27 ++---- yarn.lock | 12 --- 37 files changed, 325 insertions(+), 528 deletions(-) rename src/errors/{meilisearch-communication-error.ts => meilisearch-request-error.ts} (100%) diff --git a/package.json b/package.json index 019209538..1f57eab03 100644 --- a/package.json +++ b/package.json @@ -84,7 +84,6 @@ "@types/jest": "^29.5.11", "@typescript-eslint/eslint-plugin": "^6.19.0", "@typescript-eslint/parser": "^6.19.0", - "abort-controller": "^3.0.0", "brotli-size": "^4.0.0", "eslint": "^8.56.0", "eslint-config-prettier": "^9.1.0", diff --git a/src/errors/index.ts b/src/errors/index.ts index f23081e89..d2f24dfc1 100644 --- a/src/errors/index.ts +++ b/src/errors/index.ts @@ -1,5 +1,5 @@ export * from './meilisearch-api-error' -export * from './meilisearch-communication-error' +export * from './meilisearch-request-error' export * from './meilisearch-error' export * from './meilisearch-timeout-error' export * from './version-hint-message' diff --git a/src/errors/meilisearch-api-error.ts b/src/errors/meilisearch-api-error.ts index 1dc78b1c4..8b25995d9 100644 --- a/src/errors/meilisearch-api-error.ts +++ b/src/errors/meilisearch-api-error.ts @@ -1,12 +1,18 @@ -import { MeiliSearchErrorInfo as MeiliSearchErrorResponse } from '../types' +import { MeiliSearchErrorResponse } from '../types' import { MeiliSearchError } from './meilisearch-error' export class MeiliSearchApiError extends MeiliSearchError { override name = 'MeiliSearchApiError' - override cause: MeiliSearchErrorResponse & { response: Response } + override cause?: MeiliSearchErrorResponse + readonly response: Response - constructor(responseBody: MeiliSearchErrorResponse, response: Response) { - super(responseBody.message) - this.cause = { response, ...responseBody } + constructor(response: Response, responseBody?: MeiliSearchErrorResponse) { + super(responseBody?.message ?? `${response.status}: ${response.statusText}`) + + this.response = response + + if (responseBody !== undefined) { + this.cause = responseBody + } } } diff --git a/src/errors/meilisearch-communication-error.ts b/src/errors/meilisearch-request-error.ts similarity index 100% rename from src/errors/meilisearch-communication-error.ts rename to src/errors/meilisearch-request-error.ts diff --git a/src/http-requests.ts b/src/http-requests.ts index 86b0db5ba..e1d2a33b7 100644 --- a/src/http-requests.ts +++ b/src/http-requests.ts @@ -1,4 +1,4 @@ -import { Config, EnqueuedTaskObject, MeiliSearchErrorInfo } from './types' +import { Config, EnqueuedTaskObject } from './types' import { PACKAGE_VERSION } from './package-version' import { @@ -164,13 +164,15 @@ class HttpRequests { return response } - const parsedResponseBody = await response.json() + const responseBody = await response.text() + const parsedResponse = + responseBody === '' ? undefined : JSON.parse(responseBody) if (!response.ok) { - throw new MeiliSearchApiError(parsedResponseBody, response) + throw new MeiliSearchApiError(response, parsedResponse) } - return parsedResponseBody + return parsedResponse } async fetchWithTimeout( diff --git a/src/types/types.ts b/src/types/types.ts index 9bf63a77d..9b3337e98 100644 --- a/src/types/types.ts +++ b/src/types/types.ts @@ -546,7 +546,7 @@ export type TaskObject = Omit & { // Query parameters used to filter the tasks originalFilter?: string } - error: MeiliSearchErrorInfo | null + error: MeiliSearchErrorResponse | null duration: string startedAt: string finishedAt: string @@ -655,7 +655,7 @@ export interface FetchError extends Error { code: string } -export type MeiliSearchErrorInfo = { +export type MeiliSearchErrorResponse = { message: string // @TODO: Could be typed, but will it be kept updated? https://www.meilisearch.com/docs/reference/errors/error_codes code: string diff --git a/tests/dictionary.test.ts b/tests/dictionary.test.ts index a2f2e3a9f..1fa67c143 100644 --- a/tests/dictionary.test.ts +++ b/tests/dictionary.test.ts @@ -85,10 +85,7 @@ describe.each([ client.index(index.uid).getDictionary() ).rejects.toHaveProperty( 'message', - `request to ${strippedHost}/${route} failed, reason: connect ECONNREFUSED ${BAD_HOST.replace( - 'http://', - '' - )}` + `Request to ${strippedHost}/${route} has failed` ) }) @@ -100,10 +97,7 @@ describe.each([ client.index(index.uid).updateDictionary([]) ).rejects.toHaveProperty( 'message', - `request to ${strippedHost}/${route} failed, reason: connect ECONNREFUSED ${BAD_HOST.replace( - 'http://', - '' - )}` + `Request to ${strippedHost}/${route} has failed` ) }) @@ -115,10 +109,7 @@ describe.each([ client.index(index.uid).resetDictionary() ).rejects.toHaveProperty( 'message', - `request to ${strippedHost}/${route} failed, reason: connect ECONNREFUSED ${BAD_HOST.replace( - 'http://', - '' - )}` + `Request to ${strippedHost}/${route} has failed` ) }) }) diff --git a/tests/displayed_attributes.test.ts b/tests/displayed_attributes.test.ts index e1a8de078..36566fa10 100644 --- a/tests/displayed_attributes.test.ts +++ b/tests/displayed_attributes.test.ts @@ -86,21 +86,21 @@ describe.each([{ permission: 'Search' }])( const client = await getClient(permission) await expect( client.index(index.uid).getDisplayedAttributes() - ).rejects.toHaveProperty('code', ErrorStatusCode.INVALID_API_KEY) + ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY) }) test(`${permission} key: try to update displayed attributes and be denied`, async () => { const client = await getClient(permission) await expect( client.index(index.uid).updateDisplayedAttributes([]) - ).rejects.toHaveProperty('code', ErrorStatusCode.INVALID_API_KEY) + ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY) }) test(`${permission} key: try to reset displayed attributes and be denied`, async () => { const client = await getClient(permission) await expect( client.index(index.uid).resetDisplayedAttributes() - ).rejects.toHaveProperty('code', ErrorStatusCode.INVALID_API_KEY) + ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY) }) } ) @@ -120,7 +120,7 @@ describe.each([{ permission: 'No' }])( await expect( client.index(index.uid).getDisplayedAttributes() ).rejects.toHaveProperty( - 'code', + 'cause.code', ErrorStatusCode.MISSING_AUTHORIZATION_HEADER ) }) @@ -130,7 +130,7 @@ describe.each([{ permission: 'No' }])( await expect( client.index(index.uid).updateDisplayedAttributes([]) ).rejects.toHaveProperty( - 'code', + 'cause.code', ErrorStatusCode.MISSING_AUTHORIZATION_HEADER ) }) @@ -140,7 +140,7 @@ describe.each([{ permission: 'No' }])( await expect( client.index(index.uid).resetDisplayedAttributes() ).rejects.toHaveProperty( - 'code', + 'cause.code', ErrorStatusCode.MISSING_AUTHORIZATION_HEADER ) }) @@ -160,10 +160,7 @@ describe.each([ client.index(index.uid).getDisplayedAttributes() ).rejects.toHaveProperty( 'message', - `request to ${strippedHost}/${route} failed, reason: connect ECONNREFUSED ${BAD_HOST.replace( - 'http://', - '' - )}` + `Request to ${strippedHost}/${route} has failed` ) }) @@ -175,10 +172,7 @@ describe.each([ client.index(index.uid).updateDisplayedAttributes([]) ).rejects.toHaveProperty( 'message', - `request to ${strippedHost}/${route} failed, reason: connect ECONNREFUSED ${BAD_HOST.replace( - 'http://', - '' - )}` + `Request to ${strippedHost}/${route} has failed` ) }) @@ -190,10 +184,7 @@ describe.each([ client.index(index.uid).resetDisplayedAttributes() ).rejects.toHaveProperty( 'message', - `request to ${strippedHost}/${route} failed, reason: connect ECONNREFUSED ${BAD_HOST.replace( - 'http://', - '' - )}` + `Request to ${strippedHost}/${route} has failed` ) }) }) diff --git a/tests/distinct_attribute.test.ts b/tests/distinct_attribute.test.ts index 8e7981bcb..568883361 100644 --- a/tests/distinct_attribute.test.ts +++ b/tests/distinct_attribute.test.ts @@ -81,21 +81,21 @@ describe.each([{ permission: 'Search' }])( const client = await getClient(permission) await expect( client.index(index.uid).getDistinctAttribute() - ).rejects.toHaveProperty('code', ErrorStatusCode.INVALID_API_KEY) + ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY) }) test(`${permission} key: try to update distinct attribute and be denied`, async () => { const client = await getClient(permission) await expect( client.index(index.uid).updateDistinctAttribute('title') - ).rejects.toHaveProperty('code', ErrorStatusCode.INVALID_API_KEY) + ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY) }) test(`${permission} key: try to reset distinct attribute and be denied`, async () => { const client = await getClient(permission) await expect( client.index(index.uid).resetDistinctAttribute() - ).rejects.toHaveProperty('code', ErrorStatusCode.INVALID_API_KEY) + ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY) }) } ) @@ -112,7 +112,7 @@ describe.each([{ permission: 'No' }])( await expect( client.index(index.uid).getDistinctAttribute() ).rejects.toHaveProperty( - 'code', + 'cause.code', ErrorStatusCode.MISSING_AUTHORIZATION_HEADER ) }) @@ -122,7 +122,7 @@ describe.each([{ permission: 'No' }])( await expect( client.index(index.uid).updateDistinctAttribute('title') ).rejects.toHaveProperty( - 'code', + 'cause.code', ErrorStatusCode.MISSING_AUTHORIZATION_HEADER ) }) @@ -132,7 +132,7 @@ describe.each([{ permission: 'No' }])( await expect( client.index(index.uid).resetDistinctAttribute() ).rejects.toHaveProperty( - 'code', + 'cause.code', ErrorStatusCode.MISSING_AUTHORIZATION_HEADER ) }) @@ -152,10 +152,7 @@ describe.each([ client.index(index.uid).getDistinctAttribute() ).rejects.toHaveProperty( 'message', - `request to ${strippedHost}/${route} failed, reason: connect ECONNREFUSED ${BAD_HOST.replace( - 'http://', - '' - )}` + `Request to ${strippedHost}/${route} has failed` ) }) @@ -167,10 +164,7 @@ describe.each([ client.index(index.uid).updateDistinctAttribute('a') ).rejects.toHaveProperty( 'message', - `request to ${strippedHost}/${route} failed, reason: connect ECONNREFUSED ${BAD_HOST.replace( - 'http://', - '' - )}` + `Request to ${strippedHost}/${route} has failed` ) }) @@ -182,10 +176,7 @@ describe.each([ client.index(index.uid).resetDistinctAttribute() ).rejects.toHaveProperty( 'message', - `request to ${strippedHost}/${route} failed, reason: connect ECONNREFUSED ${BAD_HOST.replace( - 'http://', - '' - )}` + `Request to ${strippedHost}/${route} has failed` ) }) }) diff --git a/tests/documents.test.ts b/tests/documents.test.ts index 8ae96eac2..e3f8f7573 100644 --- a/tests/documents.test.ts +++ b/tests/documents.test.ts @@ -169,7 +169,7 @@ describe('Documents tests', () => { ) } catch (e: any) { expect(e.message).toEqual( - "Not Found\nHint: It might not be working because maybe you're not up to date with the Meilisearch version that getDocuments call requires." + "404: Not Found\nHint: It might not be working because maybe you're not up to date with the Meilisearch version that getDocuments call requires." ) } }) @@ -583,7 +583,7 @@ Hint: It might not be working because maybe you're not up to date with the Meili ) } catch (e: any) { expect(e.message).toEqual( - "Not Found\nHint: It might not be working because maybe you're not up to date with the Meilisearch version that deleteDocuments call requires." + "404: Not Found\nHint: It might not be working because maybe you're not up to date with the Meilisearch version that deleteDocuments call requires." ) } }) @@ -610,14 +610,14 @@ Hint: It might not be working because maybe you're not up to date with the Meili const client = await getClient(permission) await expect( client.index(indexNoPk.uid).getDocument(1) - ).rejects.toHaveProperty('code', ErrorStatusCode.DOCUMENT_NOT_FOUND) + ).rejects.toHaveProperty('cause.code', ErrorStatusCode.DOCUMENT_NOT_FOUND) }) test(`${permission} key: Try to get deleted document from index that has a primary key`, async () => { const client = await getClient(permission) await expect( client.index(indexPk.uid).getDocument(1) - ).rejects.toHaveProperty('code', ErrorStatusCode.DOCUMENT_NOT_FOUND) + ).rejects.toHaveProperty('cause.code', ErrorStatusCode.DOCUMENT_NOT_FOUND) }) test(`${permission} key: Add documents from index with no primary key by giving a primary key as parameter`, async () => { @@ -690,42 +690,42 @@ Hint: It might not be working because maybe you're not up to date with the Meili const client = await getClient(permission) await expect( client.index(indexPk.uid).addDocuments([]) - ).rejects.toHaveProperty('code', ErrorStatusCode.INVALID_API_KEY) + ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY) }) test(`${permission} key: Try to update documents and be denied`, async () => { const client = await getClient(permission) await expect( client.index(indexPk.uid).updateDocuments([]) - ).rejects.toHaveProperty('code', ErrorStatusCode.INVALID_API_KEY) + ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY) }) test(`${permission} key: Try to get documents and be denied`, async () => { const client = await getClient(permission) await expect( client.index(indexPk.uid).getDocuments() - ).rejects.toHaveProperty('code', ErrorStatusCode.INVALID_API_KEY) + ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY) }) test(`${permission} key: Try to delete one document and be denied`, async () => { const client = await getClient(permission) await expect( client.index(indexPk.uid).deleteDocument(1) - ).rejects.toHaveProperty('code', ErrorStatusCode.INVALID_API_KEY) + ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY) }) test(`${permission} key: Try to delete some documents and be denied`, async () => { const client = await getClient(permission) await expect( client.index(indexPk.uid).deleteDocuments([1, 2]) - ).rejects.toHaveProperty('code', ErrorStatusCode.INVALID_API_KEY) + ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY) }) test(`${permission} key: Try to delete all documents and be denied`, async () => { const client = await getClient(permission) await expect( client.index(indexPk.uid).deleteAllDocuments() - ).rejects.toHaveProperty('code', ErrorStatusCode.INVALID_API_KEY) + ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY) }) } ) @@ -742,7 +742,7 @@ Hint: It might not be working because maybe you're not up to date with the Meili await expect( client.index(indexPk.uid).addDocuments([]) ).rejects.toHaveProperty( - 'code', + 'cause.code', ErrorStatusCode.MISSING_AUTHORIZATION_HEADER ) }) @@ -752,7 +752,7 @@ Hint: It might not be working because maybe you're not up to date with the Meili await expect( client.index(indexPk.uid).updateDocuments([]) ).rejects.toHaveProperty( - 'code', + 'cause.code', ErrorStatusCode.MISSING_AUTHORIZATION_HEADER ) }) @@ -762,7 +762,7 @@ Hint: It might not be working because maybe you're not up to date with the Meili await expect( client.index(indexPk.uid).getDocuments() ).rejects.toHaveProperty( - 'code', + 'cause.code', ErrorStatusCode.MISSING_AUTHORIZATION_HEADER ) }) @@ -772,7 +772,7 @@ Hint: It might not be working because maybe you're not up to date with the Meili await expect( client.index(indexPk.uid).deleteDocument(1) ).rejects.toHaveProperty( - 'code', + 'cause.code', ErrorStatusCode.MISSING_AUTHORIZATION_HEADER ) }) @@ -782,7 +782,7 @@ Hint: It might not be working because maybe you're not up to date with the Meili await expect( client.index(indexPk.uid).deleteDocuments([1, 2]) ).rejects.toHaveProperty( - 'code', + 'cause.code', ErrorStatusCode.MISSING_AUTHORIZATION_HEADER ) }) @@ -792,7 +792,7 @@ Hint: It might not be working because maybe you're not up to date with the Meili await expect( client.index(indexPk.uid).deleteAllDocuments() ).rejects.toHaveProperty( - 'code', + 'cause.code', ErrorStatusCode.MISSING_AUTHORIZATION_HEADER ) }) @@ -812,10 +812,7 @@ Hint: It might not be working because maybe you're not up to date with the Meili client.index(indexPk.uid).getDocument(1) ).rejects.toHaveProperty( 'message', - `request to ${strippedHost}/${route} failed, reason: connect ECONNREFUSED ${BAD_HOST.replace( - 'http://', - '' - )}` + `Request to ${strippedHost}/${route} has failed` ) }) @@ -827,10 +824,7 @@ Hint: It might not be working because maybe you're not up to date with the Meili client.index(indexPk.uid).getDocuments() ).rejects.toHaveProperty( 'message', - `request to ${strippedHost}/${route} failed, reason: connect ECONNREFUSED ${BAD_HOST.replace( - 'http://', - '' - )}` + `Request to ${strippedHost}/${route} has failed` ) }) @@ -842,10 +836,7 @@ Hint: It might not be working because maybe you're not up to date with the Meili client.index(indexPk.uid).addDocuments([]) ).rejects.toHaveProperty( 'message', - `request to ${strippedHost}/${route} failed, reason: connect ECONNREFUSED ${BAD_HOST.replace( - 'http://', - '' - )}` + `Request to ${strippedHost}/${route} has failed` ) }) @@ -857,10 +848,7 @@ Hint: It might not be working because maybe you're not up to date with the Meili client.index(indexPk.uid).updateDocuments([]) ).rejects.toHaveProperty( 'message', - `request to ${strippedHost}/${route} failed, reason: connect ECONNREFUSED ${BAD_HOST.replace( - 'http://', - '' - )}` + `Request to ${strippedHost}/${route} has failed` ) }) @@ -872,10 +860,7 @@ Hint: It might not be working because maybe you're not up to date with the Meili client.index(indexPk.uid).deleteDocument('1') ).rejects.toHaveProperty( 'message', - `request to ${strippedHost}/${route} failed, reason: connect ECONNREFUSED ${BAD_HOST.replace( - 'http://', - '' - )}` + `Request to ${strippedHost}/${route} has failed` ) }) @@ -887,10 +872,7 @@ Hint: It might not be working because maybe you're not up to date with the Meili client.index(indexPk.uid).deleteDocuments([]) ).rejects.toHaveProperty( 'message', - `request to ${strippedHost}/${route} failed, reason: connect ECONNREFUSED ${BAD_HOST.replace( - 'http://', - '' - )}` + `Request to ${strippedHost}/${route} has failed` ) }) @@ -902,10 +884,7 @@ Hint: It might not be working because maybe you're not up to date with the Meili client.index(indexPk.uid).deleteAllDocuments() ).rejects.toHaveProperty( 'message', - `request to ${strippedHost}/${route} failed, reason: connect ECONNREFUSED ${BAD_HOST.replace( - 'http://', - '' - )}` + `Request to ${strippedHost}/${route} has failed` ) }) }) diff --git a/tests/dump.test.ts b/tests/dump.test.ts index ef25fc1ff..7cae4610d 100644 --- a/tests/dump.test.ts +++ b/tests/dump.test.ts @@ -29,7 +29,7 @@ describe.each([{ permission: 'Search' }])( test(`${permission} key: try to create dump with search key and be denied`, async () => { const client = await getClient(permission) await expect(client.createDump()).rejects.toHaveProperty( - 'code', + 'cause.code', ErrorStatusCode.INVALID_API_KEY ) }) @@ -42,7 +42,7 @@ describe.each([{ permission: 'No' }])( test(`${permission} key: try to create dump with no key and be denied`, async () => { const client = await getClient(permission) await expect(client.createDump()).rejects.toHaveProperty( - 'code', + 'cause.code', ErrorStatusCode.MISSING_AUTHORIZATION_HEADER ) }) @@ -61,10 +61,7 @@ describe.each([ await expect(client.createDump()).rejects.toHaveProperty( 'message', - `request to ${strippedHost}/${route} failed, reason: connect ECONNREFUSED ${BAD_HOST.replace( - 'http://', - '' - )}` + `Request to ${strippedHost}/${route} has failed` ) }) }) diff --git a/tests/embedders.test.ts b/tests/embedders.test.ts index 9573b64cc..efc12887d 100644 --- a/tests/embedders.test.ts +++ b/tests/embedders.test.ts @@ -119,7 +119,7 @@ describe.each([{ permission: 'Master' }, { permission: 'Admin' }])( const task: EnqueuedTask = await client .index(index.uid) .updateEmbedders(newEmbedder) - await client.waitForTask(task.taskUid) + await client.waitForTask(task.taskUid, {timeOutMs: 60_000}) const response: Embedders = await client.index(index.uid).getEmbedders() @@ -237,10 +237,7 @@ describe.each([ const strippedHost = trailing ? host.slice(0, -1) : host await expect(client.index(index.uid).getEmbedders()).rejects.toHaveProperty( 'message', - `request to ${strippedHost}/${route} failed, reason: connect ECONNREFUSED ${BAD_HOST.replace( - 'http://', - '' - )}` + `Request to ${strippedHost}/${route} has failed` ) }) @@ -252,10 +249,7 @@ describe.each([ client.index(index.uid).updateEmbedders({}) ).rejects.toHaveProperty( 'message', - `request to ${strippedHost}/${route} failed, reason: connect ECONNREFUSED ${BAD_HOST.replace( - 'http://', - '' - )}` + `Request to ${strippedHost}/${route} has failed` ) }) @@ -267,10 +261,7 @@ describe.each([ client.index(index.uid).resetEmbedders() ).rejects.toHaveProperty( 'message', - `request to ${strippedHost}/${route} failed, reason: connect ECONNREFUSED ${BAD_HOST.replace( - 'http://', - '' - )}` + `Request to ${strippedHost}/${route} has failed` ) }) }) diff --git a/tests/errors.test.ts b/tests/errors.test.ts index f3461eed4..5c986ed23 100644 --- a/tests/errors.test.ts +++ b/tests/errors.test.ts @@ -2,7 +2,7 @@ import { MeiliSearch } from './utils/meilisearch-test-utils' import { MeiliSearchError, MeiliSearchApiError, - MeiliSearchCommunicationError, + MeiliSearchRequestError, MeiliSearchTimeOutError, } from '../src/errors' import 'jest-fetch-mock' @@ -12,6 +12,7 @@ fetchMock.enableMocks() jest.setTimeout(100 * 1000) +// @TODO: Have to review this in more detail describe('Test on updates', () => { beforeEach(() => { fetchMock.mockReset() @@ -29,15 +30,12 @@ describe('Test on updates', () => { test(`Not throw MeiliSearchCommunicationError when throwned error is MeiliSearchApiError`, async () => { fetchMock.mockReject( - new MeiliSearchApiError( - { - message: 'Some error', - code: 'some_error', - type: 'random_error', - link: 'a link', - }, - 404 - ) + new MeiliSearchApiError(new Response(), { + message: 'Some error', + code: 'some_error', + type: 'random_error', + link: 'a link', + }) ) const client = new MeiliSearch({ host: 'http://localhost:9345' }) @@ -50,15 +48,12 @@ describe('Test on updates', () => { test('MeiliSearchApiError can be compared with the instanceof operator', async () => { fetchMock.mockReject( - new MeiliSearchApiError( - { - message: 'Some error', - code: 'some_error', - type: 'random_error', - link: 'a link', - }, - 404 - ) + new MeiliSearchApiError(new Response(), { + message: 'Some error', + code: 'some_error', + type: 'random_error', + link: 'a link', + }) ) const client = new MeiliSearch({ host: 'http://localhost:9345' }) @@ -75,7 +70,7 @@ describe('Test on updates', () => { try { await client.health() } catch (e: any) { - expect(e instanceof MeiliSearchCommunicationError).toEqual(true) + expect(e instanceof MeiliSearchRequestError).toEqual(true) } }) diff --git a/tests/facet_search.test.ts b/tests/facet_search.test.ts index e20866b1f..5d62a6f3a 100644 --- a/tests/facet_search.test.ts +++ b/tests/facet_search.test.ts @@ -95,6 +95,7 @@ describe.each([ } const response = await client.index(index.uid).searchForFacetValues(params) + // @TODO: This is flaky, processingTimeMs is not guaranteed expect(response).toMatchSnapshot() }) }) diff --git a/tests/faceting.test.ts b/tests/faceting.test.ts index 64457f55b..ab586a034 100644 --- a/tests/faceting.test.ts +++ b/tests/faceting.test.ts @@ -101,21 +101,21 @@ describe.each([{ permission: 'Search' }])( const client = await getClient(permission) await expect( client.index(index.uid).getFaceting() - ).rejects.toHaveProperty('code', ErrorStatusCode.INVALID_API_KEY) + ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY) }) test(`${permission} key: try to update faceting and be denied`, async () => { const client = await getClient(permission) await expect( client.index(index.uid).updateFaceting({ maxValuesPerFacet: 13 }) - ).rejects.toHaveProperty('code', ErrorStatusCode.INVALID_API_KEY) + ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY) }) test(`${permission} key: try to reset faceting and be denied`, async () => { const client = await getClient(permission) await expect( client.index(index.uid).resetFaceting() - ).rejects.toHaveProperty('code', ErrorStatusCode.INVALID_API_KEY) + ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY) }) } ) @@ -130,7 +130,7 @@ describe.each([{ permission: 'No' }])('Test on faceting', ({ permission }) => { test(`${permission} key: try to get faceting and be denied`, async () => { const client = await getClient(permission) await expect(client.index(index.uid).getFaceting()).rejects.toHaveProperty( - 'code', + 'cause.code', ErrorStatusCode.MISSING_AUTHORIZATION_HEADER ) }) @@ -140,7 +140,7 @@ describe.each([{ permission: 'No' }])('Test on faceting', ({ permission }) => { await expect( client.index(index.uid).updateFaceting({ maxValuesPerFacet: 13 }) ).rejects.toHaveProperty( - 'code', + 'cause.code', ErrorStatusCode.MISSING_AUTHORIZATION_HEADER ) }) @@ -150,7 +150,7 @@ describe.each([{ permission: 'No' }])('Test on faceting', ({ permission }) => { await expect( client.index(index.uid).resetFaceting() ).rejects.toHaveProperty( - 'code', + 'cause.code', ErrorStatusCode.MISSING_AUTHORIZATION_HEADER ) }) @@ -167,10 +167,7 @@ describe.each([ const strippedHost = trailing ? host.slice(0, -1) : host await expect(client.index(index.uid).getFaceting()).rejects.toHaveProperty( 'message', - `request to ${strippedHost}/${route} failed, reason: connect ECONNREFUSED ${BAD_HOST.replace( - 'http://', - '' - )}` + `Request to ${strippedHost}/${route} has failed` ) }) @@ -182,10 +179,7 @@ describe.each([ client.index(index.uid).updateFaceting({ maxValuesPerFacet: null }) ).rejects.toHaveProperty( 'message', - `request to ${strippedHost}/${route} failed, reason: connect ECONNREFUSED ${BAD_HOST.replace( - 'http://', - '' - )}` + `Request to ${strippedHost}/${route} has failed` ) }) @@ -197,10 +191,7 @@ describe.each([ client.index(index.uid).resetFaceting() ).rejects.toHaveProperty( 'message', - `request to ${strippedHost}/${route} failed, reason: connect ECONNREFUSED ${BAD_HOST.replace( - 'http://', - '' - )}` + `Request to ${strippedHost}/${route} has failed` ) }) }) diff --git a/tests/filterable_attributes.test.ts b/tests/filterable_attributes.test.ts index 826b6231f..ac5b17e73 100644 --- a/tests/filterable_attributes.test.ts +++ b/tests/filterable_attributes.test.ts @@ -91,21 +91,21 @@ describe.each([{ permission: 'Search' }])( const client = await getClient(permission) await expect( client.index(index.uid).getFilterableAttributes() - ).rejects.toHaveProperty('code', ErrorStatusCode.INVALID_API_KEY) + ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY) }) test(`${permission} key: try to update attributes for filtering and be denied`, async () => { const client = await getClient(permission) await expect( client.index(index.uid).updateFilterableAttributes([]) - ).rejects.toHaveProperty('code', ErrorStatusCode.INVALID_API_KEY) + ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY) }) test(`${permission} key: try to reset attributes for filtering and be denied`, async () => { const client = await getClient(permission) await expect( client.index(index.uid).resetFilterableAttributes() - ).rejects.toHaveProperty('code', ErrorStatusCode.INVALID_API_KEY) + ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY) }) } ) @@ -124,7 +124,7 @@ describe.each([{ permission: 'No' }])( await expect( client.index(index.uid).getFilterableAttributes() ).rejects.toHaveProperty( - 'code', + 'cause.code', ErrorStatusCode.MISSING_AUTHORIZATION_HEADER ) }) @@ -134,7 +134,7 @@ describe.each([{ permission: 'No' }])( await expect( client.index(index.uid).updateFilterableAttributes([]) ).rejects.toHaveProperty( - 'code', + 'cause.code', ErrorStatusCode.MISSING_AUTHORIZATION_HEADER ) }) @@ -144,7 +144,7 @@ describe.each([{ permission: 'No' }])( await expect( client.index(index.uid).resetFilterableAttributes() ).rejects.toHaveProperty( - 'code', + 'cause.code', ErrorStatusCode.MISSING_AUTHORIZATION_HEADER ) }) @@ -164,10 +164,7 @@ describe.each([ client.index(index.uid).getFilterableAttributes() ).rejects.toHaveProperty( 'message', - `request to ${strippedHost}/${route} failed, reason: connect ECONNREFUSED ${BAD_HOST.replace( - 'http://', - '' - )}` + `Request to ${strippedHost}/${route} has failed` ) }) @@ -179,10 +176,7 @@ describe.each([ client.index(index.uid).updateFilterableAttributes([]) ).rejects.toHaveProperty( 'message', - `request to ${strippedHost}/${route} failed, reason: connect ECONNREFUSED ${BAD_HOST.replace( - 'http://', - '' - )}` + `Request to ${strippedHost}/${route} has failed` ) }) @@ -194,10 +188,7 @@ describe.each([ client.index(index.uid).resetFilterableAttributes() ).rejects.toHaveProperty( 'message', - `request to ${strippedHost}/${route} failed, reason: connect ECONNREFUSED ${BAD_HOST.replace( - 'http://', - '' - )}` + `Request to ${strippedHost}/${route} has failed` ) }) }) diff --git a/tests/get_search.test.ts b/tests/get_search.test.ts index d8f53ac37..471058421 100644 --- a/tests/get_search.test.ts +++ b/tests/get_search.test.ts @@ -96,7 +96,8 @@ describe.each([ const response = await client.index(index.uid).searchGet('prince', {}) - expect(response).toHaveProperty('hits', expect.any(Array)) + expect(response).toHaveProperty('hits') + expect(Array.isArray(response.hits)) expect(response).toHaveProperty('limit', 20) expect(response).toHaveProperty('offset', 0) expect(response).toHaveProperty('processingTimeMs', expect.any(Number)) @@ -109,7 +110,8 @@ describe.each([ const response = await client .index(index.uid) .searchGet('prince', { limit: 1 }) - expect(response).toHaveProperty('hits', expect.any(Array)) + expect(response).toHaveProperty('hits') + expect(Array.isArray(response.hits)) expect(response).toHaveProperty('offset', 0) expect(response).toHaveProperty('limit', 1) expect(response).toHaveProperty('processingTimeMs', expect.any(Number)) @@ -122,7 +124,8 @@ describe.each([ const response = await client .index(index.uid) .search('', { sort: ['id:asc'] }) - expect(response).toHaveProperty('hits', expect.any(Array)) + expect(response).toHaveProperty('hits') + expect(Array.isArray(response.hits)) const hit = response.hits[0] expect(hit.id).toEqual(1) }) @@ -134,7 +137,8 @@ describe.each([ }) const hit = response.hits[0] - expect(response).toHaveProperty('hits', expect.any(Array)) + expect(response).toHaveProperty('hits') + expect(Array.isArray(response.hits)) expect(response).toHaveProperty('query', 'prince') expect(Object.keys(hit).join(',')).toEqual( Object.keys(dataset[1]).join(',') @@ -166,7 +170,8 @@ describe.each([ const response = await client .index(index.uid) .searchGet('prince', { limit: 1 }) - expect(response).toHaveProperty('hits', expect.any(Array)) + expect(response).toHaveProperty('hits') + expect(Array.isArray(response.hits)) expect(response).toHaveProperty('offset', 0) expect(response).toHaveProperty('limit', 1) expect(response).toHaveProperty('processingTimeMs', expect.any(Number)) @@ -203,7 +208,8 @@ describe.each([ cropLength: 5, showMatchesPosition: true, }) - expect(response).toHaveProperty('hits', expect.any(Array)) + expect(response).toHaveProperty('hits') + expect(Array.isArray(response.hits)) expect(response.hits[0]).toHaveProperty('_matchesPosition', { comment: [{ start: 22, length: 6 }], title: [{ start: 9, length: 6 }], @@ -223,7 +229,8 @@ describe.each([ showMatchesPosition: true, }) - expect(response).toHaveProperty('hits', expect.any(Array)) + expect(response).toHaveProperty('hits') + expect(Array.isArray(response.hits)) expect(response).toHaveProperty('offset', 0) expect(response).toHaveProperty('limit', 5) expect(response).toHaveProperty('processingTimeMs', expect.any(Number)) @@ -297,7 +304,8 @@ describe.each([ filter: 'title = "Le Petit Prince"', showMatchesPosition: true, }) - expect(response).toHaveProperty('hits', expect.any(Array)) + expect(response).toHaveProperty('hits') + expect(Array.isArray(response.hits)) expect(response).toHaveProperty('offset', 0) expect(response).toHaveProperty('limit', 5) expect(response).toHaveProperty('processingTimeMs', expect.any(Number)) @@ -326,7 +334,8 @@ describe.each([ filter: 'title = "Le Petit Prince"', showMatchesPosition: true, }) - expect(response).toHaveProperty('hits', expect.any(Array)) + expect(response).toHaveProperty('hits') + expect(Array.isArray(response.hits)) expect(response).toHaveProperty('offset', 0) expect(response).toHaveProperty('limit', 5) expect(response).toHaveProperty('processingTimeMs', expect.any(Number)) @@ -360,7 +369,8 @@ describe.each([ expect(response).toHaveProperty('facetDistribution', { genre: { romance: 2 }, }) - expect(response).toHaveProperty('hits', expect.any(Array)) + expect(response).toHaveProperty('hits') + expect(Array.isArray(response.hits)) expect(response.hits.length).toEqual(2) }) @@ -370,7 +380,8 @@ describe.each([ filter: 'id < 0', facets: ['genre'], }) - expect(response).toHaveProperty('hits', expect.any(Array)) + expect(response).toHaveProperty('hits') + expect(Array.isArray(response.hits)) expect(response.hits.length).toEqual(0) }) @@ -379,7 +390,8 @@ describe.each([ const response = await client.index(index.uid).searchGet('h', { filter: 'genre = "sci fi"', }) - expect(response).toHaveProperty('hits', expect.any(Array)) + expect(response).toHaveProperty('hits') + expect(Array.isArray(response.hits)) expect(response.hits.length).toEqual(1) }) @@ -392,7 +404,8 @@ describe.each([ expect(response).toHaveProperty('facetDistribution', { genre: { romance: 2 }, }) - expect(response).toHaveProperty('hits', expect.any(Array)) + expect(response).toHaveProperty('hits') + expect(Array.isArray(response.hits)) expect(response.hits.length).toEqual(2) }) @@ -495,7 +508,7 @@ describe.each([ await masterClient.waitForTask(taskUid) await expect( client.index(index.uid).searchGet('prince') - ).rejects.toHaveProperty('code', ErrorStatusCode.INDEX_NOT_FOUND) + ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INDEX_NOT_FOUND) }) }) @@ -510,10 +523,7 @@ describe.each([ const strippedHost = trailing ? host.slice(0, -1) : host await expect(client.index(index.uid).searchGet()).rejects.toHaveProperty( 'message', - `request to ${strippedHost}/${route} failed, reason: connect ECONNREFUSED ${BAD_HOST.replace( - 'http://', - '' - )}` + `Request to ${strippedHost}/${route} has failed` ) }) @@ -523,10 +533,7 @@ describe.each([ const strippedHost = trailing ? host.slice(0, -1) : host await expect(client.index(index.uid).searchGet()).rejects.toHaveProperty( 'message', - `request to ${strippedHost}/${route} failed, reason: connect ECONNREFUSED ${BAD_HOST.replace( - 'http://', - '' - )}` + `Request to ${strippedHost}/${route} has failed` ) }) }) diff --git a/tests/index.test.ts b/tests/index.test.ts index 24aaef38c..6ce76532f 100644 --- a/tests/index.test.ts +++ b/tests/index.test.ts @@ -88,7 +88,7 @@ describe.each([{ permission: 'Master' }, { permission: 'Admin' }])( test(`${permission} key: Get index that does not exist`, async () => { const client = await getClient(permission) await expect(client.getIndex('does_not_exist')).rejects.toHaveProperty( - 'code', + 'cause.code', ErrorStatusCode.INDEX_NOT_FOUND ) }) @@ -96,7 +96,7 @@ describe.each([{ permission: 'Master' }, { permission: 'Admin' }])( 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( - 'code', + 'cause.code', ErrorStatusCode.INDEX_NOT_FOUND ) }) @@ -329,7 +329,7 @@ describe.each([{ permission: 'Master' }, { permission: 'Admin' }])( const client = await getClient(permission) const index = client.index(indexNoPk.uid) await expect(index.getRawInfo()).rejects.toHaveProperty( - 'code', + 'cause.code', ErrorStatusCode.INDEX_NOT_FOUND ) }) @@ -337,7 +337,7 @@ describe.each([{ permission: 'Master' }, { permission: 'Admin' }])( 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( - 'code', + 'cause.code', ErrorStatusCode.INDEX_NOT_FOUND ) }) @@ -404,13 +404,13 @@ describe.each([{ permission: 'Search' }])( const client = await getClient(permission) await expect( client.index(indexNoPk.uid).getRawInfo() - ).rejects.toHaveProperty('code', ErrorStatusCode.INVALID_API_KEY) + ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY) }) 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( - 'code', + 'cause.code', ErrorStatusCode.INVALID_API_KEY ) }) @@ -418,7 +418,7 @@ describe.each([{ permission: 'Search' }])( 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( - 'code', + 'cause.code', ErrorStatusCode.INVALID_API_KEY ) }) @@ -427,13 +427,13 @@ describe.each([{ permission: 'Search' }])( const client = await getClient(permission) await expect( client.index(indexPk.uid).update({ primaryKey: indexPk.primaryKey }) - ).rejects.toHaveProperty('code', ErrorStatusCode.INVALID_API_KEY) + ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY) }) 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( - 'code', + 'cause.code', ErrorStatusCode.INVALID_API_KEY ) }) @@ -450,7 +450,7 @@ describe.each([{ permission: 'No' }])( test(`${permission} key: try to get all indexes and be denied`, async () => { const client = await getClient(permission) await expect(client.getIndexes()).rejects.toHaveProperty( - 'code', + 'cause.code', ErrorStatusCode.MISSING_AUTHORIZATION_HEADER ) }) @@ -460,7 +460,7 @@ describe.each([{ permission: 'No' }])( await expect( client.index(indexNoPk.uid).getRawInfo() ).rejects.toHaveProperty( - 'code', + 'cause.code', ErrorStatusCode.MISSING_AUTHORIZATION_HEADER ) }) @@ -468,7 +468,7 @@ describe.each([{ permission: 'No' }])( 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( - 'code', + 'cause.code', ErrorStatusCode.MISSING_AUTHORIZATION_HEADER ) }) @@ -476,7 +476,7 @@ describe.each([{ permission: 'No' }])( 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( - 'code', + 'cause.code', ErrorStatusCode.MISSING_AUTHORIZATION_HEADER ) }) @@ -486,7 +486,7 @@ describe.each([{ permission: 'No' }])( await expect( client.index(indexPk.uid).update({ primaryKey: indexPk.primaryKey }) ).rejects.toHaveProperty( - 'code', + 'cause.code', ErrorStatusCode.MISSING_AUTHORIZATION_HEADER ) }) @@ -504,10 +504,7 @@ describe.each([ const strippedHost = trailing ? host.slice(0, -1) : host await expect(client.index(indexPk.uid).getStats()).rejects.toHaveProperty( 'message', - `request to ${strippedHost}/${route} failed, reason: connect ECONNREFUSED ${BAD_HOST.replace( - 'http://', - '' - )}` + `Request to ${strippedHost}/${route} has failed` ) }) @@ -517,14 +514,11 @@ describe.each([ const strippedHost = trailing ? host.slice(0, -1) : host await expect(client.index(indexPk.uid).getRawInfo()).rejects.toHaveProperty( 'message', - `request to ${strippedHost}/${route} failed, reason: connect ECONNREFUSED ${BAD_HOST.replace( - 'http://', - '' - )}` + `Request to ${strippedHost}/${route} has failed` ) await expect(client.index(indexPk.uid).getRawInfo()).rejects.toHaveProperty( 'name', - 'MeiliSearchCommunicationError' + 'MeiliSearchRequestError' ) }) @@ -534,14 +528,11 @@ describe.each([ const strippedHost = trailing ? host.slice(0, -1) : host await expect(client.getRawIndex(indexPk.uid)).rejects.toHaveProperty( 'message', - `request to ${strippedHost}/${route} failed, reason: connect ECONNREFUSED ${BAD_HOST.replace( - 'http://', - '' - )}` + `Request to ${strippedHost}/${route} has failed` ) await expect(client.getRawIndex(indexPk.uid)).rejects.toHaveProperty( 'name', - 'MeiliSearchCommunicationError' + 'MeiliSearchRequestError' ) }) @@ -551,10 +542,7 @@ describe.each([ const strippedHost = trailing ? host.slice(0, -1) : host await expect(client.index(indexPk.uid).getRawInfo()).rejects.toHaveProperty( 'message', - `request to ${strippedHost}/${route} failed, reason: connect ECONNREFUSED ${BAD_HOST.replace( - 'http://', - '' - )}` + `Request to ${strippedHost}/${route} has failed` ) }) @@ -564,10 +552,7 @@ describe.each([ const strippedHost = trailing ? host.slice(0, -1) : host await expect(client.index(indexPk.uid).getRawInfo()).rejects.toHaveProperty( 'message', - `request to ${strippedHost}/${route} failed, reason: connect ECONNREFUSED ${BAD_HOST.replace( - 'http://', - '' - )}` + `Request to ${strippedHost}/${route} has failed` ) }) }) diff --git a/tests/keys.test.ts b/tests/keys.test.ts index 950b9b635..65fc22a9b 100644 --- a/tests/keys.test.ts +++ b/tests/keys.test.ts @@ -209,7 +209,7 @@ describe.each([{ permission: 'Search' }])( test(`${permission} key: get keys denied`, async () => { const client = await getClient(permission) await expect(client.getKeys()).rejects.toHaveProperty( - 'code', + 'cause.code', ErrorStatusCode.INVALID_API_KEY ) }) @@ -223,7 +223,7 @@ describe.each([{ permission: 'Search' }])( indexes: ['products'], expiresAt: null, }) - ).rejects.toHaveProperty('code', ErrorStatusCode.INVALID_API_KEY) + ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY) }) } ) @@ -234,7 +234,7 @@ describe.each([{ permission: 'No' }])( test(`${permission} key: get keys denied`, async () => { const client = await getClient(permission) await expect(client.getKeys()).rejects.toHaveProperty( - 'code', + 'cause.code', ErrorStatusCode.MISSING_AUTHORIZATION_HEADER ) }) @@ -249,7 +249,7 @@ describe.each([{ permission: 'No' }])( expiresAt: null, }) ).rejects.toHaveProperty( - 'code', + 'cause.code', ErrorStatusCode.MISSING_AUTHORIZATION_HEADER ) }) diff --git a/tests/non_separator_tokens.test.ts b/tests/non_separator_tokens.test.ts index 0037c2f30..8feebd97f 100644 --- a/tests/non_separator_tokens.test.ts +++ b/tests/non_separator_tokens.test.ts @@ -95,10 +95,7 @@ describe.each([ client.index(index.uid).getNonSeparatorTokens() ).rejects.toHaveProperty( 'message', - `request to ${strippedHost}/${route} failed, reason: connect ECONNREFUSED ${BAD_HOST.replace( - 'http://', - '' - )}` + `Request to ${strippedHost}/${route} has failed` ) }) @@ -110,10 +107,7 @@ describe.each([ client.index(index.uid).updateNonSeparatorTokens([]) ).rejects.toHaveProperty( 'message', - `request to ${strippedHost}/${route} failed, reason: connect ECONNREFUSED ${BAD_HOST.replace( - 'http://', - '' - )}` + `Request to ${strippedHost}/${route} has failed` ) }) @@ -125,10 +119,7 @@ describe.each([ client.index(index.uid).resetNonSeparatorTokens() ).rejects.toHaveProperty( 'message', - `request to ${strippedHost}/${route} failed, reason: connect ECONNREFUSED ${BAD_HOST.replace( - 'http://', - '' - )}` + `Request to ${strippedHost}/${route} has failed` ) }) }) diff --git a/tests/pagination.test.ts b/tests/pagination.test.ts index 8921f0f8e..160342835 100644 --- a/tests/pagination.test.ts +++ b/tests/pagination.test.ts @@ -93,21 +93,21 @@ describe.each([{ permission: 'Search' }])( const client = await getClient(permission) await expect( client.index(index.uid).getPagination() - ).rejects.toHaveProperty('code', ErrorStatusCode.INVALID_API_KEY) + ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY) }) test(`${permission} key: try to update pagination and be denied`, async () => { const client = await getClient(permission) await expect( client.index(index.uid).updatePagination({ maxTotalHits: 10 }) - ).rejects.toHaveProperty('code', ErrorStatusCode.INVALID_API_KEY) + ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY) }) test(`${permission} key: try to reset pagination and be denied`, async () => { const client = await getClient(permission) await expect( client.index(index.uid).resetPagination() - ).rejects.toHaveProperty('code', ErrorStatusCode.INVALID_API_KEY) + ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY) }) } ) @@ -126,7 +126,7 @@ describe.each([{ permission: 'No' }])( await expect( client.index(index.uid).getPagination() ).rejects.toHaveProperty( - 'code', + 'cause.code', ErrorStatusCode.MISSING_AUTHORIZATION_HEADER ) }) @@ -136,7 +136,7 @@ describe.each([{ permission: 'No' }])( await expect( client.index(index.uid).updatePagination({ maxTotalHits: 10 }) ).rejects.toHaveProperty( - 'code', + 'cause.code', ErrorStatusCode.MISSING_AUTHORIZATION_HEADER ) }) @@ -146,7 +146,7 @@ describe.each([{ permission: 'No' }])( await expect( client.index(index.uid).resetPagination() ).rejects.toHaveProperty( - 'code', + 'cause.code', ErrorStatusCode.MISSING_AUTHORIZATION_HEADER ) }) @@ -166,10 +166,7 @@ describe.each([ client.index(index.uid).getPagination() ).rejects.toHaveProperty( 'message', - `request to ${strippedHost}/${route} failed, reason: connect ECONNREFUSED ${BAD_HOST.replace( - 'http://', - '' - )}` + `Request to ${strippedHost}/${route} has failed` ) }) @@ -181,10 +178,7 @@ describe.each([ client.index(index.uid).updatePagination({ maxTotalHits: null }) ).rejects.toHaveProperty( 'message', - `request to ${strippedHost}/${route} failed, reason: connect ECONNREFUSED ${BAD_HOST.replace( - 'http://', - '' - )}` + `Request to ${strippedHost}/${route} has failed` ) }) @@ -196,10 +190,7 @@ describe.each([ client.index(index.uid).resetPagination() ).rejects.toHaveProperty( 'message', - `request to ${strippedHost}/${route} failed, reason: connect ECONNREFUSED ${BAD_HOST.replace( - 'http://', - '' - )}` + `Request to ${strippedHost}/${route} has failed` ) }) }) diff --git a/tests/proximity_precision.test.ts b/tests/proximity_precision.test.ts index 82e9d3afb..fe92844ce 100644 --- a/tests/proximity_precision.test.ts +++ b/tests/proximity_precision.test.ts @@ -95,10 +95,7 @@ describe.each([ client.index(index.uid).getProximityPrecision() ).rejects.toHaveProperty( 'message', - `request to ${strippedHost}/${route} failed, reason: connect ECONNREFUSED ${BAD_HOST.replace( - 'http://', - '' - )}` + `Request to ${strippedHost}/${route} has failed` ) }) @@ -110,10 +107,7 @@ describe.each([ client.index(index.uid).updateProximityPrecision('byAttribute') ).rejects.toHaveProperty( 'message', - `request to ${strippedHost}/${route} failed, reason: connect ECONNREFUSED ${BAD_HOST.replace( - 'http://', - '' - )}` + `Request to ${strippedHost}/${route} has failed` ) }) @@ -125,10 +119,7 @@ describe.each([ client.index(index.uid).resetProximityPrecision() ).rejects.toHaveProperty( 'message', - `request to ${strippedHost}/${route} failed, reason: connect ECONNREFUSED ${BAD_HOST.replace( - 'http://', - '' - )}` + `Request to ${strippedHost}/${route} has failed` ) }) }) diff --git a/tests/ranking_rules.test.ts b/tests/ranking_rules.test.ts index c611190ed..6cdb24126 100644 --- a/tests/ranking_rules.test.ts +++ b/tests/ranking_rules.test.ts @@ -94,21 +94,21 @@ describe.each([{ permission: 'Search' }])( const client = await getClient(permission) await expect( client.index(index.uid).getRankingRules() - ).rejects.toHaveProperty('code', ErrorStatusCode.INVALID_API_KEY) + ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY) }) test(`${permission} key: try to update ranking rules and be denied`, async () => { const client = await getClient(permission) await expect( client.index(index.uid).updateRankingRules([]) - ).rejects.toHaveProperty('code', ErrorStatusCode.INVALID_API_KEY) + ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY) }) test(`${permission} key: try to reset ranking rules and be denied`, async () => { const client = await getClient(permission) await expect( client.index(index.uid).resetRankingRules() - ).rejects.toHaveProperty('code', ErrorStatusCode.INVALID_API_KEY) + ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY) }) } ) @@ -125,7 +125,7 @@ describe.each([{ permission: 'No' }])( await expect( client.index(index.uid).getRankingRules() ).rejects.toHaveProperty( - 'code', + 'cause.code', ErrorStatusCode.MISSING_AUTHORIZATION_HEADER ) }) @@ -135,7 +135,7 @@ describe.each([{ permission: 'No' }])( await expect( client.index(index.uid).updateRankingRules([]) ).rejects.toHaveProperty( - 'code', + 'cause.code', ErrorStatusCode.MISSING_AUTHORIZATION_HEADER ) }) @@ -145,7 +145,7 @@ describe.each([{ permission: 'No' }])( await expect( client.index(index.uid).resetRankingRules() ).rejects.toHaveProperty( - 'code', + 'cause.code', ErrorStatusCode.MISSING_AUTHORIZATION_HEADER ) }) @@ -165,10 +165,7 @@ describe.each([ client.index(index.uid).getRankingRules() ).rejects.toHaveProperty( 'message', - `request to ${strippedHost}/${route} failed, reason: connect ECONNREFUSED ${BAD_HOST.replace( - 'http://', - '' - )}` + `Request to ${strippedHost}/${route} has failed` ) }) @@ -180,10 +177,7 @@ describe.each([ client.index(index.uid).updateRankingRules([]) ).rejects.toHaveProperty( 'message', - `request to ${strippedHost}/${route} failed, reason: connect ECONNREFUSED ${BAD_HOST.replace( - 'http://', - '' - )}` + `Request to ${strippedHost}/${route} has failed` ) }) @@ -195,10 +189,7 @@ describe.each([ client.index(index.uid).resetRankingRules() ).rejects.toHaveProperty( 'message', - `request to ${strippedHost}/${route} failed, reason: connect ECONNREFUSED ${BAD_HOST.replace( - 'http://', - '' - )}` + `Request to ${strippedHost}/${route} has failed` ) }) }) diff --git a/tests/search.test.ts b/tests/search.test.ts index 27aea8b27..3d7700d65 100644 --- a/tests/search.test.ts +++ b/tests/search.test.ts @@ -1,4 +1,3 @@ -import AbortController from 'abort-controller' import { ErrorStatusCode, MatchingStrategies } from '../src/types' import { EnqueuedTask } from '../src/enqueued-task' import { @@ -148,7 +147,8 @@ describe.each([ const client = await getClient(permission) const response = await client.index(index.uid).search('prince', {}) - expect(response).toHaveProperty('hits', expect.any(Array)) + expect(response).toHaveProperty('hits') + expect(Array.isArray(response.hits)) expect(response).toHaveProperty('limit', 20) expect(response).toHaveProperty('offset', 0) expect(response).toHaveProperty('processingTimeMs', expect.any(Number)) @@ -173,7 +173,8 @@ describe.each([ matchingStrategy: MatchingStrategies.ALL, }) - expect(response).toHaveProperty('hits', expect.any(Array)) + expect(response).toHaveProperty('hits') + expect(Array.isArray(response.hits)) expect(response).toHaveProperty('offset', 0) expect(response).toHaveProperty('limit', 20) expect(response.hits.length).toEqual(1) @@ -185,7 +186,8 @@ describe.each([ .index(index.uid) .search('french book', { matchingStrategy: MatchingStrategies.LAST }) - expect(response).toHaveProperty('hits', expect.any(Array)) + expect(response).toHaveProperty('hits') + expect(Array.isArray(response.hits)) expect(response).toHaveProperty('offset', 0) expect(response).toHaveProperty('limit', 20) expect(response.hits.length).toEqual(2) @@ -197,7 +199,8 @@ describe.each([ .index(index.uid) .search('other', { q: 'prince' }) - expect(response).toHaveProperty('hits', expect.any(Array)) + expect(response).toHaveProperty('hits') + expect(Array.isArray(response.hits)) expect(response).toHaveProperty('limit', 20) expect(response).toHaveProperty('offset', 0) expect(response.estimatedTotalHits).toBeDefined() @@ -210,7 +213,8 @@ describe.each([ const client = await getClient(permission) const response = await client.index(index.uid).search(null, { q: 'prince' }) - expect(response).toHaveProperty('hits', expect.any(Array)) + expect(response).toHaveProperty('hits') + expect(Array.isArray(response.hits)) expect(response).toHaveProperty('limit', 20) expect(response).toHaveProperty('offset', 0) expect(response.estimatedTotalHits).toBeDefined() @@ -224,7 +228,8 @@ describe.each([ const response = await client .index(index.uid) .search('"french book" about', {}) - expect(response).toHaveProperty('hits', expect.any(Array)) + expect(response).toHaveProperty('hits') + expect(Array.isArray(response.hits)) expect(response).toHaveProperty('limit', 20) expect(response).toHaveProperty('offset', 0) expect(response).toHaveProperty('processingTimeMs', expect.any(Number)) @@ -238,7 +243,8 @@ describe.each([ const response = await client .index(index.uid) .search('prince', { limit: 1 }) - expect(response).toHaveProperty('hits', expect.any(Array)) + expect(response).toHaveProperty('hits') + expect(Array.isArray(response.hits)) expect(response).toHaveProperty('offset', 0) expect(response).toHaveProperty('limit', 1) expect(response.estimatedTotalHits).toEqual(2) @@ -252,7 +258,8 @@ describe.each([ const response = await client .index(index.uid) .search('', { sort: ['id:asc'] }) - expect(response).toHaveProperty('hits', expect.any(Array)) + expect(response).toHaveProperty('hits') + expect(Array.isArray(response.hits)) const hit = response.hits[0] expect(hit.id).toEqual(1) }) @@ -266,7 +273,8 @@ describe.each([ const hit = response.hits[0] - expect(response).toHaveProperty('hits', expect.any(Array)) + expect(response).toHaveProperty('hits') + expect(Array.isArray(response.hits)) expect(response).toHaveProperty('query', 'prince') expect(hit).toHaveProperty('_rankingScore') }) @@ -280,7 +288,8 @@ describe.each([ const hit = response.hits[0] - expect(response).toHaveProperty('hits', expect.any(Array)) + expect(response).toHaveProperty('hits') + expect(Array.isArray(response.hits)) expect(response).toHaveProperty('query', 'prince') expect(hit).toHaveProperty('_rankingScoreDetails') expect(Object.keys(hit._rankingScoreDetails || {})).toEqual([ @@ -300,7 +309,8 @@ describe.each([ }) const hit = response.hits[0] - expect(response).toHaveProperty('hits', expect.any(Array)) + expect(response).toHaveProperty('hits') + expect(Array.isArray(response.hits)) expect(response).toHaveProperty('query', 'prince') expect(Object.keys(hit).join(',')).toEqual( Object.keys(dataset[1]).join(',') @@ -335,7 +345,8 @@ describe.each([ }) const hit = response.hits[0] - expect(response).toHaveProperty('hits', expect.any(Array)) + expect(response).toHaveProperty('hits') + expect(Array.isArray(response.hits)) expect(response).toHaveProperty('query', 'prince') expect(Object.keys(hit).join(',')).toEqual( Object.keys(dataset[1]).join(',') @@ -347,7 +358,8 @@ describe.each([ const response = await client .index(index.uid) .search('prince', { limit: 1 }) - expect(response).toHaveProperty('hits', expect.any(Array)) + expect(response).toHaveProperty('hits') + expect(Array.isArray(response.hits)) expect(response).toHaveProperty('offset', 0) expect(response).toHaveProperty('limit', 1) expect(response.estimatedTotalHits).toEqual(2) @@ -396,7 +408,8 @@ describe.each([ cropLength: 5, showMatchesPosition: true, }) - expect(response).toHaveProperty('hits', expect.any(Array)) + expect(response).toHaveProperty('hits') + expect(Array.isArray(response.hits)) expect(response.hits[0]).toHaveProperty('_matchesPosition', { comment: [{ start: 22, length: 6 }], title: [{ start: 9, length: 6 }], @@ -415,7 +428,8 @@ describe.each([ filter: 'title = "Le Petit Prince"', showMatchesPosition: true, }) - expect(response).toHaveProperty('hits', expect.any(Array)) + expect(response).toHaveProperty('hits') + expect(Array.isArray(response.hits)) expect(response).toHaveProperty('offset', 0) expect(response).toHaveProperty('limit', 5) expect(response.estimatedTotalHits).toEqual(1) @@ -490,7 +504,8 @@ describe.each([ filter: 'title = "Le Petit Prince"', showMatchesPosition: true, }) - expect(response).toHaveProperty('hits', expect.any(Array)) + expect(response).toHaveProperty('hits') + expect(Array.isArray(response.hits)) expect(response).toHaveProperty('offset', 0) expect(response).toHaveProperty('limit', 5) expect(response).toHaveProperty('processingTimeMs', expect.any(Number)) @@ -519,7 +534,8 @@ describe.each([ filter: 'title = "Le Petit Prince"', showMatchesPosition: true, }) - expect(response).toHaveProperty('hits', expect.any(Array)) + expect(response).toHaveProperty('hits') + expect(Array.isArray(response.hits)) expect(response).toHaveProperty('offset', 0) expect(response).toHaveProperty('limit', 5) expect(response).toHaveProperty('processingTimeMs', expect.any(Number)) @@ -578,7 +594,8 @@ describe.each([ expect(response.facetStats).toEqual({ id: { min: 2, max: 123 } }) expect(response.facetStats?.['id']?.max).toBe(123) - expect(response).toHaveProperty('hits', expect.any(Array)) + expect(response).toHaveProperty('hits') + expect(Array.isArray(response.hits)) expect(response.hits.length).toEqual(2) }) @@ -587,7 +604,8 @@ describe.each([ const response = await client.index(index.uid).search('a', { filter: 'id < 0', }) - expect(response).toHaveProperty('hits', expect.any(Array)) + expect(response).toHaveProperty('hits') + expect(Array.isArray(response.hits)) expect(response.hits.length).toEqual(0) }) @@ -597,7 +615,8 @@ describe.each([ filter: ['genre = "sci fi"'], }) - expect(response).toHaveProperty('hits', expect.any(Array)) + expect(response).toHaveProperty('hits') + expect(Array.isArray(response.hits)) expect(response.hits.length).toEqual(1) }) @@ -610,7 +629,8 @@ describe.each([ expect(response).toHaveProperty('facetDistribution', { genre: { romance: 2 }, }) - expect(response).toHaveProperty('hits', expect.any(Array)) + expect(response).toHaveProperty('hits') + expect(Array.isArray(response.hits)) expect(response.hits.length).toEqual(2) }) @@ -882,7 +902,7 @@ describe.each([ await expect( client.index(index.uid).search('prince', {}) - ).rejects.toHaveProperty('code', ErrorStatusCode.INDEX_NOT_FOUND) + ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INDEX_NOT_FOUND) }) }) @@ -900,7 +920,7 @@ describe.each([{ permission: 'No' }])( await expect( client.index(index.uid).search('prince') ).rejects.toHaveProperty( - 'code', + 'cause.code', ErrorStatusCode.MISSING_AUTHORIZATION_HEADER ) }) @@ -908,7 +928,7 @@ describe.each([{ permission: 'No' }])( test(`${permission} key: Try multi search and be denied`, async () => { const client = await getClient(permission) await expect(client.multiSearch({ queries: [] })).rejects.toHaveProperty( - 'code', + 'cause.code', ErrorStatusCode.MISSING_AUTHORIZATION_HEADER ) }) @@ -1017,7 +1037,7 @@ describe.each([ controller.abort() searchPromise.catch((error: any) => { - expect(error).toHaveProperty('message', 'The user aborted a request.') + expect(error).toHaveProperty('cause.message', 'This operation was aborted') }) }) @@ -1072,7 +1092,7 @@ describe.each([ }) searchBPromise.catch((error: any) => { - expect(error).toHaveProperty('message', 'The user aborted a request.') + expect(error).toHaveProperty('cause.message', 'This operation was aborted') }) }) @@ -1086,8 +1106,8 @@ describe.each([ try { await client.health() } catch (e: any) { - expect(e.message).toEqual('Error: Request Timed Out') - expect(e.name).toEqual('MeiliSearchCommunicationError') + expect(e.cause.message).toEqual('Error: Request Timed Out') + expect(e.name).toEqual('MeiliSearchRequestError') } }) }) @@ -1103,10 +1123,7 @@ describe.each([ const strippedHost = trailing ? host.slice(0, -1) : host await expect(client.index(index.uid).search()).rejects.toHaveProperty( 'message', - `request to ${strippedHost}/${route} failed, reason: connect ECONNREFUSED ${BAD_HOST.replace( - 'http://', - '' - )}` + `Request to ${strippedHost}/${route} has failed` ) }) @@ -1116,10 +1133,7 @@ describe.each([ const strippedHost = trailing ? host.slice(0, -1) : host await expect(client.index(index.uid).search()).rejects.toHaveProperty( 'message', - `request to ${strippedHost}/${route} failed, reason: connect ECONNREFUSED ${BAD_HOST.replace( - 'http://', - '' - )}` + `Request to ${strippedHost}/${route} has failed` ) }) }) diff --git a/tests/searchCutoffMs.ts b/tests/searchCutoffMs.ts index b0cb391aa..ec4206f3c 100644 --- a/tests/searchCutoffMs.ts +++ b/tests/searchCutoffMs.ts @@ -70,7 +70,7 @@ describe.each([{ permission: 'Master' }, { permission: 'Admin' }])( await expect( client.index(index.uid).updateSearchCutoffMs(newSearchCutoffMs) ).rejects.toHaveProperty( - 'code', + 'cause.code', ErrorStatusCode.INVALID_SETTINGS_SEARCH_CUTOFF_MS ) }) @@ -105,21 +105,21 @@ describe.each([{ permission: 'Search' }])( const client = await getClient(permission) await expect( client.index(index.uid).getSearchCutoffMs() - ).rejects.toHaveProperty('code', ErrorStatusCode.INVALID_API_KEY) + ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY) }) test(`${permission} key: try to update searchCutoffMs and be denied`, async () => { const client = await getClient(permission) await expect( client.index(index.uid).updateSearchCutoffMs(100) - ).rejects.toHaveProperty('code', ErrorStatusCode.INVALID_API_KEY) + ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY) }) test(`${permission} key: try to reset searchCutoffMs and be denied`, async () => { const client = await getClient(permission) await expect( client.index(index.uid).resetSearchCutoffMs() - ).rejects.toHaveProperty('code', ErrorStatusCode.INVALID_API_KEY) + ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY) }) } ) @@ -138,7 +138,7 @@ describe.each([{ permission: 'No' }])( await expect( client.index(index.uid).getSearchCutoffMs() ).rejects.toHaveProperty( - 'code', + 'cause.code', ErrorStatusCode.MISSING_AUTHORIZATION_HEADER ) }) @@ -148,7 +148,7 @@ describe.each([{ permission: 'No' }])( await expect( client.index(index.uid).updateSearchCutoffMs(100) ).rejects.toHaveProperty( - 'code', + 'cause.code', ErrorStatusCode.MISSING_AUTHORIZATION_HEADER ) }) @@ -158,7 +158,7 @@ describe.each([{ permission: 'No' }])( await expect( client.index(index.uid).resetSearchCutoffMs() ).rejects.toHaveProperty( - 'code', + 'cause.code', ErrorStatusCode.MISSING_AUTHORIZATION_HEADER ) }) @@ -178,10 +178,7 @@ describe.each([ client.index(index.uid).getSearchCutoffMs() ).rejects.toHaveProperty( 'message', - `request to ${strippedHost}/${route} failed, reason: connect ECONNREFUSED ${BAD_HOST.replace( - 'http://', - '' - )}` + `Request to ${strippedHost}/${route} has failed` ) }) @@ -193,10 +190,7 @@ describe.each([ client.index(index.uid).updateSearchCutoffMs(null) ).rejects.toHaveProperty( 'message', - `request to ${strippedHost}/${route} failed, reason: connect ECONNREFUSED ${BAD_HOST.replace( - 'http://', - '' - )}` + `Request to ${strippedHost}/${route} has failed` ) }) @@ -208,10 +202,7 @@ describe.each([ client.index(index.uid).resetSearchCutoffMs() ).rejects.toHaveProperty( 'message', - `request to ${strippedHost}/${route} failed, reason: connect ECONNREFUSED ${BAD_HOST.replace( - 'http://', - '' - )}` + `Request to ${strippedHost}/${route} has failed` ) }) }) diff --git a/tests/searchable_attributes.test.ts b/tests/searchable_attributes.test.ts index 05642617d..e546b9996 100644 --- a/tests/searchable_attributes.test.ts +++ b/tests/searchable_attributes.test.ts @@ -93,21 +93,21 @@ describe.each([{ permission: 'Search' }])( const client = await getClient(permission) await expect( client.index(index.uid).getSearchableAttributes() - ).rejects.toHaveProperty('code', ErrorStatusCode.INVALID_API_KEY) + ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY) }) test(`${permission} key: try to update searchable attributes and be denied`, async () => { const client = await getClient(permission) await expect( client.index(index.uid).updateSearchableAttributes([]) - ).rejects.toHaveProperty('code', ErrorStatusCode.INVALID_API_KEY) + ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY) }) test(`${permission} key: try to reset searchable attributes and be denied`, async () => { const client = await getClient(permission) await expect( client.index(index.uid).resetSearchableAttributes() - ).rejects.toHaveProperty('code', ErrorStatusCode.INVALID_API_KEY) + ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY) }) } ) @@ -126,7 +126,7 @@ describe.each([{ permission: 'No' }])( await expect( client.index(index.uid).getSearchableAttributes() ).rejects.toHaveProperty( - 'code', + 'cause.code', ErrorStatusCode.MISSING_AUTHORIZATION_HEADER ) }) @@ -136,7 +136,7 @@ describe.each([{ permission: 'No' }])( await expect( client.index(index.uid).updateSearchableAttributes([]) ).rejects.toHaveProperty( - 'code', + 'cause.code', ErrorStatusCode.MISSING_AUTHORIZATION_HEADER ) }) @@ -146,7 +146,7 @@ describe.each([{ permission: 'No' }])( await expect( client.index(index.uid).resetSearchableAttributes() ).rejects.toHaveProperty( - 'code', + 'cause.code', ErrorStatusCode.MISSING_AUTHORIZATION_HEADER ) }) @@ -166,10 +166,7 @@ describe.each([ client.index(index.uid).getSearchableAttributes() ).rejects.toHaveProperty( 'message', - `request to ${strippedHost}/${route} failed, reason: connect ECONNREFUSED ${BAD_HOST.replace( - 'http://', - '' - )}` + `Request to ${strippedHost}/${route} has failed` ) }) @@ -181,10 +178,7 @@ describe.each([ client.index(index.uid).updateSearchableAttributes([]) ).rejects.toHaveProperty( 'message', - `request to ${strippedHost}/${route} failed, reason: connect ECONNREFUSED ${BAD_HOST.replace( - 'http://', - '' - )}` + `Request to ${strippedHost}/${route} has failed` ) }) @@ -196,10 +190,7 @@ describe.each([ client.index(index.uid).resetSearchableAttributes() ).rejects.toHaveProperty( 'message', - `request to ${strippedHost}/${route} failed, reason: connect ECONNREFUSED ${BAD_HOST.replace( - 'http://', - '' - )}` + `Request to ${strippedHost}/${route} has failed` ) }) }) diff --git a/tests/separator_tokens.test.ts b/tests/separator_tokens.test.ts index ebb0f455b..c23f88c64 100644 --- a/tests/separator_tokens.test.ts +++ b/tests/separator_tokens.test.ts @@ -95,10 +95,7 @@ describe.each([ client.index(index.uid).getSeparatorTokens() ).rejects.toHaveProperty( 'message', - `request to ${strippedHost}/${route} failed, reason: connect ECONNREFUSED ${BAD_HOST.replace( - 'http://', - '' - )}` + `Request to ${strippedHost}/${route} has failed` ) }) @@ -110,10 +107,7 @@ describe.each([ client.index(index.uid).updateSeparatorTokens([]) ).rejects.toHaveProperty( 'message', - `request to ${strippedHost}/${route} failed, reason: connect ECONNREFUSED ${BAD_HOST.replace( - 'http://', - '' - )}` + `Request to ${strippedHost}/${route} has failed` ) }) @@ -125,10 +119,7 @@ describe.each([ client.index(index.uid).resetSeparatorTokens() ).rejects.toHaveProperty( 'message', - `request to ${strippedHost}/${route} failed, reason: connect ECONNREFUSED ${BAD_HOST.replace( - 'http://', - '' - )}` + `Request to ${strippedHost}/${route} has failed` ) }) }) diff --git a/tests/settings.test.ts b/tests/settings.test.ts index 964c267ed..9834bd5be 100644 --- a/tests/settings.test.ts +++ b/tests/settings.test.ts @@ -280,19 +280,19 @@ describe.each([{ permission: 'Search' }])( const client = await getClient(permission) await expect( client.index(index.uid).getSettings() - ).rejects.toHaveProperty('code', ErrorStatusCode.INVALID_API_KEY) + ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY) }) test(`${permission} key: try to update settings and be denied`, async () => { const client = await getClient(permission) await expect( client.index(index.uid).updateSettings({}) - ).rejects.toHaveProperty('code', ErrorStatusCode.INVALID_API_KEY) + ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY) }) test(`${permission} key: try to reset settings and be denied`, async () => { const client = await getClient(permission) await expect( client.index(index.uid).resetSettings() - ).rejects.toHaveProperty('code', ErrorStatusCode.INVALID_API_KEY) + ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY) }) } ) @@ -304,7 +304,7 @@ describe.each([{ permission: 'No' }])('Test on settings', ({ permission }) => { test(`${permission} key: try to get settings and be denied`, async () => { const client = await getClient(permission) await expect(client.index(index.uid).getSettings()).rejects.toHaveProperty( - 'code', + 'cause.code', ErrorStatusCode.MISSING_AUTHORIZATION_HEADER ) }) @@ -313,7 +313,7 @@ describe.each([{ permission: 'No' }])('Test on settings', ({ permission }) => { await expect( client.index(index.uid).updateSettings({}) ).rejects.toHaveProperty( - 'code', + 'cause.code', ErrorStatusCode.MISSING_AUTHORIZATION_HEADER ) }) @@ -322,7 +322,7 @@ describe.each([{ permission: 'No' }])('Test on settings', ({ permission }) => { await expect( client.index(index.uid).resetSettings() ).rejects.toHaveProperty( - 'code', + 'cause.code', ErrorStatusCode.MISSING_AUTHORIZATION_HEADER ) }) @@ -339,10 +339,7 @@ describe.each([ const strippedHost = trailing ? host.slice(0, -1) : host await expect(client.index(index.uid).getSettings()).rejects.toHaveProperty( 'message', - `request to ${strippedHost}/${route} failed, reason: connect ECONNREFUSED ${BAD_HOST.replace( - 'http://', - '' - )}` + `Request to ${strippedHost}/${route} has failed` ) }) @@ -354,10 +351,7 @@ describe.each([ client.index(index.uid).updateSettings({}) ).rejects.toHaveProperty( 'message', - `request to ${strippedHost}/${route} failed, reason: connect ECONNREFUSED ${BAD_HOST.replace( - 'http://', - '' - )}` + `Request to ${strippedHost}/${route} has failed` ) }) @@ -369,10 +363,7 @@ describe.each([ client.index(index.uid).resetSettings() ).rejects.toHaveProperty( 'message', - `request to ${strippedHost}/${route} failed, reason: connect ECONNREFUSED ${BAD_HOST.replace( - 'http://', - '' - )}` + `Request to ${strippedHost}/${route} has failed` ) }) }) diff --git a/tests/snapshots.test.ts b/tests/snapshots.test.ts index b77e20bf7..8ed7d8aac 100644 --- a/tests/snapshots.test.ts +++ b/tests/snapshots.test.ts @@ -29,7 +29,7 @@ describe.each([{ permission: 'Search' }])( test(`${permission} key: try to create snapshot with search key and be denied`, async () => { const client = await getClient(permission) await expect(client.createSnapshot()).rejects.toHaveProperty( - 'code', + 'cause.code', ErrorStatusCode.INVALID_API_KEY ) }) @@ -42,7 +42,7 @@ describe.each([{ permission: 'No' }])( test(`${permission} key: try to create snapshot with no key and be denied`, async () => { const client = await getClient(permission) await expect(client.createSnapshot()).rejects.toHaveProperty( - 'code', + 'cause.code', ErrorStatusCode.MISSING_AUTHORIZATION_HEADER ) }) @@ -61,10 +61,7 @@ describe.each([ await expect(client.createSnapshot()).rejects.toHaveProperty( 'message', - `request to ${strippedHost}/${route} failed, reason: connect ECONNREFUSED ${BAD_HOST.replace( - 'http://', - '' - )}` + `Request to ${strippedHost}/${route} has failed` ) }) }) diff --git a/tests/sortable_attributes.test.ts b/tests/sortable_attributes.test.ts index aa1e62eac..13cb2f5b5 100644 --- a/tests/sortable_attributes.test.ts +++ b/tests/sortable_attributes.test.ts @@ -87,21 +87,21 @@ describe.each([{ permission: 'Search' }])( const client = await getClient(permission) await expect( client.index(index.uid).getSortableAttributes() - ).rejects.toHaveProperty('code', ErrorStatusCode.INVALID_API_KEY) + ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY) }) test(`${permission} key: try to update sortable attributes and be denied`, async () => { const client = await getClient(permission) await expect( client.index(index.uid).updateSortableAttributes([]) - ).rejects.toHaveProperty('code', ErrorStatusCode.INVALID_API_KEY) + ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY) }) test(`${permission} key: try to reset sortable attributes and be denied`, async () => { const client = await getClient(permission) await expect( client.index(index.uid).resetSortableAttributes() - ).rejects.toHaveProperty('code', ErrorStatusCode.INVALID_API_KEY) + ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY) }) } ) @@ -120,7 +120,7 @@ describe.each([{ permission: 'No' }])( await expect( client.index(index.uid).getSortableAttributes() ).rejects.toHaveProperty( - 'code', + 'cause.code', ErrorStatusCode.MISSING_AUTHORIZATION_HEADER ) }) @@ -131,7 +131,7 @@ describe.each([{ permission: 'No' }])( await expect( client.index(index.uid).updateSortableAttributes(resetSortable) ).rejects.toHaveProperty( - 'code', + 'cause.code', ErrorStatusCode.MISSING_AUTHORIZATION_HEADER ) }) @@ -141,7 +141,7 @@ describe.each([{ permission: 'No' }])( await expect( client.index(index.uid).resetSortableAttributes() ).rejects.toHaveProperty( - 'code', + 'cause.code', ErrorStatusCode.MISSING_AUTHORIZATION_HEADER ) }) @@ -161,10 +161,7 @@ describe.each([ client.index(index.uid).getSortableAttributes() ).rejects.toHaveProperty( 'message', - `request to ${strippedHost}/${route} failed, reason: connect ECONNREFUSED ${BAD_HOST.replace( - 'http://', - '' - )}` + `Request to ${strippedHost}/${route} has failed` ) }) @@ -176,10 +173,7 @@ describe.each([ client.index(index.uid).updateSortableAttributes([]) ).rejects.toHaveProperty( 'message', - `request to ${strippedHost}/${route} failed, reason: connect ECONNREFUSED ${BAD_HOST.replace( - 'http://', - '' - )}` + `Request to ${strippedHost}/${route} has failed` ) }) @@ -191,10 +185,7 @@ describe.each([ client.index(index.uid).resetSortableAttributes() ).rejects.toHaveProperty( 'message', - `request to ${strippedHost}/${route} failed, reason: connect ECONNREFUSED ${BAD_HOST.replace( - 'http://', - '' - )}` + `Request to ${strippedHost}/${route} has failed` ) }) }) diff --git a/tests/stop_words.test.ts b/tests/stop_words.test.ts index 1dbff0897..8eb923af4 100644 --- a/tests/stop_words.test.ts +++ b/tests/stop_words.test.ts @@ -84,21 +84,21 @@ describe.each([{ permission: 'Search' }])( const client = await getClient(permission) await expect( client.index(index.uid).getStopWords() - ).rejects.toHaveProperty('code', ErrorStatusCode.INVALID_API_KEY) + ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY) }) test(`${permission} key: try to update stop words and be denied`, async () => { const client = await getClient(permission) await expect( client.index(index.uid).updateStopWords([]) - ).rejects.toHaveProperty('code', ErrorStatusCode.INVALID_API_KEY) + ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY) }) test(`${permission} key: try to reset stop words and be denied`, async () => { const client = await getClient(permission) await expect( client.index(index.uid).resetStopWords() - ).rejects.toHaveProperty('code', ErrorStatusCode.INVALID_API_KEY) + ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY) }) } ) @@ -115,7 +115,7 @@ describe.each([{ permission: 'No' }])( await expect( client.index(index.uid).getStopWords() ).rejects.toHaveProperty( - 'code', + 'cause.code', ErrorStatusCode.MISSING_AUTHORIZATION_HEADER ) }) @@ -125,7 +125,7 @@ describe.each([{ permission: 'No' }])( await expect( client.index(index.uid).updateStopWords([]) ).rejects.toHaveProperty( - 'code', + 'cause.code', ErrorStatusCode.MISSING_AUTHORIZATION_HEADER ) }) @@ -135,7 +135,7 @@ describe.each([{ permission: 'No' }])( await expect( client.index(index.uid).resetStopWords() ).rejects.toHaveProperty( - 'code', + 'cause.code', ErrorStatusCode.MISSING_AUTHORIZATION_HEADER ) }) @@ -153,10 +153,7 @@ describe.each([ const strippedHost = trailing ? host.slice(0, -1) : host await expect(client.index(index.uid).getStopWords()).rejects.toHaveProperty( 'message', - `request to ${strippedHost}/${route} failed, reason: connect ECONNREFUSED ${BAD_HOST.replace( - 'http://', - '' - )}` + `Request to ${strippedHost}/${route} has failed` ) }) @@ -168,10 +165,7 @@ describe.each([ client.index(index.uid).updateStopWords([]) ).rejects.toHaveProperty( 'message', - `request to ${strippedHost}/${route} failed, reason: connect ECONNREFUSED ${BAD_HOST.replace( - 'http://', - '' - )}` + `Request to ${strippedHost}/${route} has failed` ) }) @@ -183,10 +177,7 @@ describe.each([ client.index(index.uid).resetStopWords() ).rejects.toHaveProperty( 'message', - `request to ${strippedHost}/${route} failed, reason: connect ECONNREFUSED ${BAD_HOST.replace( - 'http://', - '' - )}` + `Request to ${strippedHost}/${route} has failed` ) }) }) diff --git a/tests/synonyms.test.ts b/tests/synonyms.test.ts index aa4be52bd..4a8cec4f5 100644 --- a/tests/synonyms.test.ts +++ b/tests/synonyms.test.ts @@ -81,21 +81,21 @@ describe.each([{ permission: 'Search' }])( const client = await getClient(permission) await expect( client.index(index.uid).getSynonyms() - ).rejects.toHaveProperty('code', ErrorStatusCode.INVALID_API_KEY) + ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY) }) test(`${permission} key: try to update synonyms and be denied`, async () => { const client = await getClient(permission) await expect( client.index(index.uid).updateSynonyms({}) - ).rejects.toHaveProperty('code', ErrorStatusCode.INVALID_API_KEY) + ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY) }) test(`${permission} key: try to reset synonyms and be denied`, async () => { const client = await getClient(permission) await expect( client.index(index.uid).resetSynonyms() - ).rejects.toHaveProperty('code', ErrorStatusCode.INVALID_API_KEY) + ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY) }) } ) @@ -108,7 +108,7 @@ describe.each([{ permission: 'No' }])('Test on synonyms', ({ permission }) => { test(`${permission} key: try to get synonyms and be denied`, async () => { const client = await getClient(permission) await expect(client.index(index.uid).getSynonyms()).rejects.toHaveProperty( - 'code', + 'cause.code', ErrorStatusCode.MISSING_AUTHORIZATION_HEADER ) }) @@ -118,7 +118,7 @@ describe.each([{ permission: 'No' }])('Test on synonyms', ({ permission }) => { await expect( client.index(index.uid).updateSynonyms({}) ).rejects.toHaveProperty( - 'code', + 'cause.code', ErrorStatusCode.MISSING_AUTHORIZATION_HEADER ) }) @@ -128,7 +128,7 @@ describe.each([{ permission: 'No' }])('Test on synonyms', ({ permission }) => { await expect( client.index(index.uid).resetSynonyms() ).rejects.toHaveProperty( - 'code', + 'cause.code', ErrorStatusCode.MISSING_AUTHORIZATION_HEADER ) }) @@ -145,10 +145,7 @@ describe.each([ const strippedHost = trailing ? host.slice(0, -1) : host await expect(client.index(index.uid).getSynonyms()).rejects.toHaveProperty( 'message', - `request to ${strippedHost}/${route} failed, reason: connect ECONNREFUSED ${BAD_HOST.replace( - 'http://', - '' - )}` + `Request to ${strippedHost}/${route} has failed` ) }) @@ -160,10 +157,7 @@ describe.each([ client.index(index.uid).updateSynonyms({}) ).rejects.toHaveProperty( 'message', - `request to ${strippedHost}/${route} failed, reason: connect ECONNREFUSED ${BAD_HOST.replace( - 'http://', - '' - )}` + `Request to ${strippedHost}/${route} has failed` ) }) @@ -175,10 +169,7 @@ describe.each([ client.index(index.uid).resetSynonyms() ).rejects.toHaveProperty( 'message', - `request to ${strippedHost}/${route} failed, reason: connect ECONNREFUSED ${BAD_HOST.replace( - 'http://', - '' - )}` + `Request to ${strippedHost}/${route} has failed` ) }) }) diff --git a/tests/task.test.ts b/tests/task.test.ts index 0ab50efc4..2622cf095 100644 --- a/tests/task.test.ts +++ b/tests/task.test.ts @@ -377,7 +377,7 @@ describe.each([{ permission: 'Master' }, { permission: 'Admin' }])( await expect( // @ts-expect-error testing wrong argument type client.getTasks({ types: ['wrong'] }) - ).rejects.toHaveProperty('code', ErrorStatusCode.INVALID_TASK_TYPES) + ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_TASK_TYPES) }) // filters error code: INVALID_TASK_STATUSES_FILTER @@ -387,7 +387,7 @@ describe.each([{ permission: 'Master' }, { permission: 'Admin' }])( await expect( // @ts-expect-error testing wrong argument type client.getTasks({ statuses: ['wrong'] }) - ).rejects.toHaveProperty('code', ErrorStatusCode.INVALID_TASK_STATUSES) + ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_TASK_STATUSES) }) // filters error code: INVALID_TASK_UIDS_FILTER @@ -397,7 +397,7 @@ describe.each([{ permission: 'Master' }, { permission: 'Admin' }])( await expect( // @ts-expect-error testing wrong argument type client.getTasks({ uids: ['wrong'] }) - ).rejects.toHaveProperty('code', ErrorStatusCode.INVALID_TASK_UIDS) + ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_TASK_UIDS) }) // filters error code: INVALID_TASK_CANCELED_BY_FILTER @@ -407,7 +407,7 @@ describe.each([{ permission: 'Master' }, { permission: 'Admin' }])( await expect( // @ts-expect-error testing wrong canceledBy type client.getTasks({ canceledBy: ['wrong'] }) - ).rejects.toHaveProperty('code', ErrorStatusCode.INVALID_TASK_CANCELED_BY) + ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_TASK_CANCELED_BY) }) // filters error code: INVALID_TASK_DATE_FILTER @@ -418,7 +418,7 @@ describe.each([{ permission: 'Master' }, { permission: 'Admin' }])( // @ts-expect-error testing wrong date format client.getTasks({ beforeEnqueuedAt: 'wrong' }) ).rejects.toHaveProperty( - 'code', + 'cause.code', ErrorStatusCode.INVALID_TASK_BEFORE_ENQUEUED_AT ) }) @@ -584,7 +584,7 @@ describe.each([{ permission: 'Master' }, { permission: 'Admin' }])( await expect( // @ts-expect-error testing wrong argument type client.cancelTasks() - ).rejects.toHaveProperty('code', ErrorStatusCode.MISSING_TASK_FILTERS) + ).rejects.toHaveProperty('cause.code', ErrorStatusCode.MISSING_TASK_FILTERS) }) // delete: uid @@ -602,7 +602,7 @@ describe.each([{ permission: 'Master' }, { permission: 'Admin' }])( expect(deleteTask.type).toEqual(TaskTypes.TASK_DELETION) expect(task.details?.deletedTasks).toBeDefined() await expect(client.getTask(addDocuments.taskUid)).rejects.toHaveProperty( - 'code', + 'cause.code', ErrorStatusCode.TASK_NOT_FOUND ) }) @@ -621,7 +621,7 @@ describe.each([{ permission: 'Master' }, { permission: 'Admin' }])( expect(deleteTask.type).toEqual(TaskTypes.TASK_DELETION) await expect(client.getTask(addDocuments.taskUid)).rejects.toHaveProperty( - 'code', + 'cause.code', ErrorStatusCode.TASK_NOT_FOUND ) }) @@ -766,7 +766,7 @@ describe.each([{ permission: 'Master' }, { permission: 'Admin' }])( const client = await getClient(permission) await expect(client.getTask(254500)).rejects.toHaveProperty( - 'code', + 'cause.code', ErrorStatusCode.TASK_NOT_FOUND ) }) @@ -781,7 +781,7 @@ describe.each([{ permission: 'Search' }])('Test on tasks', ({ permission }) => { test(`${permission} key: Try to get a task and be denied`, async () => { const client = await getClient(permission) await expect(client.getTask(0)).rejects.toHaveProperty( - 'code', + 'cause.code', ErrorStatusCode.INVALID_API_KEY ) }) @@ -795,7 +795,7 @@ describe.each([{ permission: 'No' }])('Test on tasks', ({ permission }) => { test(`${permission} key: Try to get an task and be denied`, async () => { const client = await getClient(permission) await expect(client.getTask(0)).rejects.toHaveProperty( - 'code', + 'cause.code', ErrorStatusCode.MISSING_AUTHORIZATION_HEADER ) }) @@ -813,10 +813,7 @@ describe.each([ await expect(client.index(index.uid).getTask(1)).rejects.toHaveProperty( 'message', - `request to ${strippedHost}/${route} failed, reason: connect ECONNREFUSED ${BAD_HOST.replace( - 'http://', - '' - )}` + `Request to ${strippedHost}/${route} has failed` ) }) @@ -827,10 +824,7 @@ describe.each([ await expect(client.index(index.uid).getTasks()).rejects.toHaveProperty( 'message', - `request to ${strippedHost}/${route} failed, reason: connect ECONNREFUSED ${BAD_HOST.replace( - 'http://', - '' - )}` + `Request to ${strippedHost}/${route} has failed` ) }) }) diff --git a/tests/token.test.ts b/tests/token.test.ts index 87963ea27..4c81d9248 100644 --- a/tests/token.test.ts +++ b/tests/token.test.ts @@ -222,7 +222,7 @@ describe.each([{ permission: 'Admin' }])( // search await expect( searchClient.index(UID).search('pride') - ).rejects.toHaveProperty('code', 'invalid_api_key') + ).rejects.toHaveProperty('cause.code', 'invalid_api_key') }) test(`${permission} key: Search in tenant token on index with no permissions `, async () => { @@ -236,7 +236,7 @@ describe.each([{ permission: 'Admin' }])( // search await expect( searchClient.index(UID).search('pride') - ).rejects.toHaveProperty('code', 'invalid_api_key') + ).rejects.toHaveProperty('cause.code', 'invalid_api_key') }) test(`${permission} key: Creates tenant token with an expiration date in the past throws an error`, async () => { diff --git a/tests/typed_search.test.ts b/tests/typed_search.test.ts index 2abacc13e..7d893b8a1 100644 --- a/tests/typed_search.test.ts +++ b/tests/typed_search.test.ts @@ -313,7 +313,8 @@ describe.each([ const response = await client.index(index.uid).search('h', { filter: ['genre="sci fi"'], }) - expect(response).toHaveProperty('hits', expect.any(Array)) + expect(response).toHaveProperty('hits') + expect(Array.isArray(response.hits)) expect(response.hits.length === 1).toBeTruthy() }) @@ -380,7 +381,7 @@ describe.each([ await expect( client.index(index.uid).search('prince') - ).rejects.toHaveProperty('code', ErrorStatusCode.INDEX_NOT_FOUND) + ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INDEX_NOT_FOUND) }) }) @@ -459,7 +460,7 @@ describe.each([{ permission: 'No' }])( await expect( client.index(index.uid).search('prince') ).rejects.toHaveProperty( - 'code', + 'cause.code', ErrorStatusCode.MISSING_AUTHORIZATION_HEADER ) }) @@ -479,10 +480,7 @@ describe.each([ client.index(index.uid).search() ).rejects.toHaveProperty( 'message', - `request to ${strippedHost}/${route} failed, reason: connect ECONNREFUSED ${BAD_HOST.replace( - 'http://', - '' - )}` + `Request to ${strippedHost}/${route} has failed` ) }) @@ -494,10 +492,7 @@ describe.each([ client.index(index.uid).search() ).rejects.toHaveProperty( 'message', - `request to ${strippedHost}/${route} failed, reason: connect ECONNREFUSED ${BAD_HOST.replace( - 'http://', - '' - )}` + `Request to ${strippedHost}/${route} has failed` ) }) }) diff --git a/tests/typo_tolerance.test.ts b/tests/typo_tolerance.test.ts index 82457eb28..844d814b4 100644 --- a/tests/typo_tolerance.test.ts +++ b/tests/typo_tolerance.test.ts @@ -98,21 +98,21 @@ describe.each([{ permission: 'Search' }])( const client = await getClient(permission) await expect( client.index(index.uid).getTypoTolerance() - ).rejects.toHaveProperty('code', ErrorStatusCode.INVALID_API_KEY) + ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY) }) test(`${permission} key: try to update typo tolerance settings and be denied`, async () => { const client = await getClient(permission) await expect( client.index(index.uid).updateTypoTolerance({}) - ).rejects.toHaveProperty('code', ErrorStatusCode.INVALID_API_KEY) + ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY) }) test(`${permission} key: try to reset typo tolerance settings and be denied`, async () => { const client = await getClient(permission) await expect( client.index(index.uid).resetTypoTolerance() - ).rejects.toHaveProperty('code', ErrorStatusCode.INVALID_API_KEY) + ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY) }) } ) @@ -129,7 +129,7 @@ describe.each([{ permission: 'No' }])( await expect( client.index(index.uid).getTypoTolerance() ).rejects.toHaveProperty( - 'code', + 'cause.code', ErrorStatusCode.MISSING_AUTHORIZATION_HEADER ) }) @@ -139,7 +139,7 @@ describe.each([{ permission: 'No' }])( await expect( client.index(index.uid).updateTypoTolerance({}) ).rejects.toHaveProperty( - 'code', + 'cause.code', ErrorStatusCode.MISSING_AUTHORIZATION_HEADER ) }) @@ -149,7 +149,7 @@ describe.each([{ permission: 'No' }])( await expect( client.index(index.uid).resetTypoTolerance() ).rejects.toHaveProperty( - 'code', + 'cause.code', ErrorStatusCode.MISSING_AUTHORIZATION_HEADER ) }) @@ -169,10 +169,7 @@ describe.each([ client.index(index.uid).getTypoTolerance() ).rejects.toHaveProperty( 'message', - `request to ${strippedHost}/${route} failed, reason: connect ECONNREFUSED ${BAD_HOST.replace( - 'http://', - '' - )}` + `Request to ${strippedHost}/${route} has failed` ) }) @@ -184,10 +181,7 @@ describe.each([ client.index(index.uid).updateTypoTolerance({}) ).rejects.toHaveProperty( 'message', - `request to ${strippedHost}/${route} failed, reason: connect ECONNREFUSED ${BAD_HOST.replace( - 'http://', - '' - )}` + `Request to ${strippedHost}/${route} has failed` ) }) @@ -199,10 +193,7 @@ describe.each([ client.index(index.uid).resetTypoTolerance() ).rejects.toHaveProperty( 'message', - `request to ${strippedHost}/${route} failed, reason: connect ECONNREFUSED ${BAD_HOST.replace( - 'http://', - '' - )}` + `Request to ${strippedHost}/${route} has failed` ) }) }) diff --git a/yarn.lock b/yarn.lock index c149dbc13..e104911a2 100644 --- a/yarn.lock +++ b/yarn.lock @@ -2141,13 +2141,6 @@ abbrev@1: resolved "https://registry.yarnpkg.com/abbrev/-/abbrev-1.1.1.tgz#f8f2c887ad10bf67f634f005b6987fed3179aac8" integrity sha512-nne9/IiQ/hzIhY6pdDnbBtz7DjPTKrY00P/zvPSm5pOFkl6xuGrGnXn/VtTNNfNtAfZ9/1RtehkszU9qcTii0Q== -abort-controller@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/abort-controller/-/abort-controller-3.0.0.tgz#eaf54d53b62bae4138e809ca225c8439a6efb392" - integrity sha512-h8lQ8tacZYnR3vNQTgibj+tODHI5/+l06Au2Pcriv/Gmet0eaj4TwWH41sO9wnHDiQsEj19q0drzdWdeAHtweg== - dependencies: - event-target-shim "^5.0.0" - acorn-globals@^7.0.0: version "7.0.1" resolved "https://registry.yarnpkg.com/acorn-globals/-/acorn-globals-7.0.1.tgz#0dbf05c44fa7c94332914c02066d5beff62c40c3" @@ -3185,11 +3178,6 @@ esutils@^2.0.2: resolved "https://registry.yarnpkg.com/esutils/-/esutils-2.0.3.tgz#74d2eb4de0b8da1293711910d50775b9b710ef64" integrity sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g== -event-target-shim@^5.0.0: - version "5.0.1" - resolved "https://registry.yarnpkg.com/event-target-shim/-/event-target-shim-5.0.1.tgz#5d4d3ebdf9583d63a5333ce2deb7480ab2b05789" - integrity sha512-i/2XbnSz/uxRCU6+NdVJgKWDTM427+MqYbkQzD321DuCQJUqOuJKIA0IM2+W2xtYHdKOmZ4dR6fExsd4SXL+WQ== - execa@^5.0.0: version "5.0.0" resolved "https://registry.yarnpkg.com/execa/-/execa-5.0.0.tgz#4029b0007998a841fbd1032e5f4de86a3c1e3376" From 6ed75e01416866a5dbbc934a79d08dccf9c048ee Mon Sep 17 00:00:00 2001 From: "F. Levi" <55688616+flevi29@users.noreply.github.com> Date: Wed, 22 May 2024 12:41:49 +0300 Subject: [PATCH 4/9] Adapted error tests, dropped one test case as it no longer applies --- tests/documents.test.ts | 4 ++-- tests/errors.test.ts | 37 ++++++------------------------------- 2 files changed, 8 insertions(+), 33 deletions(-) diff --git a/tests/documents.test.ts b/tests/documents.test.ts index e3f8f7573..b36252716 100644 --- a/tests/documents.test.ts +++ b/tests/documents.test.ts @@ -157,7 +157,7 @@ describe('Documents tests', () => { expect(documents.results.length).toEqual(2) }) - test(`${permission} key: Get documents should trigger error with a MeilisearchCommunicationError`, async () => { + test(`${permission} key: Get documents should trigger error with a MeilisearchRequestError`, async () => { const apiKey = await getKey(permission) const client = new MeiliSearch({ host: `${HOST}/indexes`, apiKey }) @@ -571,7 +571,7 @@ Hint: It might not be working because maybe you're not up to date with the Meili } }) - test(`${permission} key: Delete some documents should trigger error with a hint on a MeilisearchCommunicationError`, async () => { + test(`${permission} key: Delete some documents should trigger error with a hint on a MeilisearchRequestError`, async () => { const apiKey = await getKey(permission) const client = new MeiliSearch({ host: `${HOST}/indexes`, apiKey }) diff --git a/tests/errors.test.ts b/tests/errors.test.ts index 5c986ed23..0fe5f2af4 100644 --- a/tests/errors.test.ts +++ b/tests/errors.test.ts @@ -18,53 +18,28 @@ describe('Test on updates', () => { fetchMock.mockReset() }) - test(`Throw MeiliSearchCommunicationError when throwned error is not MeiliSearchApiError`, async () => { + test(`Throw MeilisearchRequestError when throwned error is not MeiliSearchApiError`, async () => { fetchMock.mockReject(new Error('fake error message')) const client = new MeiliSearch({ host: 'http://localhost:9345' }) try { await client.health() } catch (e: any) { - expect(e.name).toEqual('MeiliSearchCommunicationError') - } - }) - - test(`Not throw MeiliSearchCommunicationError when throwned error is MeiliSearchApiError`, async () => { - fetchMock.mockReject( - new MeiliSearchApiError(new Response(), { - message: 'Some error', - code: 'some_error', - type: 'random_error', - link: 'a link', - }) - ) - - const client = new MeiliSearch({ host: 'http://localhost:9345' }) - try { - await client.health() - } catch (e: any) { - expect(e.name).toEqual('MeiliSearchApiError') + expect(e.name).toEqual('MeiliSearchRequestError') } }) test('MeiliSearchApiError can be compared with the instanceof operator', async () => { - fetchMock.mockReject( + expect( new MeiliSearchApiError(new Response(), { message: 'Some error', code: 'some_error', type: 'random_error', link: 'a link', - }) - ) - - const client = new MeiliSearch({ host: 'http://localhost:9345' }) - try { - await client.health() - } catch (e: any) { - expect(e instanceof MeiliSearchApiError).toEqual(true) - } + }) instanceof MeiliSearchApiError + ).toEqual(true) }) - test('MeiliSearchCommunicationError can be compared with the instanceof operator', async () => { + test('MeilisearchRequestError can be compared with the instanceof operator', async () => { fetchMock.mockReject(new Error('fake error message')) const client = new MeiliSearch({ host: 'http://localhost:9345' }) try { From aa5e8e1dce9e194e6140efa113b1eb306104f40a Mon Sep 17 00:00:00 2001 From: "F. Levi" <55688616+flevi29@users.noreply.github.com> Date: Wed, 22 May 2024 13:27:37 +0300 Subject: [PATCH 5/9] Formatting and linting applied --- jest.config.js | 42 ++++++++++++++++++++--------------------- src/indexes.ts | 5 +---- tests/documents.test.ts | 10 ++++++++-- tests/embedders.test.ts | 2 +- tests/errors.test.ts | 2 +- tests/search.test.ts | 10 ++++++++-- tests/task.test.ts | 15 ++++++++++++--- 7 files changed, 52 insertions(+), 34 deletions(-) diff --git a/jest.config.js b/jest.config.js index 167e81ed4..6bbaf4a9a 100644 --- a/jest.config.js +++ b/jest.config.js @@ -1,43 +1,43 @@ /** @type {import('jest').Config} */ const config = { - rootDir: ".", - testMatch: ["/tests/**/*.ts?(x)"], + rootDir: '.', + testMatch: ['/tests/**/*.ts?(x)'], verbose: true, - testPathIgnorePatterns: ["meilisearch-test-utils", "env"], + testPathIgnorePatterns: ['meilisearch-test-utils', 'env'], collectCoverage: true, coverageThreshold: { global: { - "ts-jest": { - tsConfig: "/tsconfig.json", + 'ts-jest': { + tsConfig: '/tsconfig.json', }, }, }, watchPlugins: [ - "jest-watch-typeahead/filename", - "jest-watch-typeahead/testname", + 'jest-watch-typeahead/filename', + 'jest-watch-typeahead/testname', ], projects: [ { - preset: "ts-jest", - displayName: "browser", - testEnvironment: "jsdom", - testMatch: ["/tests/**/*.ts?(x)"], + preset: 'ts-jest', + displayName: 'browser', + testEnvironment: 'jsdom', + testMatch: ['/tests/**/*.ts?(x)'], testPathIgnorePatterns: [ - "meilisearch-test-utils", - "env/", - "token.test.ts", + 'meilisearch-test-utils', + 'env/', + 'token.test.ts', ], // make sure built-in Node.js fetch doesn't get replaced for consistency globals: { fetch: global.fetch }, }, { - preset: "ts-jest", - displayName: "node", - testEnvironment: "node", - testMatch: ["/tests/**/*.ts?(x)"], - testPathIgnorePatterns: ["meilisearch-test-utils", "env/"], + preset: 'ts-jest', + displayName: 'node', + testEnvironment: 'node', + testMatch: ['/tests/**/*.ts?(x)'], + testPathIgnorePatterns: ['meilisearch-test-utils', 'env/'], }, ], -}; +} -module.exports = config; +module.exports = config diff --git a/src/indexes.ts b/src/indexes.ts index ba0dc7ff9..a03b3a9cb 100644 --- a/src/indexes.ts +++ b/src/indexes.ts @@ -585,10 +585,7 @@ class Index = Record> { return new EnqueuedTask(task) } catch (e) { - if ( - e instanceof MeiliSearchRequestError && - isDocumentsDeletionQuery - ) { + if (e instanceof MeiliSearchRequestError && isDocumentsDeletionQuery) { e.message = versionErrorHintMessage(e.message, 'deleteDocuments') } else if (e instanceof MeiliSearchApiError) { e.message = versionErrorHintMessage(e.message, 'deleteDocuments') diff --git a/tests/documents.test.ts b/tests/documents.test.ts index b36252716..b91eed06a 100644 --- a/tests/documents.test.ts +++ b/tests/documents.test.ts @@ -610,14 +610,20 @@ Hint: It might not be working because maybe you're not up to date with the Meili const client = await getClient(permission) await expect( client.index(indexNoPk.uid).getDocument(1) - ).rejects.toHaveProperty('cause.code', ErrorStatusCode.DOCUMENT_NOT_FOUND) + ).rejects.toHaveProperty( + 'cause.code', + ErrorStatusCode.DOCUMENT_NOT_FOUND + ) }) test(`${permission} key: Try to get deleted document from index that has a primary key`, async () => { const client = await getClient(permission) await expect( client.index(indexPk.uid).getDocument(1) - ).rejects.toHaveProperty('cause.code', ErrorStatusCode.DOCUMENT_NOT_FOUND) + ).rejects.toHaveProperty( + 'cause.code', + ErrorStatusCode.DOCUMENT_NOT_FOUND + ) }) test(`${permission} key: Add documents from index with no primary key by giving a primary key as parameter`, async () => { diff --git a/tests/embedders.test.ts b/tests/embedders.test.ts index efc12887d..e4341538f 100644 --- a/tests/embedders.test.ts +++ b/tests/embedders.test.ts @@ -119,7 +119,7 @@ describe.each([{ permission: 'Master' }, { permission: 'Admin' }])( const task: EnqueuedTask = await client .index(index.uid) .updateEmbedders(newEmbedder) - await client.waitForTask(task.taskUid, {timeOutMs: 60_000}) + await client.waitForTask(task.taskUid, { timeOutMs: 60_000 }) const response: Embedders = await client.index(index.uid).getEmbedders() diff --git a/tests/errors.test.ts b/tests/errors.test.ts index 0fe5f2af4..f461bb870 100644 --- a/tests/errors.test.ts +++ b/tests/errors.test.ts @@ -28,7 +28,7 @@ describe('Test on updates', () => { } }) - test('MeiliSearchApiError can be compared with the instanceof operator', async () => { + test('MeiliSearchApiError can be compared with the instanceof operator', () => { expect( new MeiliSearchApiError(new Response(), { message: 'Some error', diff --git a/tests/search.test.ts b/tests/search.test.ts index 3d7700d65..c46780f57 100644 --- a/tests/search.test.ts +++ b/tests/search.test.ts @@ -1037,7 +1037,10 @@ describe.each([ controller.abort() searchPromise.catch((error: any) => { - expect(error).toHaveProperty('cause.message', 'This operation was aborted') + expect(error).toHaveProperty( + 'cause.message', + 'This operation was aborted' + ) }) }) @@ -1092,7 +1095,10 @@ describe.each([ }) searchBPromise.catch((error: any) => { - expect(error).toHaveProperty('cause.message', 'This operation was aborted') + expect(error).toHaveProperty( + 'cause.message', + 'This operation was aborted' + ) }) }) diff --git a/tests/task.test.ts b/tests/task.test.ts index 2622cf095..37ec531e9 100644 --- a/tests/task.test.ts +++ b/tests/task.test.ts @@ -387,7 +387,10 @@ describe.each([{ permission: 'Master' }, { permission: 'Admin' }])( await expect( // @ts-expect-error testing wrong argument type client.getTasks({ statuses: ['wrong'] }) - ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_TASK_STATUSES) + ).rejects.toHaveProperty( + 'cause.code', + ErrorStatusCode.INVALID_TASK_STATUSES + ) }) // filters error code: INVALID_TASK_UIDS_FILTER @@ -407,7 +410,10 @@ describe.each([{ permission: 'Master' }, { permission: 'Admin' }])( await expect( // @ts-expect-error testing wrong canceledBy type client.getTasks({ canceledBy: ['wrong'] }) - ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_TASK_CANCELED_BY) + ).rejects.toHaveProperty( + 'cause.code', + ErrorStatusCode.INVALID_TASK_CANCELED_BY + ) }) // filters error code: INVALID_TASK_DATE_FILTER @@ -584,7 +590,10 @@ describe.each([{ permission: 'Master' }, { permission: 'Admin' }])( await expect( // @ts-expect-error testing wrong argument type client.cancelTasks() - ).rejects.toHaveProperty('cause.code', ErrorStatusCode.MISSING_TASK_FILTERS) + ).rejects.toHaveProperty( + 'cause.code', + ErrorStatusCode.MISSING_TASK_FILTERS + ) }) // delete: uid From 12dad0e3a2bbb9eb4f13e914b1fa6174e301c8d8 Mon Sep 17 00:00:00 2001 From: "F. Levi" <55688616+flevi29@users.noreply.github.com> Date: Wed, 22 May 2024 13:54:18 +0300 Subject: [PATCH 6/9] Fixed jsdom trying to polyfill AbortController --- jest.config.js | 2 +- src/types/types.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/jest.config.js b/jest.config.js index 6bbaf4a9a..644f19a90 100644 --- a/jest.config.js +++ b/jest.config.js @@ -28,7 +28,7 @@ const config = { 'token.test.ts', ], // make sure built-in Node.js fetch doesn't get replaced for consistency - globals: { fetch: global.fetch }, + globals: { fetch: global.fetch, AbortController: global.AbortController }, }, { preset: 'ts-jest', diff --git a/src/types/types.ts b/src/types/types.ts index 9b3337e98..ae1224644 100644 --- a/src/types/types.ts +++ b/src/types/types.ts @@ -664,7 +664,7 @@ export type MeiliSearchErrorResponse = { link: string } -// @TODO: This doesn't seem to be updated, and its usefullness comes into question. +// @TODO: This doesn't seem to be up to date, and its usefullness comes into question. export const ErrorStatusCode = { /** @see https://www.meilisearch.com/docs/reference/errors/error_codes#index_creation_failed */ INDEX_CREATION_FAILED: 'index_creation_failed', From 96d5ba72f1fedbc4c86bbcd2f9ee2981defc2ce3 Mon Sep 17 00:00:00 2001 From: "F. Levi" <55688616+flevi29@users.noreply.github.com> Date: Wed, 22 May 2024 15:26:17 +0300 Subject: [PATCH 7/9] Fixed array checks in tests --- tests/get_search.test.ts | 26 +++++++++++------------ tests/search.test.ts | 42 +++++++++++++++++++------------------- tests/typed_search.test.ts | 2 +- 3 files changed, 35 insertions(+), 35 deletions(-) diff --git a/tests/get_search.test.ts b/tests/get_search.test.ts index 471058421..1504f06a5 100644 --- a/tests/get_search.test.ts +++ b/tests/get_search.test.ts @@ -97,7 +97,7 @@ describe.each([ const response = await client.index(index.uid).searchGet('prince', {}) expect(response).toHaveProperty('hits') - expect(Array.isArray(response.hits)) + expect(Array.isArray(response.hits)).toBe(true) expect(response).toHaveProperty('limit', 20) expect(response).toHaveProperty('offset', 0) expect(response).toHaveProperty('processingTimeMs', expect.any(Number)) @@ -111,7 +111,7 @@ describe.each([ .index(index.uid) .searchGet('prince', { limit: 1 }) expect(response).toHaveProperty('hits') - expect(Array.isArray(response.hits)) + expect(Array.isArray(response.hits)).toBe(true) expect(response).toHaveProperty('offset', 0) expect(response).toHaveProperty('limit', 1) expect(response).toHaveProperty('processingTimeMs', expect.any(Number)) @@ -125,7 +125,7 @@ describe.each([ .index(index.uid) .search('', { sort: ['id:asc'] }) expect(response).toHaveProperty('hits') - expect(Array.isArray(response.hits)) + expect(Array.isArray(response.hits)).toBe(true) const hit = response.hits[0] expect(hit.id).toEqual(1) }) @@ -138,7 +138,7 @@ describe.each([ const hit = response.hits[0] expect(response).toHaveProperty('hits') - expect(Array.isArray(response.hits)) + expect(Array.isArray(response.hits)).toBe(true) expect(response).toHaveProperty('query', 'prince') expect(Object.keys(hit).join(',')).toEqual( Object.keys(dataset[1]).join(',') @@ -171,7 +171,7 @@ describe.each([ .index(index.uid) .searchGet('prince', { limit: 1 }) expect(response).toHaveProperty('hits') - expect(Array.isArray(response.hits)) + expect(Array.isArray(response.hits)).toBe(true) expect(response).toHaveProperty('offset', 0) expect(response).toHaveProperty('limit', 1) expect(response).toHaveProperty('processingTimeMs', expect.any(Number)) @@ -209,7 +209,7 @@ describe.each([ showMatchesPosition: true, }) expect(response).toHaveProperty('hits') - expect(Array.isArray(response.hits)) + expect(Array.isArray(response.hits)).toBe(true) expect(response.hits[0]).toHaveProperty('_matchesPosition', { comment: [{ start: 22, length: 6 }], title: [{ start: 9, length: 6 }], @@ -230,7 +230,7 @@ describe.each([ }) expect(response).toHaveProperty('hits') - expect(Array.isArray(response.hits)) + expect(Array.isArray(response.hits)).toBe(true) expect(response).toHaveProperty('offset', 0) expect(response).toHaveProperty('limit', 5) expect(response).toHaveProperty('processingTimeMs', expect.any(Number)) @@ -305,7 +305,7 @@ describe.each([ showMatchesPosition: true, }) expect(response).toHaveProperty('hits') - expect(Array.isArray(response.hits)) + expect(Array.isArray(response.hits)).toBe(true) expect(response).toHaveProperty('offset', 0) expect(response).toHaveProperty('limit', 5) expect(response).toHaveProperty('processingTimeMs', expect.any(Number)) @@ -335,7 +335,7 @@ describe.each([ showMatchesPosition: true, }) expect(response).toHaveProperty('hits') - expect(Array.isArray(response.hits)) + expect(Array.isArray(response.hits)).toBe(true) expect(response).toHaveProperty('offset', 0) expect(response).toHaveProperty('limit', 5) expect(response).toHaveProperty('processingTimeMs', expect.any(Number)) @@ -370,7 +370,7 @@ describe.each([ genre: { romance: 2 }, }) expect(response).toHaveProperty('hits') - expect(Array.isArray(response.hits)) + expect(Array.isArray(response.hits)).toBe(true) expect(response.hits.length).toEqual(2) }) @@ -381,7 +381,7 @@ describe.each([ facets: ['genre'], }) expect(response).toHaveProperty('hits') - expect(Array.isArray(response.hits)) + expect(Array.isArray(response.hits)).toBe(true) expect(response.hits.length).toEqual(0) }) @@ -391,7 +391,7 @@ describe.each([ filter: 'genre = "sci fi"', }) expect(response).toHaveProperty('hits') - expect(Array.isArray(response.hits)) + expect(Array.isArray(response.hits)).toBe(true) expect(response.hits.length).toEqual(1) }) @@ -405,7 +405,7 @@ describe.each([ genre: { romance: 2 }, }) expect(response).toHaveProperty('hits') - expect(Array.isArray(response.hits)) + expect(Array.isArray(response.hits)).toBe(true) expect(response.hits.length).toEqual(2) }) diff --git a/tests/search.test.ts b/tests/search.test.ts index c46780f57..e1dd65a41 100644 --- a/tests/search.test.ts +++ b/tests/search.test.ts @@ -148,7 +148,7 @@ describe.each([ const response = await client.index(index.uid).search('prince', {}) expect(response).toHaveProperty('hits') - expect(Array.isArray(response.hits)) + expect(Array.isArray(response.hits)).toBe(true) expect(response).toHaveProperty('limit', 20) expect(response).toHaveProperty('offset', 0) expect(response).toHaveProperty('processingTimeMs', expect.any(Number)) @@ -174,7 +174,7 @@ describe.each([ }) expect(response).toHaveProperty('hits') - expect(Array.isArray(response.hits)) + expect(Array.isArray(response.hits)).toBe(true) expect(response).toHaveProperty('offset', 0) expect(response).toHaveProperty('limit', 20) expect(response.hits.length).toEqual(1) @@ -187,7 +187,7 @@ describe.each([ .search('french book', { matchingStrategy: MatchingStrategies.LAST }) expect(response).toHaveProperty('hits') - expect(Array.isArray(response.hits)) + expect(Array.isArray(response.hits)).toBe(true) expect(response).toHaveProperty('offset', 0) expect(response).toHaveProperty('limit', 20) expect(response.hits.length).toEqual(2) @@ -200,7 +200,7 @@ describe.each([ .search('other', { q: 'prince' }) expect(response).toHaveProperty('hits') - expect(Array.isArray(response.hits)) + expect(Array.isArray(response.hits)).toBe(true) expect(response).toHaveProperty('limit', 20) expect(response).toHaveProperty('offset', 0) expect(response.estimatedTotalHits).toBeDefined() @@ -214,7 +214,7 @@ describe.each([ const response = await client.index(index.uid).search(null, { q: 'prince' }) expect(response).toHaveProperty('hits') - expect(Array.isArray(response.hits)) + expect(Array.isArray(response.hits)).toBe(true) expect(response).toHaveProperty('limit', 20) expect(response).toHaveProperty('offset', 0) expect(response.estimatedTotalHits).toBeDefined() @@ -229,7 +229,7 @@ describe.each([ .index(index.uid) .search('"french book" about', {}) expect(response).toHaveProperty('hits') - expect(Array.isArray(response.hits)) + expect(Array.isArray(response.hits)).toBe(true) expect(response).toHaveProperty('limit', 20) expect(response).toHaveProperty('offset', 0) expect(response).toHaveProperty('processingTimeMs', expect.any(Number)) @@ -244,7 +244,7 @@ describe.each([ .index(index.uid) .search('prince', { limit: 1 }) expect(response).toHaveProperty('hits') - expect(Array.isArray(response.hits)) + expect(Array.isArray(response.hits)).toBe(true) expect(response).toHaveProperty('offset', 0) expect(response).toHaveProperty('limit', 1) expect(response.estimatedTotalHits).toEqual(2) @@ -259,7 +259,7 @@ describe.each([ .index(index.uid) .search('', { sort: ['id:asc'] }) expect(response).toHaveProperty('hits') - expect(Array.isArray(response.hits)) + expect(Array.isArray(response.hits)).toBe(true) const hit = response.hits[0] expect(hit.id).toEqual(1) }) @@ -274,7 +274,7 @@ describe.each([ const hit = response.hits[0] expect(response).toHaveProperty('hits') - expect(Array.isArray(response.hits)) + expect(Array.isArray(response.hits)).toBe(true) expect(response).toHaveProperty('query', 'prince') expect(hit).toHaveProperty('_rankingScore') }) @@ -289,7 +289,7 @@ describe.each([ const hit = response.hits[0] expect(response).toHaveProperty('hits') - expect(Array.isArray(response.hits)) + expect(Array.isArray(response.hits)).toBe(true) expect(response).toHaveProperty('query', 'prince') expect(hit).toHaveProperty('_rankingScoreDetails') expect(Object.keys(hit._rankingScoreDetails || {})).toEqual([ @@ -310,7 +310,7 @@ describe.each([ const hit = response.hits[0] expect(response).toHaveProperty('hits') - expect(Array.isArray(response.hits)) + expect(Array.isArray(response.hits)).toBe(true) expect(response).toHaveProperty('query', 'prince') expect(Object.keys(hit).join(',')).toEqual( Object.keys(dataset[1]).join(',') @@ -346,7 +346,7 @@ describe.each([ const hit = response.hits[0] expect(response).toHaveProperty('hits') - expect(Array.isArray(response.hits)) + expect(Array.isArray(response.hits)).toBe(true) expect(response).toHaveProperty('query', 'prince') expect(Object.keys(hit).join(',')).toEqual( Object.keys(dataset[1]).join(',') @@ -359,7 +359,7 @@ describe.each([ .index(index.uid) .search('prince', { limit: 1 }) expect(response).toHaveProperty('hits') - expect(Array.isArray(response.hits)) + expect(Array.isArray(response.hits)).toBe(true) expect(response).toHaveProperty('offset', 0) expect(response).toHaveProperty('limit', 1) expect(response.estimatedTotalHits).toEqual(2) @@ -409,7 +409,7 @@ describe.each([ showMatchesPosition: true, }) expect(response).toHaveProperty('hits') - expect(Array.isArray(response.hits)) + expect(Array.isArray(response.hits)).toBe(true) expect(response.hits[0]).toHaveProperty('_matchesPosition', { comment: [{ start: 22, length: 6 }], title: [{ start: 9, length: 6 }], @@ -429,7 +429,7 @@ describe.each([ showMatchesPosition: true, }) expect(response).toHaveProperty('hits') - expect(Array.isArray(response.hits)) + expect(Array.isArray(response.hits)).toBe(true) expect(response).toHaveProperty('offset', 0) expect(response).toHaveProperty('limit', 5) expect(response.estimatedTotalHits).toEqual(1) @@ -505,7 +505,7 @@ describe.each([ showMatchesPosition: true, }) expect(response).toHaveProperty('hits') - expect(Array.isArray(response.hits)) + expect(Array.isArray(response.hits)).toBe(true) expect(response).toHaveProperty('offset', 0) expect(response).toHaveProperty('limit', 5) expect(response).toHaveProperty('processingTimeMs', expect.any(Number)) @@ -535,7 +535,7 @@ describe.each([ showMatchesPosition: true, }) expect(response).toHaveProperty('hits') - expect(Array.isArray(response.hits)) + expect(Array.isArray(response.hits)).toBe(true) expect(response).toHaveProperty('offset', 0) expect(response).toHaveProperty('limit', 5) expect(response).toHaveProperty('processingTimeMs', expect.any(Number)) @@ -595,7 +595,7 @@ describe.each([ expect(response.facetStats).toEqual({ id: { min: 2, max: 123 } }) expect(response.facetStats?.['id']?.max).toBe(123) expect(response).toHaveProperty('hits') - expect(Array.isArray(response.hits)) + expect(Array.isArray(response.hits)).toBe(true) expect(response.hits.length).toEqual(2) }) @@ -605,7 +605,7 @@ describe.each([ filter: 'id < 0', }) expect(response).toHaveProperty('hits') - expect(Array.isArray(response.hits)) + expect(Array.isArray(response.hits)).toBe(true) expect(response.hits.length).toEqual(0) }) @@ -616,7 +616,7 @@ describe.each([ }) expect(response).toHaveProperty('hits') - expect(Array.isArray(response.hits)) + expect(Array.isArray(response.hits)).toBe(true) expect(response.hits.length).toEqual(1) }) @@ -630,7 +630,7 @@ describe.each([ genre: { romance: 2 }, }) expect(response).toHaveProperty('hits') - expect(Array.isArray(response.hits)) + expect(Array.isArray(response.hits)).toBe(true) expect(response.hits.length).toEqual(2) }) diff --git a/tests/typed_search.test.ts b/tests/typed_search.test.ts index 7d893b8a1..e1f5c1804 100644 --- a/tests/typed_search.test.ts +++ b/tests/typed_search.test.ts @@ -314,7 +314,7 @@ describe.each([ filter: ['genre="sci fi"'], }) expect(response).toHaveProperty('hits') - expect(Array.isArray(response.hits)) + expect(Array.isArray(response.hits)).toBe(true) expect(response.hits.length === 1).toBeTruthy() }) From bc4ebb4544ef88542cd1dd7dee09a04ce217877b Mon Sep 17 00:00:00 2001 From: "F. Levi" <55688616+flevi29@users.noreply.github.com> Date: Wed, 29 May 2024 23:00:37 +0300 Subject: [PATCH 8/9] Format to try and ease merge to main --- .eslintrc.js | 2 +- .prettierrc.js | 5 +- jest.config.js | 4 +- playgrounds/javascript/src/app.js | 52 +- rollup.config.js | 32 +- scripts/build.js | 32 +- scripts/file-size.js | 62 +- src/browser.ts | 12 +- src/clients/browser-client.ts | 8 +- src/clients/client.ts | 168 ++-- src/clients/node-client.ts | 22 +- src/enqueued-task.ts | 24 +- src/errors/index.ts | 10 +- src/errors/meilisearch-api-error.ts | 18 +- src/errors/meilisearch-error.ts | 4 +- src/errors/meilisearch-request-error.ts | 6 +- src/errors/meilisearch-timeout-error.ts | 6 +- src/errors/version-hint-message.ts | 2 +- src/http-requests.ts | 212 ++--- src/index.ts | 16 +- src/indexes.ts | 596 ++++++------- src/package-version.ts | 2 +- src/task.ts | 116 +-- src/token.ts | 88 +- src/types/index.ts | 2 +- src/types/types.ts | 730 +++++++-------- src/utils.ts | 26 +- tests/client.test.ts | 824 ++++++++--------- tests/dictionary.test.ts | 118 +-- tests/displayed_attributes.test.ts | 200 ++--- tests/distinct_attribute.test.ts | 186 ++-- tests/documents.test.ts | 934 +++++++++---------- tests/dump.test.ts | 58 +- tests/embedders.test.ts | 178 ++-- tests/errors.test.ts | 56 +- tests/facet_search.test.ts | 70 +- tests/faceting.test.ts | 196 ++-- tests/filterable_attributes.test.ts | 192 ++-- tests/get_search.test.ts | 492 +++++----- tests/index.test.ts | 630 ++++++------- tests/keys.test.ts | 250 +++--- tests/non_separator_tokens.test.ts | 116 +-- tests/pagination.test.ts | 206 ++--- tests/proximity_precision.test.ts | 116 +-- tests/ranking_rules.test.ts | 198 +++-- tests/raw_document.test.ts | 214 ++--- tests/search.test.ts | 1086 ++++++++++++----------- tests/searchCutoffMs.ts | 216 ++--- tests/searchable_attributes.test.ts | 192 ++-- tests/separator_tokens.test.ts | 116 +-- tests/settings.test.ts | 286 +++--- tests/snapshots.test.ts | 58 +- tests/sortable_attributes.test.ts | 198 ++--- tests/stop_words.test.ts | 186 ++-- tests/synonyms.test.ts | 180 ++-- tests/task.test.ts | 845 +++++++++--------- tests/token.test.ts | 298 +++---- tests/typed_search.test.ts | 468 +++++----- tests/typo_tolerance.test.ts | 188 ++-- tests/unit.test.ts | 24 +- tests/utils/meilisearch-test-utils.ts | 86 +- tests/wait_for_task.test.ts | 150 ++-- 62 files changed, 6054 insertions(+), 6014 deletions(-) diff --git a/.eslintrc.js b/.eslintrc.js index 3aa30a3a1..6dd79bf19 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -79,4 +79,4 @@ module.exports = { }, }, ], -} +}; diff --git a/.prettierrc.js b/.prettierrc.js index 2feaa1b3a..51e0bb825 100644 --- a/.prettierrc.js +++ b/.prettierrc.js @@ -1,10 +1,7 @@ // https://prettier.io/docs/en/options.html module.exports = { - singleQuote: true, - semi: false, - trailingComma: 'es5', plugins: ['./node_modules/prettier-plugin-jsdoc/dist/index.js'], // https://github.com/hosseinmd/prettier-plugin-jsdoc#tsdoc tsdoc: true, -} +}; diff --git a/jest.config.js b/jest.config.js index 644f19a90..1c52074f8 100644 --- a/jest.config.js +++ b/jest.config.js @@ -38,6 +38,6 @@ const config = { testPathIgnorePatterns: ['meilisearch-test-utils', 'env/'], }, ], -} +}; -module.exports = config +module.exports = config; diff --git a/playgrounds/javascript/src/app.js b/playgrounds/javascript/src/app.js index c3fcd74ef..7d693768d 100644 --- a/playgrounds/javascript/src/app.js +++ b/playgrounds/javascript/src/app.js @@ -1,19 +1,19 @@ -import { MeiliSearch } from '../../../src' +import { MeiliSearch } from '../../../src'; const config = { host: 'http://127.0.0.1:7700', apiKey: 'masterKey', -} +}; -const client = new MeiliSearch(config) -const indexUid = 'movies' +const client = new MeiliSearch(config); +const indexUid = 'movies'; const addDataset = async () => { - await client.deleteIndex(indexUid) - const { taskUid } = await client.createIndex(indexUid) - await client.index(indexUid).waitForTask(taskUid) + await client.deleteIndex(indexUid); + const { taskUid } = await client.createIndex(indexUid); + await client.index(indexUid).waitForTask(taskUid); - const documents = await client.index(indexUid).getDocuments() + const documents = await client.index(indexUid).getDocuments(); const dataset = [ { id: 1, title: 'Carol', genres: ['Romance', 'Drama'] }, @@ -26,35 +26,35 @@ const addDataset = async () => { }, { id: 5, title: 'Moana', genres: ['Fantasy', 'Action'] }, { id: 6, title: 'Philadelphia', genres: ['Drama'] }, - ] + ]; if (documents.results.length === 0) { - const { taskUid } = await client.index(indexUid).addDocuments(dataset) - await client.index(indexUid).waitForTask(taskUid) + const { taskUid } = await client.index(indexUid).addDocuments(dataset); + await client.index(indexUid).waitForTask(taskUid); } -} +}; -;(async () => { +(async () => { try { - await addDataset() - const indexes = await client.getRawIndexes() + await addDataset(); + const indexes = await client.getRawIndexes(); document.querySelector('.indexes').innerText = JSON.stringify( indexes, null, - 1 - ) + 1, + ); const resp = await client.index(indexUid).search('', { attributesToHighlight: ['title'], - }) - console.log({ resp }) - console.log({ hit: resp.hits[0] }) + }); + console.log({ resp }); + console.log({ hit: resp.hits[0] }); document.querySelector('.hits').innerText = JSON.stringify( resp.hits.map((hit) => hit.title), null, - 1 - ) - document.querySelector('.errors_title').style.display = 'none' + 1, + ); + document.querySelector('.errors_title').style.display = 'none'; } catch (e) { - console.error(e) - document.querySelector('.errors').innerText = JSON.stringify(e, null, 1) + console.error(e); + document.querySelector('.errors').innerText = JSON.stringify(e, null, 1); } -})() +})(); diff --git a/rollup.config.js b/rollup.config.js index fba21d667..853cd9512 100644 --- a/rollup.config.js +++ b/rollup.config.js @@ -1,18 +1,18 @@ -const nodeResolve = require('@rollup/plugin-node-resolve') -const { resolve } = require('path') -const commonjs = require('@rollup/plugin-commonjs') -const json = require('@rollup/plugin-json') -const typescript = require('rollup-plugin-typescript2') -const pkg = require('./package.json') -const { terser } = require('rollup-plugin-terser') -const { babel } = require('@rollup/plugin-babel') +const nodeResolve = require('@rollup/plugin-node-resolve'); +const { resolve } = require('path'); +const commonjs = require('@rollup/plugin-commonjs'); +const json = require('@rollup/plugin-json'); +const typescript = require('rollup-plugin-typescript2'); +const pkg = require('./package.json'); +const { terser } = require('rollup-plugin-terser'); +const { babel } = require('@rollup/plugin-babel'); function getOutputFileName(fileName, isProd = false) { - return isProd ? fileName.replace(/\.js$/, '.min.js') : fileName + return isProd ? fileName.replace(/\.js$/, '.min.js') : fileName; } -const env = process.env.NODE_ENV || 'development' -const ROOT = resolve(__dirname, '.') +const env = process.env.NODE_ENV || 'development'; +const ROOT = resolve(__dirname, '.'); const PLUGINS = [ typescript({ @@ -23,7 +23,7 @@ const PLUGINS = [ exclude: ['tests', 'examples', '*.js', 'scripts'], }, }), -] +]; module.exports = [ // browser-friendly UMD build @@ -36,7 +36,7 @@ module.exports = [ file: getOutputFileName( // will add .min. in filename if in production env resolve(ROOT, pkg.jsdelivr), - env === 'production' + env === 'production', ), format: 'umd', sourcemap: env === 'production', // create sourcemap for error reporting in production mode @@ -80,7 +80,7 @@ module.exports = [ { file: getOutputFileName( resolve(ROOT, pkg.module), - env === 'production' + env === 'production', ), exports: 'named', format: 'es', @@ -101,11 +101,11 @@ module.exports = [ file: getOutputFileName( // will add .min. in filename if in production env resolve(ROOT, pkg.main), - env === 'production' + env === 'production', ), exports: 'named', format: 'cjs', }, plugins: [...PLUGINS], }, -] +]; diff --git a/scripts/build.js b/scripts/build.js index 2f9f78948..1379e879c 100644 --- a/scripts/build.js +++ b/scripts/build.js @@ -1,16 +1,16 @@ /** This file only purpose is to execute any build related tasks */ -const { resolve, normalize } = require('path') -const { readFileSync, writeFileSync } = require('fs') -const pkg = require('../package.json') +const { resolve, normalize } = require('path'); +const { readFileSync, writeFileSync } = require('fs'); +const pkg = require('../package.json'); -const ROOT = resolve(__dirname, '..') -const TYPES_ROOT_FILE = resolve(ROOT, normalize(pkg.typings)) +const ROOT = resolve(__dirname, '..'); +const TYPES_ROOT_FILE = resolve(ROOT, normalize(pkg.typings)); -main() +main(); function main() { - writeDtsHeader() + writeDtsHeader(); } function writeDtsHeader() { @@ -19,10 +19,10 @@ function writeDtsHeader() { pkg.version, pkg.author, pkg.repository.url, - pkg.devDependencies.typescript - ) + pkg.devDependencies.typescript, + ); - prependFileSync(TYPES_ROOT_FILE, dtsHeader) + prependFileSync(TYPES_ROOT_FILE, dtsHeader); } /** @@ -33,8 +33,8 @@ function writeDtsHeader() { * @param {string} tsVersion */ function getDtsHeader(pkgName, version, author, repoUrl, tsVersion) { - const extractUserName = repoUrl.match(/\.com\/([\w-]+)\/\w+/i) - const githubUserUrl = extractUserName ? extractUserName[1] : 'Unknown' + const extractUserName = repoUrl.match(/\.com\/([\w-]+)\/\w+/i); + const githubUserUrl = extractUserName ? extractUserName[1] : 'Unknown'; return ` // Type definitions for ${pkgName} ${version} @@ -42,7 +42,7 @@ function getDtsHeader(pkgName, version, author, repoUrl, tsVersion) { // Definitions by: ${author} // Definitions: ${repoUrl} // TypeScript Version: ${tsVersion} -`.replace(/^\s+/gm, '') +`.replace(/^\s+/gm, ''); } /** @@ -52,10 +52,10 @@ function getDtsHeader(pkgName, version, author, repoUrl, tsVersion) { function prependFileSync(path, data) { const existingFileContent = readFileSync(path, { encoding: 'utf8', - }) - const newFileContent = [data, existingFileContent].join('\n') + }); + const newFileContent = [data, existingFileContent].join('\n'); writeFileSync(path, newFileContent, { flag: 'w+', encoding: 'utf8', - }) + }); } diff --git a/scripts/file-size.js b/scripts/file-size.js index 219e1b764..6bf025a0e 100644 --- a/scripts/file-size.js +++ b/scripts/file-size.js @@ -1,34 +1,34 @@ -const { basename, normalize } = require('path') -const { readFile: readFileCb } = require('fs') -const { promisify } = require('util') -const readFile = promisify(readFileCb) +const { basename, normalize } = require('path'); +const { readFile: readFileCb } = require('fs'); +const { promisify } = require('util'); +const readFile = promisify(readFileCb); -const kolor = require('kleur') -const prettyBytes = require('pretty-bytes') -const brotliSize = require('brotli-size') -const gzipSize = require('gzip-size') -const { log } = console -const pkg = require('../package.json') +const kolor = require('kleur'); +const prettyBytes = require('pretty-bytes'); +const brotliSize = require('brotli-size'); +const gzipSize = require('gzip-size'); +const { log } = console; +const pkg = require('../package.json'); -main() +main(); async function main() { - const args = process.argv.splice(2) - const filePaths = [...args.map(normalize)] + const args = process.argv.splice(2); + const filePaths = [...args.map(normalize)]; const fileMetadata = await Promise.all( filePaths.map(async (filePath) => { return { path: filePath, blob: await readFile(filePath, { encoding: 'utf8' }), - } - }) - ) + }; + }), + ); const output = await Promise.all( - fileMetadata.map((metadata) => getSizeInfo(metadata.blob, metadata.path)) - ) + fileMetadata.map((metadata) => getSizeInfo(metadata.blob, metadata.path)), + ); - log(getFormatedOutput(pkg.name, output)) + log(getFormatedOutput(pkg.name, output)); } /** @@ -36,15 +36,15 @@ async function main() { * @param {string[]} filesOutput */ function getFormatedOutput(pkgName, filesOutput) { - const MAGIC_INDENTATION = 3 - const WHITE_SPACE = ' '.repeat(MAGIC_INDENTATION) + const MAGIC_INDENTATION = 3; + const WHITE_SPACE = ' '.repeat(MAGIC_INDENTATION); return ( kolor.blue(`${pkgName} bundle sizes: 📦`) + `\n${WHITE_SPACE}` + readFile.name + filesOutput.join(`\n${WHITE_SPACE}`) - ) + ); } /** @@ -54,13 +54,13 @@ function getFormatedOutput(pkgName, filesOutput) { * @param {boolean} raw */ function formatSize(size, filename, type, raw) { - const pretty = raw ? `${size} B` : prettyBytes(size) - const color = size < 5000 ? 'green' : size > 40000 ? 'red' : 'yellow' - const MAGIC_INDENTATION = type === 'br' ? 13 : 10 + const pretty = raw ? `${size} B` : prettyBytes(size); + const color = size < 5000 ? 'green' : size > 40000 ? 'red' : 'yellow'; + const MAGIC_INDENTATION = type === 'br' ? 13 : 10; return `${' '.repeat(MAGIC_INDENTATION - pretty.length)}${kolor[color]( - pretty - )}: ${kolor.white(basename(filename))}.${type}` + pretty, + )}: ${kolor.white(basename(filename))}.${type}`; } /** @@ -69,8 +69,8 @@ function formatSize(size, filename, type, raw) { * @param {boolean} [raw=false] Default is `false` */ async function getSizeInfo(code, filename, raw = false) { - const isRaw = raw || code.length < 5000 - const gzip = formatSize(await gzipSize(code), filename, 'gz', isRaw) - const brotli = formatSize(await brotliSize.sync(code), filename, 'br', isRaw) - return gzip + '\n' + brotli + const isRaw = raw || code.length < 5000; + const gzip = formatSize(await gzipSize(code), filename, 'gz', isRaw); + const brotli = formatSize(await brotliSize.sync(code), filename, 'br', isRaw); + return gzip + '\n' + brotli; } diff --git a/src/browser.ts b/src/browser.ts index d3e40facc..c78a67940 100644 --- a/src/browser.ts +++ b/src/browser.ts @@ -1,7 +1,7 @@ -export * from './types' -export * from './errors' -export * from './indexes' -import { MeiliSearch } from './clients/browser-client' +export * from './types'; +export * from './errors'; +export * from './indexes'; +import { MeiliSearch } from './clients/browser-client'; -export { MeiliSearch, MeiliSearch as Meilisearch } -export default MeiliSearch +export { MeiliSearch, MeiliSearch as Meilisearch }; +export default MeiliSearch; diff --git a/src/clients/browser-client.ts b/src/clients/browser-client.ts index 362e024d0..eb02229ec 100644 --- a/src/clients/browser-client.ts +++ b/src/clients/browser-client.ts @@ -1,10 +1,10 @@ -import { Config } from '../types' -import { Client } from './client' +import { Config } from '../types'; +import { Client } from './client'; class MeiliSearch extends Client { constructor(config: Config) { - super(config) + super(config); } } -export { MeiliSearch } +export { MeiliSearch }; diff --git a/src/clients/client.ts b/src/clients/client.ts index 2eb61713d..ac031601a 100644 --- a/src/clients/client.ts +++ b/src/clients/client.ts @@ -5,9 +5,9 @@ * Copyright: 2019, MeiliSearch */ -'use strict' +'use strict'; -import { Index } from '../indexes' +import { Index } from '../indexes'; import { KeyCreation, Config, @@ -34,15 +34,15 @@ import { DeleteTasksQuery, MultiSearchParams, MultiSearchResponse, -} from '../types' -import { HttpRequests } from '../http-requests' -import { TaskClient, Task } from '../task' -import { EnqueuedTask } from '../enqueued-task' +} from '../types'; +import { HttpRequests } from '../http-requests'; +import { TaskClient, Task } from '../task'; +import { EnqueuedTask } from '../enqueued-task'; class Client { - config: Config - httpRequest: HttpRequests - tasks: TaskClient + config: Config; + httpRequest: HttpRequests; + tasks: TaskClient; /** * Creates new MeiliSearch instance @@ -50,9 +50,9 @@ class Client { * @param config - Configuration object */ constructor(config: Config) { - this.config = config - this.httpRequest = new HttpRequests(config) - this.tasks = new TaskClient(config) + this.config = config; + this.httpRequest = new HttpRequests(config); + this.tasks = new TaskClient(config); } /** @@ -62,9 +62,9 @@ class Client { * @returns Instance of Index */ index = Record>( - indexUid: string + indexUid: string, ): Index { - return new Index(this.config, indexUid) + return new Index(this.config, indexUid); } /** @@ -75,9 +75,9 @@ class Client { * @returns Promise returning Index instance */ async getIndex = Record>( - indexUid: string + indexUid: string, ): Promise> { - return new Index(this.config, indexUid).fetchInfo() + return new Index(this.config, indexUid).fetchInfo(); } /** @@ -88,7 +88,7 @@ class Client { * @returns Promise returning index information */ async getRawIndex(indexUid: string): Promise { - return new Index(this.config, indexUid).getRawInfo() + return new Index(this.config, indexUid).getRawInfo(); } /** @@ -98,13 +98,13 @@ class Client { * @returns Promise returning array of raw index information */ async getIndexes( - parameters: IndexesQuery = {} + parameters: IndexesQuery = {}, ): Promise> { - const rawIndexes = await this.getRawIndexes(parameters) + 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 } + (index) => new Index(this.config, index.uid, index.primaryKey), + ); + return { ...rawIndexes, results: indexes }; } /** @@ -114,13 +114,13 @@ class Client { * @returns Promise returning array of raw index information */ async getRawIndexes( - parameters: IndexesQuery = {} + parameters: IndexesQuery = {}, ): Promise> { - const url = `indexes` + const url = `indexes`; return await this.httpRequest.get>( url, - parameters - ) + parameters, + ); } /** @@ -132,9 +132,9 @@ class Client { */ async createIndex( uid: string, - options: IndexOptions = {} + options: IndexOptions = {}, ): Promise { - return await Index.create(uid, options, this.config) + return await Index.create(uid, options, this.config); } /** @@ -146,9 +146,9 @@ class Client { */ async updateIndex( uid: string, - options: IndexOptions = {} + options: IndexOptions = {}, ): Promise { - return await new Index(this.config, uid).update(options) + return await new Index(this.config, uid).update(options); } /** @@ -158,7 +158,7 @@ class Client { * @returns Promise which resolves when index is deleted successfully */ async deleteIndex(uid: string): Promise { - return await new Index(this.config, uid).delete() + return await new Index(this.config, uid).delete(); } /** @@ -170,13 +170,13 @@ class Client { */ async deleteIndexIfExists(uid: string): Promise { try { - await this.deleteIndex(uid) - return true + await this.deleteIndex(uid); + return true; } catch (e: any) { if (e.code === ErrorStatusCode.INDEX_NOT_FOUND) { - return false + return false; } - throw e + throw e; } } @@ -187,8 +187,8 @@ class Client { * @returns Promise returning object of the enqueued task */ async swapIndexes(params: SwapIndexesParams): Promise { - const url = '/swap-indexes' - return await this.httpRequest.post(url, params) + const url = '/swap-indexes'; + return await this.httpRequest.post(url, params); } /// @@ -209,7 +209,7 @@ class Client { * { indexUid: 'movies', q: 'wonder' }, * { indexUid: 'books', q: 'flower' }, * ], - * }) + * }); * ``` * * @param queries - Search queries @@ -218,11 +218,11 @@ class Client { */ async multiSearch = Record>( queries?: MultiSearchParams, - config?: Partial + config?: Partial, ): Promise> { - const url = `multi-search` + const url = `multi-search`; - return await this.httpRequest.post(url, queries, undefined, config) + return await this.httpRequest.post(url, queries, undefined, config); } /// @@ -236,7 +236,7 @@ class Client { * @returns Promise returning all tasks */ async getTasks(parameters: TasksQuery = {}): Promise { - return await this.tasks.getTasks(parameters) + return await this.tasks.getTasks(parameters); } /** @@ -246,7 +246,7 @@ class Client { * @returns Promise returning a task */ async getTask(taskUid: number): Promise { - return await this.tasks.getTask(taskUid) + return await this.tasks.getTask(taskUid); } /** @@ -258,12 +258,12 @@ class Client { */ async waitForTasks( taskUids: number[], - { timeOutMs = 5000, intervalMs = 50 }: WaitOptions = {} + { timeOutMs = 5000, intervalMs = 50 }: WaitOptions = {}, ): Promise { return await this.tasks.waitForTasks(taskUids, { timeOutMs, intervalMs, - }) + }); } /** @@ -275,12 +275,12 @@ class Client { */ async waitForTask( taskUid: number, - { timeOutMs = 5000, intervalMs = 50 }: WaitOptions = {} + { timeOutMs = 5000, intervalMs = 50 }: WaitOptions = {}, ): Promise { return await this.tasks.waitForTask(taskUid, { timeOutMs, intervalMs, - }) + }); } /** @@ -290,7 +290,7 @@ class Client { * @returns Promise containing an EnqueuedTask */ async cancelTasks(parameters: CancelTasksQuery): Promise { - return await this.tasks.cancelTasks(parameters) + return await this.tasks.cancelTasks(parameters); } /** @@ -300,7 +300,7 @@ class Client { * @returns Promise containing an EnqueuedTask */ async deleteTasks(parameters: DeleteTasksQuery = {}): Promise { - return await this.tasks.deleteTasks(parameters) + return await this.tasks.deleteTasks(parameters); } /// @@ -314,16 +314,16 @@ class Client { * @returns Promise returning an object with keys */ async getKeys(parameters: KeysQuery = {}): Promise { - const url = `keys` - const keys = await this.httpRequest.get(url, parameters) + const url = `keys`; + const keys = await this.httpRequest.get(url, parameters); keys.results = keys.results.map((key) => ({ ...key, createdAt: new Date(key.createdAt), updatedAt: new Date(key.updatedAt), - })) + })); - return keys + return keys; } /** @@ -333,8 +333,8 @@ class Client { * @returns Promise returning a key */ async getKey(keyOrUid: string): Promise { - const url = `keys/${keyOrUid}` - return await this.httpRequest.get(url) + const url = `keys/${keyOrUid}`; + return await this.httpRequest.get(url); } /** @@ -344,8 +344,8 @@ class Client { * @returns Promise returning a key */ async createKey(options: KeyCreation): Promise { - const url = `keys` - return await this.httpRequest.post(url, options) + const url = `keys`; + return await this.httpRequest.post(url, options); } /** @@ -356,8 +356,8 @@ class Client { * @returns Promise returning a key */ async updateKey(keyOrUid: string, options: KeyUpdate): Promise { - const url = `keys/${keyOrUid}` - return await this.httpRequest.patch(url, options) + const url = `keys/${keyOrUid}`; + return await this.httpRequest.patch(url, options); } /** @@ -367,8 +367,8 @@ class Client { * @returns */ async deleteKey(keyOrUid: string): Promise { - const url = `keys/${keyOrUid}` - return await this.httpRequest.delete(url) + const url = `keys/${keyOrUid}`; + return await this.httpRequest.delete(url); } /// @@ -381,8 +381,8 @@ class Client { * @returns Promise returning an object with health details */ async health(): Promise { - const url = `health` - return await this.httpRequest.get(url) + const url = `health`; + return await this.httpRequest.get(url); } /** @@ -392,11 +392,11 @@ class Client { */ async isHealthy(): Promise { try { - const url = `health` - await this.httpRequest.get(url) - return true + const url = `health`; + await this.httpRequest.get(url); + return true; } catch (e: any) { - return false + return false; } } @@ -410,8 +410,8 @@ class Client { * @returns Promise returning object of all the stats */ async getStats(): Promise { - const url = `stats` - return await this.httpRequest.get(url) + const url = `stats`; + return await this.httpRequest.get(url); } /// @@ -424,8 +424,8 @@ class Client { * @returns Promise returning object with version details */ async getVersion(): Promise { - const url = `version` - return await this.httpRequest.get(url) + const url = `version`; + return await this.httpRequest.get(url); } /// @@ -438,9 +438,11 @@ class Client { * @returns Promise returning object of the enqueued task */ async createDump(): Promise { - const url = `dumps` - const task = await this.httpRequest.post(url) - return new EnqueuedTask(task) + const url = `dumps`; + const task = await this.httpRequest.post( + url, + ); + return new EnqueuedTask(task); } /// @@ -453,10 +455,12 @@ class Client { * @returns Promise returning object of the enqueued task */ async createSnapshot(): Promise { - const url = `snapshots` - const task = await this.httpRequest.post(url) + const url = `snapshots`; + const task = await this.httpRequest.post( + url, + ); - return new EnqueuedTask(task) + return new EnqueuedTask(task); } /// @@ -474,13 +478,13 @@ class Client { generateTenantToken( _apiKeyUid: string, _searchRules: TokenSearchRules, - _options?: TokenOptions + _options?: TokenOptions, ): Promise { - const error = new Error() - error.message = `Meilisearch: failed to generate a tenant token. Generation of a token only works in a node environment \n ${error.stack}.` + const error = new Error(); + error.message = `Meilisearch: failed to generate a tenant token. Generation of a token only works in a node environment \n ${error.stack}.`; - return Promise.reject(error) + return Promise.reject(error); } } -export { Client } +export { Client }; diff --git a/src/clients/node-client.ts b/src/clients/node-client.ts index c74f96c3c..3a4a60742 100644 --- a/src/clients/node-client.ts +++ b/src/clients/node-client.ts @@ -1,13 +1,13 @@ -import { Client } from './client' -import { Config, TokenSearchRules, TokenOptions } from '../types' -import { Token } from '../token' +import { Client } from './client'; +import { Config, TokenSearchRules, TokenOptions } from '../types'; +import { Token } from '../token'; class MeiliSearch extends Client { - tokens: Token + tokens: Token; constructor(config: Config) { - super(config) - this.tokens = new Token(config) + super(config); + this.tokens = new Token(config); } /** @@ -21,16 +21,16 @@ class MeiliSearch extends Client { async generateTenantToken( apiKeyUid: string, searchRules: TokenSearchRules, - options?: TokenOptions + options?: TokenOptions, ): Promise { if (typeof window === 'undefined') { return await this.tokens.generateTenantToken( apiKeyUid, searchRules, - options - ) + options, + ); } - return await super.generateTenantToken(apiKeyUid, searchRules, options) + return await super.generateTenantToken(apiKeyUid, searchRules, options); } } -export { MeiliSearch } +export { MeiliSearch }; diff --git a/src/enqueued-task.ts b/src/enqueued-task.ts index fb6d6b598..53f7907c7 100644 --- a/src/enqueued-task.ts +++ b/src/enqueued-task.ts @@ -1,19 +1,19 @@ -import { EnqueuedTaskObject } from './types' +import { EnqueuedTaskObject } from './types'; class EnqueuedTask { - taskUid: EnqueuedTaskObject['taskUid'] - indexUid: EnqueuedTaskObject['indexUid'] - status: EnqueuedTaskObject['status'] - type: EnqueuedTaskObject['type'] - enqueuedAt: Date + taskUid: EnqueuedTaskObject['taskUid']; + indexUid: EnqueuedTaskObject['indexUid']; + status: EnqueuedTaskObject['status']; + type: EnqueuedTaskObject['type']; + enqueuedAt: Date; constructor(task: EnqueuedTaskObject) { - this.taskUid = task.taskUid - this.indexUid = task.indexUid - this.status = task.status - this.type = task.type - this.enqueuedAt = new Date(task.enqueuedAt) + this.taskUid = task.taskUid; + this.indexUid = task.indexUid; + this.status = task.status; + this.type = task.type; + this.enqueuedAt = new Date(task.enqueuedAt); } } -export { EnqueuedTask } +export { EnqueuedTask }; diff --git a/src/errors/index.ts b/src/errors/index.ts index d2f24dfc1..27ff6676f 100644 --- a/src/errors/index.ts +++ b/src/errors/index.ts @@ -1,5 +1,5 @@ -export * from './meilisearch-api-error' -export * from './meilisearch-request-error' -export * from './meilisearch-error' -export * from './meilisearch-timeout-error' -export * from './version-hint-message' +export * from './meilisearch-api-error'; +export * from './meilisearch-request-error'; +export * from './meilisearch-error'; +export * from './meilisearch-timeout-error'; +export * from './version-hint-message'; diff --git a/src/errors/meilisearch-api-error.ts b/src/errors/meilisearch-api-error.ts index 8b25995d9..68121074f 100644 --- a/src/errors/meilisearch-api-error.ts +++ b/src/errors/meilisearch-api-error.ts @@ -1,18 +1,20 @@ -import { MeiliSearchErrorResponse } from '../types' -import { MeiliSearchError } from './meilisearch-error' +import { MeiliSearchErrorResponse } from '../types'; +import { MeiliSearchError } from './meilisearch-error'; export class MeiliSearchApiError extends MeiliSearchError { - override name = 'MeiliSearchApiError' - override cause?: MeiliSearchErrorResponse - readonly response: Response + override name = 'MeiliSearchApiError'; + override cause?: MeiliSearchErrorResponse; + readonly response: Response; constructor(response: Response, responseBody?: MeiliSearchErrorResponse) { - super(responseBody?.message ?? `${response.status}: ${response.statusText}`) + super( + responseBody?.message ?? `${response.status}: ${response.statusText}`, + ); - this.response = response + this.response = response; if (responseBody !== undefined) { - this.cause = responseBody + this.cause = responseBody; } } } diff --git a/src/errors/meilisearch-error.ts b/src/errors/meilisearch-error.ts index b601c2add..09c33e7c9 100644 --- a/src/errors/meilisearch-error.ts +++ b/src/errors/meilisearch-error.ts @@ -1,7 +1,7 @@ export class MeiliSearchError extends Error { - override name = 'MeiliSearchError' + override name = 'MeiliSearchError'; constructor(...params: ConstructorParameters) { - super(...params) + super(...params); } } diff --git a/src/errors/meilisearch-request-error.ts b/src/errors/meilisearch-request-error.ts index 89984a253..aef8e429b 100644 --- a/src/errors/meilisearch-request-error.ts +++ b/src/errors/meilisearch-request-error.ts @@ -1,9 +1,9 @@ -import { MeiliSearchError } from './meilisearch-error' +import { MeiliSearchError } from './meilisearch-error'; export class MeiliSearchRequestError extends MeiliSearchError { - override name = 'MeiliSearchRequestError' + override name = 'MeiliSearchRequestError'; constructor(url: string, cause: unknown) { - super(`Request to ${url} has failed`, { cause }) + super(`Request to ${url} has failed`, { cause }); } } diff --git a/src/errors/meilisearch-timeout-error.ts b/src/errors/meilisearch-timeout-error.ts index fdfc5d3d4..e6730e8a9 100644 --- a/src/errors/meilisearch-timeout-error.ts +++ b/src/errors/meilisearch-timeout-error.ts @@ -1,9 +1,9 @@ -import { MeiliSearchError } from './meilisearch-error' +import { MeiliSearchError } from './meilisearch-error'; export class MeiliSearchTimeOutError extends MeiliSearchError { - override name = 'MeiliSearchTimeOutError' + override name = 'MeiliSearchTimeOutError'; constructor(message: string) { - super(message) + super(message); } } diff --git a/src/errors/version-hint-message.ts b/src/errors/version-hint-message.ts index e04cb98d2..889b24a86 100644 --- a/src/errors/version-hint-message.ts +++ b/src/errors/version-hint-message.ts @@ -1,3 +1,3 @@ export function versionErrorHintMessage(message: string, method: string) { - return `${message}\nHint: It might not be working because maybe you're not up to date with the Meilisearch version that ${method} call requires.` + return `${message}\nHint: It might not be working because maybe you're not up to date with the Meilisearch version that ${method} call requires.`; } diff --git a/src/http-requests.ts b/src/http-requests.ts index e1d2a33b7..96e2b606e 100644 --- a/src/http-requests.ts +++ b/src/http-requests.ts @@ -1,40 +1,40 @@ -import { Config, EnqueuedTaskObject } from './types' -import { PACKAGE_VERSION } from './package-version' +import { Config, EnqueuedTaskObject } from './types'; +import { PACKAGE_VERSION } from './package-version'; import { MeiliSearchError, MeiliSearchApiError, MeiliSearchRequestError, -} from './errors' +} from './errors'; -import { addTrailingSlash, addProtocolIfNotPresent } from './utils' +import { addTrailingSlash, addProtocolIfNotPresent } from './utils'; -type queryParams = { [key in keyof T]: string } +type queryParams = { [key in keyof T]: string }; function toQueryParams(parameters: T): queryParams { - const params = Object.keys(parameters) as Array + const params = Object.keys(parameters) as Array; const queryParams = params.reduce>((acc, key) => { - const value = parameters[key] + const value = parameters[key]; if (value === undefined) { - return acc + return acc; } else if (Array.isArray(value)) { - return { ...acc, [key]: value.join(',') } + return { ...acc, [key]: value.join(',') }; } else if (value instanceof Date) { - return { ...acc, [key]: value.toISOString() } + return { ...acc, [key]: value.toISOString() }; } - return { ...acc, [key]: value } - }, {} as queryParams) - return queryParams + return { ...acc, [key]: value }; + }, {} as queryParams); + return queryParams; } function constructHostURL(host: string): string { try { - host = addProtocolIfNotPresent(host) - host = addTrailingSlash(host) - return host + host = addProtocolIfNotPresent(host); + host = addTrailingSlash(host); + return host; } catch (e) { - throw new MeiliSearchError('The provided host is not valid.') + throw new MeiliSearchError('The provided host is not valid.'); } } @@ -42,71 +42,71 @@ function cloneAndParseHeaders(headers: HeadersInit): Record { if (Array.isArray(headers)) { return headers.reduce( (acc, headerPair) => { - acc[headerPair[0]] = headerPair[1] - return acc + acc[headerPair[0]] = headerPair[1]; + return acc; }, - {} as Record - ) + {} as Record, + ); } else if ('has' in headers) { - const clonedHeaders: Record = {} - ;(headers as Headers).forEach((value, key) => (clonedHeaders[key] = value)) - return clonedHeaders + const clonedHeaders: Record = {}; + (headers as Headers).forEach((value, key) => (clonedHeaders[key] = value)); + return clonedHeaders; } else { - return Object.assign({}, headers) + return Object.assign({}, headers); } } function createHeaders(config: Config): Record { - const agentHeader = 'X-Meilisearch-Client' - const packageAgent = `Meilisearch JavaScript (v${PACKAGE_VERSION})` - const contentType = 'Content-Type' - const authorization = 'Authorization' - const headers = cloneAndParseHeaders(config.requestConfig?.headers ?? {}) + const agentHeader = 'X-Meilisearch-Client'; + const packageAgent = `Meilisearch JavaScript (v${PACKAGE_VERSION})`; + const contentType = 'Content-Type'; + const authorization = 'Authorization'; + const headers = cloneAndParseHeaders(config.requestConfig?.headers ?? {}); // do not override if user provided the header if (config.apiKey && !headers[authorization]) { - headers[authorization] = `Bearer ${config.apiKey}` + headers[authorization] = `Bearer ${config.apiKey}`; } if (!headers[contentType]) { - headers['Content-Type'] = 'application/json' + headers['Content-Type'] = 'application/json'; } // Creates the custom user agent with information on the package used. if (config.clientAgents && Array.isArray(config.clientAgents)) { - const clients = config.clientAgents.concat(packageAgent) + const clients = config.clientAgents.concat(packageAgent); - headers[agentHeader] = clients.join(' ; ') + headers[agentHeader] = clients.join(' ; '); } else if (config.clientAgents && !Array.isArray(config.clientAgents)) { // If the header is defined but not an array throw new MeiliSearchError( - `Meilisearch: The header "${agentHeader}" should be an array of string(s).\n` - ) + `Meilisearch: The header "${agentHeader}" should be an array of string(s).\n`, + ); } else { - headers[agentHeader] = packageAgent + headers[agentHeader] = packageAgent; } - return headers + return headers; } class HttpRequests { - headers: Record - url: URL - requestConfig?: Config['requestConfig'] - httpClient?: Required['httpClient'] - requestTimeout?: number + headers: Record; + url: URL; + requestConfig?: Config['requestConfig']; + httpClient?: Required['httpClient']; + requestTimeout?: number; constructor(config: Config) { - this.headers = createHeaders(config) - this.requestConfig = config.requestConfig - this.httpClient = config.httpClient - this.requestTimeout = config.timeout + this.headers = createHeaders(config); + this.requestConfig = config.requestConfig; + this.httpClient = config.httpClient; + this.requestTimeout = config.timeout; try { - const host = constructHostURL(config.host) - this.url = new URL(host) + const host = constructHostURL(config.host); + this.url = new URL(host); } catch (e) { - throw new MeiliSearchError('The provided host is not valid.') + throw new MeiliSearchError('The provided host is not valid.'); } } @@ -117,32 +117,32 @@ class HttpRequests { body, config = {}, }: { - method: string - url: string - params?: { [key: string]: any } - body?: any - config?: Record + method: string; + url: string; + params?: { [key: string]: any }; + body?: any; + config?: Record; }) { if (typeof fetch === 'undefined') { - require('cross-fetch/polyfill') + require('cross-fetch/polyfill'); } - const constructURL = new URL(url, this.url) + const constructURL = new URL(url, this.url); if (params) { - const queryParams = new URLSearchParams() + const queryParams = new URLSearchParams(); Object.keys(params) .filter((x: string) => params[x] !== null) - .map((x: string) => queryParams.set(x, params[x])) - constructURL.search = queryParams.toString() + .map((x: string) => queryParams.set(x, params[x])); + constructURL.search = queryParams.toString(); } // in case a custom content-type is provided // do not stringify body if (!config.headers?.['Content-Type']) { - body = JSON.stringify(body) + body = JSON.stringify(body); } - const headers = { ...this.headers, ...config.headers } + const headers = { ...this.headers, ...config.headers }; const responsePromise = this.fetchWithTimeout( constructURL.toString(), { @@ -152,99 +152,99 @@ class HttpRequests { body, headers, }, - this.requestTimeout - ) + this.requestTimeout, + ); const response = await responsePromise.catch((error: unknown) => { - throw new MeiliSearchRequestError(constructURL.toString(), error) - }) + throw new MeiliSearchRequestError(constructURL.toString(), error); + }); // When using a custom HTTP client, the response is returned to allow the user to parse/handle it as they see fit if (this.httpClient !== undefined) { - return response + return response; } - const responseBody = await response.text() + const responseBody = await response.text(); const parsedResponse = - responseBody === '' ? undefined : JSON.parse(responseBody) + responseBody === '' ? undefined : JSON.parse(responseBody); if (!response.ok) { - throw new MeiliSearchApiError(response, parsedResponse) + throw new MeiliSearchApiError(response, parsedResponse); } - return parsedResponse + return parsedResponse; } async fetchWithTimeout( url: string, options: Record | RequestInit | undefined, - timeout: HttpRequests['requestTimeout'] + timeout: HttpRequests['requestTimeout'], ): Promise { return new Promise((resolve, reject) => { - const fetchFn = this.httpClient ? this.httpClient : fetch + const fetchFn = this.httpClient ? this.httpClient : fetch; - const fetchPromise = fetchFn(url, options) + const fetchPromise = fetchFn(url, options); - const promises: Array> = [fetchPromise] + const promises: Array> = [fetchPromise]; // TimeoutPromise will not run if undefined or zero - let timeoutId: ReturnType + let timeoutId: ReturnType; if (timeout) { const timeoutPromise = new Promise((_, reject) => { timeoutId = setTimeout(() => { - reject(new Error('Error: Request Timed Out')) - }, timeout) - }) + reject(new Error('Error: Request Timed Out')); + }, timeout); + }); - promises.push(timeoutPromise) + promises.push(timeoutPromise); } Promise.race(promises) .then(resolve) .catch(reject) .finally(() => { - clearTimeout(timeoutId) - }) - }) + clearTimeout(timeoutId); + }); + }); } async get( url: string, params?: { [key: string]: any }, - config?: Record - ): Promise + config?: Record, + ): Promise; async get( url: string, params?: { [key: string]: any }, - config?: Record - ): Promise + config?: Record, + ): Promise; async get( url: string, params?: { [key: string]: any }, - config?: Record + config?: Record, ): Promise { return await this.request({ method: 'GET', url, params, config, - }) + }); } async post( url: string, data?: T, params?: { [key: string]: any }, - config?: Record - ): Promise + config?: Record, + ): Promise; async post( url: string, data?: any, params?: { [key: string]: any }, - config?: Record + config?: Record, ): Promise { return await this.request({ method: 'POST', @@ -252,21 +252,21 @@ class HttpRequests { body: data, params, config, - }) + }); } async put( url: string, data?: T, params?: { [key: string]: any }, - config?: Record - ): Promise + config?: Record, + ): Promise; async put( url: string, data?: any, params?: { [key: string]: any }, - config?: Record + config?: Record, ): Promise { return await this.request({ method: 'PUT', @@ -274,14 +274,14 @@ class HttpRequests { body: data, params, config, - }) + }); } async patch( url: string, data?: any, params?: { [key: string]: any }, - config?: Record + config?: Record, ): Promise { return await this.request({ method: 'PATCH', @@ -289,26 +289,26 @@ class HttpRequests { body: data, params, config, - }) + }); } async delete( url: string, data?: any, params?: { [key: string]: any }, - config?: Record - ): Promise + config?: Record, + ): Promise; async delete( url: string, data?: any, params?: { [key: string]: any }, - config?: Record - ): Promise + config?: Record, + ): Promise; async delete( url: string, data?: any, params?: { [key: string]: any }, - config?: Record + config?: Record, ): Promise { return await this.request({ method: 'DELETE', @@ -316,8 +316,8 @@ class HttpRequests { body: data, params, config, - }) + }); } } -export { HttpRequests, toQueryParams } +export { HttpRequests, toQueryParams }; diff --git a/src/index.ts b/src/index.ts index c2c6d86ba..62fbca731 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,9 +1,9 @@ -export * from './types' -export * from './errors' -export * from './indexes' -export * from './enqueued-task' -export * from './task' -import { MeiliSearch } from './clients/node-client' +export * from './types'; +export * from './errors'; +export * from './indexes'; +export * from './enqueued-task'; +export * from './task'; +import { MeiliSearch } from './clients/node-client'; -export { MeiliSearch, MeiliSearch as Meilisearch } -export default MeiliSearch +export { MeiliSearch, MeiliSearch as Meilisearch }; +export default MeiliSearch; diff --git a/src/indexes.ts b/src/indexes.ts index a03b3a9cb..a2451ae8b 100644 --- a/src/indexes.ts +++ b/src/indexes.ts @@ -5,14 +5,14 @@ * Copyright: 2019, MeiliSearch */ -'use strict' +'use strict'; import { MeiliSearchError, MeiliSearchRequestError, versionErrorHintMessage, MeiliSearchApiError, -} from './errors' +} from './errors'; import { Config, SearchResponse, @@ -53,19 +53,19 @@ import { ProximityPrecision, Embedders, SearchCutoffMs, -} from './types' -import { removeUndefinedFromObject } from './utils' -import { HttpRequests } from './http-requests' -import { Task, TaskClient } from './task' -import { EnqueuedTask } from './enqueued-task' +} from './types'; +import { removeUndefinedFromObject } from './utils'; +import { HttpRequests } from './http-requests'; +import { Task, TaskClient } from './task'; +import { EnqueuedTask } from './enqueued-task'; class Index = Record> { - uid: string - primaryKey: string | undefined - createdAt: Date | undefined - updatedAt: Date | undefined - httpRequest: HttpRequests - tasks: TaskClient + uid: string; + primaryKey: string | undefined; + createdAt: Date | undefined; + updatedAt: Date | undefined; + httpRequest: HttpRequests; + tasks: TaskClient; /** * @param config - Request configuration options @@ -73,10 +73,10 @@ class Index = Record> { * @param primaryKey - Primary Key of the index */ constructor(config: Config, uid: string, primaryKey?: string) { - this.uid = uid - this.primaryKey = primaryKey - this.httpRequest = new HttpRequests(config) - this.tasks = new TaskClient(config) + this.uid = uid; + this.primaryKey = primaryKey; + this.httpRequest = new HttpRequests(config); + this.tasks = new TaskClient(config); } /// @@ -97,16 +97,16 @@ class Index = Record> { >( query?: string | null, options?: S, - config?: Partial + config?: Partial, ): Promise> { - const url = `indexes/${this.uid}/search` + const url = `indexes/${this.uid}/search`; return await this.httpRequest.post( url, removeUndefinedFromObject({ q: query, ...options }), undefined, - config - ) + config, + ); } /** @@ -123,18 +123,18 @@ class Index = Record> { >( query?: string | null, options?: S, - config?: Partial + config?: Partial, ): Promise> { - const url = `indexes/${this.uid}/search` + const url = `indexes/${this.uid}/search`; const parseFilter = (filter?: Filter): string | undefined => { - if (typeof filter === 'string') return filter + if (typeof filter === 'string') return filter; else if (Array.isArray(filter)) throw new MeiliSearchError( - 'The filter query parameter should be in string format when using searchGet' - ) - else return undefined - } + 'The filter query parameter should be in string format when using searchGet', + ); + else return undefined; + }; const getParams: SearchRequestGET = { q: query, @@ -147,13 +147,13 @@ class Index = Record> { attributesToHighlight: options?.attributesToHighlight?.join(','), vector: options?.vector?.join(','), attributesToSearchOn: options?.attributesToSearchOn?.join(','), - } + }; return await this.httpRequest.get>( url, removeUndefinedFromObject(getParams), - config - ) + config, + ); } /** @@ -165,16 +165,16 @@ class Index = Record> { */ async searchForFacetValues( params: SearchForFacetValuesParams, - config?: Partial + config?: Partial, ): Promise { - const url = `indexes/${this.uid}/facet-search` + const url = `indexes/${this.uid}/facet-search`; return await this.httpRequest.post( url, removeUndefinedFromObject(params), undefined, - config - ) + config, + ); } /// @@ -187,12 +187,12 @@ class Index = Record> { * @returns Promise containing index information */ async getRawInfo(): Promise { - const url = `indexes/${this.uid}` - const res = await this.httpRequest.get(url) - this.primaryKey = res.primaryKey - this.updatedAt = new Date(res.updatedAt) - this.createdAt = new Date(res.createdAt) - return res + const url = `indexes/${this.uid}`; + const res = await this.httpRequest.get(url); + this.primaryKey = res.primaryKey; + this.updatedAt = new Date(res.updatedAt); + this.createdAt = new Date(res.createdAt); + return res; } /** @@ -201,8 +201,8 @@ class Index = Record> { * @returns Promise to the current Index object with updated information */ async fetchInfo(): Promise { - await this.getRawInfo() - return this + await this.getRawInfo(); + return this; } /** @@ -211,8 +211,8 @@ class Index = Record> { * @returns Promise containing the Primary Key of the index */ async fetchPrimaryKey(): Promise { - this.primaryKey = (await this.getRawInfo()).primaryKey - return this.primaryKey + this.primaryKey = (await this.getRawInfo()).primaryKey; + return this.primaryKey; } /** @@ -226,13 +226,13 @@ class Index = Record> { static async create( uid: string, options: IndexOptions = {}, - config: Config + config: Config, ): Promise { - const url = `indexes` - const req = new HttpRequests(config) - const task = await req.post(url, { ...options, uid }) + const url = `indexes`; + const req = new HttpRequests(config); + const task = await req.post(url, { ...options, uid }); - return new EnqueuedTask(task) + return new EnqueuedTask(task); } /** @@ -242,12 +242,12 @@ class Index = Record> { * @returns Promise to the current Index object with updated information */ async update(data: IndexOptions): Promise { - const url = `indexes/${this.uid}` - const task = await this.httpRequest.patch(url, data) + const url = `indexes/${this.uid}`; + const task = await this.httpRequest.patch(url, data); - task.enqueuedAt = new Date(task.enqueuedAt) + task.enqueuedAt = new Date(task.enqueuedAt); - return task + return task; } /** @@ -256,10 +256,10 @@ class Index = Record> { * @returns Promise which resolves when index is deleted successfully */ async delete(): Promise { - const url = `indexes/${this.uid}` - const task = await this.httpRequest.delete(url) + const url = `indexes/${this.uid}`; + const task = await this.httpRequest.delete(url); - return new EnqueuedTask(task) + return new EnqueuedTask(task); } /// @@ -273,7 +273,7 @@ class Index = Record> { * @returns Promise containing all tasks */ async getTasks(parameters: TasksQuery = {}): Promise { - return await this.tasks.getTasks({ ...parameters, indexUids: [this.uid] }) + return await this.tasks.getTasks({ ...parameters, indexUids: [this.uid] }); } /** @@ -283,7 +283,7 @@ class Index = Record> { * @returns Promise containing a task */ async getTask(taskUid: number): Promise { - return await this.tasks.getTask(taskUid) + return await this.tasks.getTask(taskUid); } /** @@ -295,12 +295,12 @@ class Index = Record> { */ async waitForTasks( taskUids: number[], - { timeOutMs = 5000, intervalMs = 50 }: WaitOptions = {} + { timeOutMs = 5000, intervalMs = 50 }: WaitOptions = {}, ): Promise { return await this.tasks.waitForTasks(taskUids, { timeOutMs, intervalMs, - }) + }); } /** @@ -312,12 +312,12 @@ class Index = Record> { */ async waitForTask( taskUid: number, - { timeOutMs = 5000, intervalMs = 50 }: WaitOptions = {} + { timeOutMs = 5000, intervalMs = 50 }: WaitOptions = {}, ): Promise { return await this.tasks.waitForTask(taskUid, { timeOutMs, intervalMs, - }) + }); } /// @@ -330,8 +330,8 @@ class Index = Record> { * @returns Promise containing object with stats of the index */ async getStats(): Promise { - const url = `indexes/${this.uid}/stats` - return await this.httpRequest.get(url) + const url = `indexes/${this.uid}/stats`; + return await this.httpRequest.get(url); } /// @@ -346,41 +346,41 @@ class Index = Record> { * @returns Promise containing the returned documents */ async getDocuments = T>( - parameters: DocumentsQuery = {} + parameters: DocumentsQuery = {}, ): Promise> { - parameters = removeUndefinedFromObject(parameters) + parameters = removeUndefinedFromObject(parameters); // In case `filter` is provided, use `POST /documents/fetch` if (parameters.filter !== undefined) { try { - const url = `indexes/${this.uid}/documents/fetch` + const url = `indexes/${this.uid}/documents/fetch`; return await this.httpRequest.post< DocumentsQuery, Promise> - >(url, parameters) + >(url, parameters); } catch (e) { if (e instanceof MeiliSearchRequestError) { - e.message = versionErrorHintMessage(e.message, 'getDocuments') + e.message = versionErrorHintMessage(e.message, 'getDocuments'); } else if (e instanceof MeiliSearchApiError) { - e.message = versionErrorHintMessage(e.message, 'getDocuments') + e.message = versionErrorHintMessage(e.message, 'getDocuments'); } - throw e + throw e; } // Else use `GET /documents` method } else { - const url = `indexes/${this.uid}/documents` + const url = `indexes/${this.uid}/documents`; // Transform fields to query parameter string format const fields = Array.isArray(parameters?.fields) ? { fields: parameters?.fields?.join(',') } - : {} + : {}; return await this.httpRequest.get>>(url, { ...parameters, ...fields, - }) + }); } } @@ -393,24 +393,24 @@ class Index = Record> { */ async getDocument = T>( documentId: string | number, - parameters?: DocumentQuery + parameters?: DocumentQuery, ): Promise { - const url = `indexes/${this.uid}/documents/${documentId}` + const url = `indexes/${this.uid}/documents/${documentId}`; const fields = (() => { if (Array.isArray(parameters?.fields)) { - return parameters?.fields?.join(',') + return parameters?.fields?.join(','); } - return undefined - })() + return undefined; + })(); return await this.httpRequest.get( url, removeUndefinedFromObject({ ...parameters, fields, - }) - ) + }), + ); } /** @@ -422,12 +422,12 @@ class Index = Record> { */ async addDocuments( documents: T[], - options?: DocumentOptions + options?: DocumentOptions, ): Promise { - const url = `indexes/${this.uid}/documents` - const task = await this.httpRequest.post(url, documents, options) + const url = `indexes/${this.uid}/documents`; + const task = await this.httpRequest.post(url, documents, options); - return new EnqueuedTask(task) + return new EnqueuedTask(task); } /** @@ -443,17 +443,17 @@ class Index = Record> { async addDocumentsFromString( documents: string, contentType: ContentType, - queryParams?: RawDocumentAdditionOptions + queryParams?: RawDocumentAdditionOptions, ): Promise { - const url = `indexes/${this.uid}/documents` + const url = `indexes/${this.uid}/documents`; const task = await this.httpRequest.post(url, documents, queryParams, { headers: { 'Content-Type': contentType, }, - }) + }); - return new EnqueuedTask(task) + return new EnqueuedTask(task); } /** @@ -467,15 +467,15 @@ class Index = Record> { async addDocumentsInBatches( documents: T[], batchSize = 1000, - options?: DocumentOptions + options?: DocumentOptions, ): Promise { - const updates = [] + const updates = []; for (let i = 0; i < documents.length; i += batchSize) { updates.push( - await this.addDocuments(documents.slice(i, i + batchSize), options) - ) + await this.addDocuments(documents.slice(i, i + batchSize), options), + ); } - return updates + return updates; } /** @@ -487,12 +487,12 @@ class Index = Record> { */ async updateDocuments( documents: Array>, - options?: DocumentOptions + options?: DocumentOptions, ): Promise { - const url = `indexes/${this.uid}/documents` - const task = await this.httpRequest.put(url, documents, options) + const url = `indexes/${this.uid}/documents`; + const task = await this.httpRequest.put(url, documents, options); - return new EnqueuedTask(task) + return new EnqueuedTask(task); } /** @@ -506,15 +506,15 @@ class Index = Record> { async updateDocumentsInBatches( documents: Array>, batchSize = 1000, - options?: DocumentOptions + options?: DocumentOptions, ): Promise { - const updates = [] + const updates = []; for (let i = 0; i < documents.length; i += batchSize) { updates.push( - await this.updateDocuments(documents.slice(i, i + batchSize), options) - ) + await this.updateDocuments(documents.slice(i, i + batchSize), options), + ); } - return updates + return updates; } /** @@ -530,17 +530,17 @@ class Index = Record> { async updateDocumentsFromString( documents: string, contentType: ContentType, - queryParams?: RawDocumentAdditionOptions + queryParams?: RawDocumentAdditionOptions, ): Promise { - const url = `indexes/${this.uid}/documents` + const url = `indexes/${this.uid}/documents`; const task = await this.httpRequest.put(url, documents, queryParams, { headers: { 'Content-Type': contentType, }, - }) + }); - return new EnqueuedTask(task) + return new EnqueuedTask(task); } /** @@ -550,12 +550,12 @@ class Index = Record> { * @returns Promise containing an EnqueuedTask */ async deleteDocument(documentId: string | number): Promise { - const url = `indexes/${this.uid}/documents/${documentId}` - const task = await this.httpRequest.delete(url) + const url = `indexes/${this.uid}/documents/${documentId}`; + const task = await this.httpRequest.delete(url); - task.enqueuedAt = new Date(task.enqueuedAt) + task.enqueuedAt = new Date(task.enqueuedAt); - return task + return task; } /** @@ -570,28 +570,28 @@ class Index = Record> { * @returns Promise containing an EnqueuedTask */ async deleteDocuments( - params: DocumentsDeletionQuery | DocumentsIds + params: DocumentsDeletionQuery | DocumentsIds, ): Promise { // If params is of type DocumentsDeletionQuery const isDocumentsDeletionQuery = - !Array.isArray(params) && typeof params === 'object' + !Array.isArray(params) && typeof params === 'object'; const endpoint = isDocumentsDeletionQuery ? 'documents/delete' - : 'documents/delete-batch' - const url = `indexes/${this.uid}/${endpoint}` + : 'documents/delete-batch'; + const url = `indexes/${this.uid}/${endpoint}`; try { - const task = await this.httpRequest.post(url, params) + const task = await this.httpRequest.post(url, params); - return new EnqueuedTask(task) + return new EnqueuedTask(task); } catch (e) { if (e instanceof MeiliSearchRequestError && isDocumentsDeletionQuery) { - e.message = versionErrorHintMessage(e.message, 'deleteDocuments') + e.message = versionErrorHintMessage(e.message, 'deleteDocuments'); } else if (e instanceof MeiliSearchApiError) { - e.message = versionErrorHintMessage(e.message, 'deleteDocuments') + e.message = versionErrorHintMessage(e.message, 'deleteDocuments'); } - throw e + throw e; } } @@ -601,12 +601,12 @@ class Index = Record> { * @returns Promise containing an EnqueuedTask */ async deleteAllDocuments(): Promise { - const url = `indexes/${this.uid}/documents` - const task = await this.httpRequest.delete(url) + const url = `indexes/${this.uid}/documents`; + const task = await this.httpRequest.delete(url); - task.enqueuedAt = new Date(task.enqueuedAt) + task.enqueuedAt = new Date(task.enqueuedAt); - return task + return task; } /// @@ -619,8 +619,8 @@ class Index = Record> { * @returns Promise containing Settings object */ async getSettings(): Promise { - const url = `indexes/${this.uid}/settings` - return await this.httpRequest.get(url) + const url = `indexes/${this.uid}/settings`; + return await this.httpRequest.get(url); } /** @@ -630,12 +630,12 @@ class Index = Record> { * @returns Promise containing an EnqueuedTask */ async updateSettings(settings: Settings): Promise { - const url = `indexes/${this.uid}/settings` - const task = await this.httpRequest.patch(url, settings) + const url = `indexes/${this.uid}/settings`; + const task = await this.httpRequest.patch(url, settings); - task.enqueued = new Date(task.enqueuedAt) + task.enqueued = new Date(task.enqueuedAt); - return task + return task; } /** @@ -644,12 +644,12 @@ class Index = Record> { * @returns Promise containing an EnqueuedTask */ async resetSettings(): Promise { - const url = `indexes/${this.uid}/settings` - const task = await this.httpRequest.delete(url) + const url = `indexes/${this.uid}/settings`; + const task = await this.httpRequest.delete(url); - task.enqueuedAt = new Date(task.enqueuedAt) + task.enqueuedAt = new Date(task.enqueuedAt); - return task + return task; } /// @@ -662,8 +662,8 @@ class Index = Record> { * @returns Promise containing object of pagination settings */ async getPagination(): Promise { - const url = `indexes/${this.uid}/settings/pagination` - return await this.httpRequest.get(url) + const url = `indexes/${this.uid}/settings/pagination`; + return await this.httpRequest.get(url); } /** @@ -673,12 +673,12 @@ class Index = Record> { * @returns Promise containing an EnqueuedTask */ async updatePagination( - pagination: PaginationSettings + pagination: PaginationSettings, ): Promise { - const url = `indexes/${this.uid}/settings/pagination` - const task = await this.httpRequest.patch(url, pagination) + const url = `indexes/${this.uid}/settings/pagination`; + const task = await this.httpRequest.patch(url, pagination); - return new EnqueuedTask(task) + return new EnqueuedTask(task); } /** @@ -687,10 +687,10 @@ class Index = Record> { * @returns Promise containing an EnqueuedTask */ async resetPagination(): Promise { - const url = `indexes/${this.uid}/settings/pagination` - const task = await this.httpRequest.delete(url) + const url = `indexes/${this.uid}/settings/pagination`; + const task = await this.httpRequest.delete(url); - return new EnqueuedTask(task) + return new EnqueuedTask(task); } /// @@ -703,8 +703,8 @@ class Index = Record> { * @returns Promise containing object of synonym mappings */ async getSynonyms(): Promise { - const url = `indexes/${this.uid}/settings/synonyms` - return await this.httpRequest.get(url) + const url = `indexes/${this.uid}/settings/synonyms`; + return await this.httpRequest.get(url); } /** @@ -714,10 +714,10 @@ class Index = Record> { * @returns Promise containing an EnqueuedTask */ async updateSynonyms(synonyms: Synonyms): Promise { - const url = `indexes/${this.uid}/settings/synonyms` - const task = await this.httpRequest.put(url, synonyms) + const url = `indexes/${this.uid}/settings/synonyms`; + const task = await this.httpRequest.put(url, synonyms); - return new EnqueuedTask(task) + return new EnqueuedTask(task); } /** @@ -726,12 +726,12 @@ class Index = Record> { * @returns Promise containing an EnqueuedTask */ async resetSynonyms(): Promise { - const url = `indexes/${this.uid}/settings/synonyms` - const task = await this.httpRequest.delete(url) + const url = `indexes/${this.uid}/settings/synonyms`; + const task = await this.httpRequest.delete(url); - task.enqueuedAt = new Date(task.enqueuedAt) + task.enqueuedAt = new Date(task.enqueuedAt); - return task + return task; } /// @@ -744,8 +744,8 @@ class Index = Record> { * @returns Promise containing array of stop-words */ async getStopWords(): Promise { - const url = `indexes/${this.uid}/settings/stop-words` - return await this.httpRequest.get(url) + const url = `indexes/${this.uid}/settings/stop-words`; + return await this.httpRequest.get(url); } /** @@ -755,10 +755,10 @@ class Index = Record> { * @returns Promise containing an EnqueuedTask */ async updateStopWords(stopWords: StopWords): Promise { - const url = `indexes/${this.uid}/settings/stop-words` - const task = await this.httpRequest.put(url, stopWords) + const url = `indexes/${this.uid}/settings/stop-words`; + const task = await this.httpRequest.put(url, stopWords); - return new EnqueuedTask(task) + return new EnqueuedTask(task); } /** @@ -767,12 +767,12 @@ class Index = Record> { * @returns Promise containing an EnqueuedTask */ async resetStopWords(): Promise { - const url = `indexes/${this.uid}/settings/stop-words` - const task = await this.httpRequest.delete(url) + const url = `indexes/${this.uid}/settings/stop-words`; + const task = await this.httpRequest.delete(url); - task.enqueuedAt = new Date(task.enqueuedAt) + task.enqueuedAt = new Date(task.enqueuedAt); - return task + return task; } /// @@ -785,8 +785,8 @@ class Index = Record> { * @returns Promise containing array of ranking-rules */ async getRankingRules(): Promise { - const url = `indexes/${this.uid}/settings/ranking-rules` - return await this.httpRequest.get(url) + const url = `indexes/${this.uid}/settings/ranking-rules`; + return await this.httpRequest.get(url); } /** @@ -797,10 +797,10 @@ class Index = Record> { * @returns Promise containing an EnqueuedTask */ async updateRankingRules(rankingRules: RankingRules): Promise { - const url = `indexes/${this.uid}/settings/ranking-rules` - const task = await this.httpRequest.put(url, rankingRules) + const url = `indexes/${this.uid}/settings/ranking-rules`; + const task = await this.httpRequest.put(url, rankingRules); - return new EnqueuedTask(task) + return new EnqueuedTask(task); } /** @@ -809,12 +809,12 @@ class Index = Record> { * @returns Promise containing an EnqueuedTask */ async resetRankingRules(): Promise { - const url = `indexes/${this.uid}/settings/ranking-rules` - const task = await this.httpRequest.delete(url) + const url = `indexes/${this.uid}/settings/ranking-rules`; + const task = await this.httpRequest.delete(url); - task.enqueuedAt = new Date(task.enqueuedAt) + task.enqueuedAt = new Date(task.enqueuedAt); - return task + return task; } /// @@ -827,8 +827,8 @@ class Index = Record> { * @returns Promise containing the distinct-attribute of the index */ async getDistinctAttribute(): Promise { - const url = `indexes/${this.uid}/settings/distinct-attribute` - return await this.httpRequest.get(url) + const url = `indexes/${this.uid}/settings/distinct-attribute`; + return await this.httpRequest.get(url); } /** @@ -838,12 +838,12 @@ class Index = Record> { * @returns Promise containing an EnqueuedTask */ async updateDistinctAttribute( - distinctAttribute: DistinctAttribute + distinctAttribute: DistinctAttribute, ): Promise { - const url = `indexes/${this.uid}/settings/distinct-attribute` - const task = await this.httpRequest.put(url, distinctAttribute) + const url = `indexes/${this.uid}/settings/distinct-attribute`; + const task = await this.httpRequest.put(url, distinctAttribute); - return new EnqueuedTask(task) + return new EnqueuedTask(task); } /** @@ -852,12 +852,12 @@ class Index = Record> { * @returns Promise containing an EnqueuedTask */ async resetDistinctAttribute(): Promise { - const url = `indexes/${this.uid}/settings/distinct-attribute` - const task = await this.httpRequest.delete(url) + const url = `indexes/${this.uid}/settings/distinct-attribute`; + const task = await this.httpRequest.delete(url); - task.enqueuedAt = new Date(task.enqueuedAt) + task.enqueuedAt = new Date(task.enqueuedAt); - return task + return task; } /// @@ -870,8 +870,8 @@ class Index = Record> { * @returns Promise containing an array of filterable-attributes */ async getFilterableAttributes(): Promise { - const url = `indexes/${this.uid}/settings/filterable-attributes` - return await this.httpRequest.get(url) + const url = `indexes/${this.uid}/settings/filterable-attributes`; + return await this.httpRequest.get(url); } /** @@ -882,12 +882,12 @@ class Index = Record> { * @returns Promise containing an EnqueuedTask */ async updateFilterableAttributes( - filterableAttributes: FilterableAttributes + filterableAttributes: FilterableAttributes, ): Promise { - const url = `indexes/${this.uid}/settings/filterable-attributes` - const task = await this.httpRequest.put(url, filterableAttributes) + const url = `indexes/${this.uid}/settings/filterable-attributes`; + const task = await this.httpRequest.put(url, filterableAttributes); - return new EnqueuedTask(task) + return new EnqueuedTask(task); } /** @@ -896,12 +896,12 @@ class Index = Record> { * @returns Promise containing an EnqueuedTask */ async resetFilterableAttributes(): Promise { - const url = `indexes/${this.uid}/settings/filterable-attributes` - const task = await this.httpRequest.delete(url) + const url = `indexes/${this.uid}/settings/filterable-attributes`; + const task = await this.httpRequest.delete(url); - task.enqueuedAt = new Date(task.enqueuedAt) + task.enqueuedAt = new Date(task.enqueuedAt); - return task + return task; } /// @@ -914,8 +914,8 @@ class Index = Record> { * @returns Promise containing array of sortable-attributes */ async getSortableAttributes(): Promise { - const url = `indexes/${this.uid}/settings/sortable-attributes` - return await this.httpRequest.get(url) + const url = `indexes/${this.uid}/settings/sortable-attributes`; + return await this.httpRequest.get(url); } /** @@ -926,12 +926,12 @@ class Index = Record> { * @returns Promise containing an EnqueuedTask */ async updateSortableAttributes( - sortableAttributes: SortableAttributes + sortableAttributes: SortableAttributes, ): Promise { - const url = `indexes/${this.uid}/settings/sortable-attributes` - const task = await this.httpRequest.put(url, sortableAttributes) + const url = `indexes/${this.uid}/settings/sortable-attributes`; + const task = await this.httpRequest.put(url, sortableAttributes); - return new EnqueuedTask(task) + return new EnqueuedTask(task); } /** @@ -940,12 +940,12 @@ class Index = Record> { * @returns Promise containing an EnqueuedTask */ async resetSortableAttributes(): Promise { - const url = `indexes/${this.uid}/settings/sortable-attributes` - const task = await this.httpRequest.delete(url) + const url = `indexes/${this.uid}/settings/sortable-attributes`; + const task = await this.httpRequest.delete(url); - task.enqueuedAt = new Date(task.enqueuedAt) + task.enqueuedAt = new Date(task.enqueuedAt); - return task + return task; } /// @@ -958,8 +958,8 @@ class Index = Record> { * @returns Promise containing array of searchable-attributes */ async getSearchableAttributes(): Promise { - const url = `indexes/${this.uid}/settings/searchable-attributes` - return await this.httpRequest.get(url) + const url = `indexes/${this.uid}/settings/searchable-attributes`; + return await this.httpRequest.get(url); } /** @@ -970,12 +970,12 @@ class Index = Record> { * @returns Promise containing an EnqueuedTask */ async updateSearchableAttributes( - searchableAttributes: SearchableAttributes + searchableAttributes: SearchableAttributes, ): Promise { - const url = `indexes/${this.uid}/settings/searchable-attributes` - const task = await this.httpRequest.put(url, searchableAttributes) + const url = `indexes/${this.uid}/settings/searchable-attributes`; + const task = await this.httpRequest.put(url, searchableAttributes); - return new EnqueuedTask(task) + return new EnqueuedTask(task); } /** @@ -984,12 +984,12 @@ class Index = Record> { * @returns Promise containing an EnqueuedTask */ async resetSearchableAttributes(): Promise { - const url = `indexes/${this.uid}/settings/searchable-attributes` - const task = await this.httpRequest.delete(url) + const url = `indexes/${this.uid}/settings/searchable-attributes`; + const task = await this.httpRequest.delete(url); - task.enqueuedAt = new Date(task.enqueuedAt) + task.enqueuedAt = new Date(task.enqueuedAt); - return task + return task; } /// @@ -1002,8 +1002,8 @@ class Index = Record> { * @returns Promise containing array of displayed-attributes */ async getDisplayedAttributes(): Promise { - const url = `indexes/${this.uid}/settings/displayed-attributes` - return await this.httpRequest.get(url) + const url = `indexes/${this.uid}/settings/displayed-attributes`; + return await this.httpRequest.get(url); } /** @@ -1014,12 +1014,12 @@ class Index = Record> { * @returns Promise containing an EnqueuedTask */ async updateDisplayedAttributes( - displayedAttributes: DisplayedAttributes + displayedAttributes: DisplayedAttributes, ): Promise { - const url = `indexes/${this.uid}/settings/displayed-attributes` - const task = await this.httpRequest.put(url, displayedAttributes) + const url = `indexes/${this.uid}/settings/displayed-attributes`; + const task = await this.httpRequest.put(url, displayedAttributes); - return new EnqueuedTask(task) + return new EnqueuedTask(task); } /** @@ -1028,12 +1028,12 @@ class Index = Record> { * @returns Promise containing an EnqueuedTask */ async resetDisplayedAttributes(): Promise { - const url = `indexes/${this.uid}/settings/displayed-attributes` - const task = await this.httpRequest.delete(url) + const url = `indexes/${this.uid}/settings/displayed-attributes`; + const task = await this.httpRequest.delete(url); - task.enqueuedAt = new Date(task.enqueuedAt) + task.enqueuedAt = new Date(task.enqueuedAt); - return task + return task; } /// @@ -1046,8 +1046,8 @@ class Index = Record> { * @returns Promise containing the typo tolerance settings. */ async getTypoTolerance(): Promise { - const url = `indexes/${this.uid}/settings/typo-tolerance` - return await this.httpRequest.get(url) + const url = `indexes/${this.uid}/settings/typo-tolerance`; + return await this.httpRequest.get(url); } /** @@ -1058,14 +1058,14 @@ class Index = Record> { * @returns Promise containing object of the enqueued update */ async updateTypoTolerance( - typoTolerance: TypoTolerance + typoTolerance: TypoTolerance, ): Promise { - const url = `indexes/${this.uid}/settings/typo-tolerance` - const task = await this.httpRequest.patch(url, typoTolerance) + const url = `indexes/${this.uid}/settings/typo-tolerance`; + const task = await this.httpRequest.patch(url, typoTolerance); - task.enqueuedAt = new Date(task.enqueuedAt) + task.enqueuedAt = new Date(task.enqueuedAt); - return task + return task; } /** @@ -1074,12 +1074,12 @@ class Index = Record> { * @returns Promise containing object of the enqueued update */ async resetTypoTolerance(): Promise { - const url = `indexes/${this.uid}/settings/typo-tolerance` - const task = await this.httpRequest.delete(url) + const url = `indexes/${this.uid}/settings/typo-tolerance`; + const task = await this.httpRequest.delete(url); - task.enqueuedAt = new Date(task.enqueuedAt) + task.enqueuedAt = new Date(task.enqueuedAt); - return task + return task; } /// @@ -1092,8 +1092,8 @@ class Index = Record> { * @returns Promise containing object of faceting index settings */ async getFaceting(): Promise { - const url = `indexes/${this.uid}/settings/faceting` - return await this.httpRequest.get(url) + const url = `indexes/${this.uid}/settings/faceting`; + return await this.httpRequest.get(url); } /** @@ -1103,10 +1103,10 @@ class Index = Record> { * @returns Promise containing an EnqueuedTask */ async updateFaceting(faceting: Faceting): Promise { - const url = `indexes/${this.uid}/settings/faceting` - const task = await this.httpRequest.patch(url, faceting) + const url = `indexes/${this.uid}/settings/faceting`; + const task = await this.httpRequest.patch(url, faceting); - return new EnqueuedTask(task) + return new EnqueuedTask(task); } /** @@ -1115,10 +1115,10 @@ class Index = Record> { * @returns Promise containing an EnqueuedTask */ async resetFaceting(): Promise { - const url = `indexes/${this.uid}/settings/faceting` - const task = await this.httpRequest.delete(url) + const url = `indexes/${this.uid}/settings/faceting`; + const task = await this.httpRequest.delete(url); - return new EnqueuedTask(task) + return new EnqueuedTask(task); } /// @@ -1131,8 +1131,8 @@ class Index = Record> { * @returns Promise containing array of separator tokens */ async getSeparatorTokens(): Promise { - const url = `indexes/${this.uid}/settings/separator-tokens` - return await this.httpRequest.get(url) + const url = `indexes/${this.uid}/settings/separator-tokens`; + return await this.httpRequest.get(url); } /** @@ -1142,12 +1142,12 @@ class Index = Record> { * @returns Promise containing an EnqueuedTask or null */ async updateSeparatorTokens( - separatorTokens: SeparatorTokens + separatorTokens: SeparatorTokens, ): Promise { - const url = `indexes/${this.uid}/settings/separator-tokens` - const task = await this.httpRequest.put(url, separatorTokens) + const url = `indexes/${this.uid}/settings/separator-tokens`; + const task = await this.httpRequest.put(url, separatorTokens); - return new EnqueuedTask(task) + return new EnqueuedTask(task); } /** @@ -1156,12 +1156,12 @@ class Index = Record> { * @returns Promise containing an EnqueuedTask */ async resetSeparatorTokens(): Promise { - const url = `indexes/${this.uid}/settings/separator-tokens` - const task = await this.httpRequest.delete(url) + const url = `indexes/${this.uid}/settings/separator-tokens`; + const task = await this.httpRequest.delete(url); - task.enqueuedAt = new Date(task.enqueuedAt) + task.enqueuedAt = new Date(task.enqueuedAt); - return task + return task; } /// @@ -1174,8 +1174,8 @@ class Index = Record> { * @returns Promise containing array of non-separator tokens */ async getNonSeparatorTokens(): Promise { - const url = `indexes/${this.uid}/settings/non-separator-tokens` - return await this.httpRequest.get(url) + const url = `indexes/${this.uid}/settings/non-separator-tokens`; + return await this.httpRequest.get(url); } /** @@ -1185,12 +1185,12 @@ class Index = Record> { * @returns Promise containing an EnqueuedTask or null */ async updateNonSeparatorTokens( - nonSeparatorTokens: NonSeparatorTokens + nonSeparatorTokens: NonSeparatorTokens, ): Promise { - const url = `indexes/${this.uid}/settings/non-separator-tokens` - const task = await this.httpRequest.put(url, nonSeparatorTokens) + const url = `indexes/${this.uid}/settings/non-separator-tokens`; + const task = await this.httpRequest.put(url, nonSeparatorTokens); - return new EnqueuedTask(task) + return new EnqueuedTask(task); } /** @@ -1199,12 +1199,12 @@ class Index = Record> { * @returns Promise containing an EnqueuedTask */ async resetNonSeparatorTokens(): Promise { - const url = `indexes/${this.uid}/settings/non-separator-tokens` - const task = await this.httpRequest.delete(url) + const url = `indexes/${this.uid}/settings/non-separator-tokens`; + const task = await this.httpRequest.delete(url); - task.enqueuedAt = new Date(task.enqueuedAt) + task.enqueuedAt = new Date(task.enqueuedAt); - return task + return task; } /// @@ -1217,8 +1217,8 @@ class Index = Record> { * @returns Promise containing the dictionary settings */ async getDictionary(): Promise { - const url = `indexes/${this.uid}/settings/dictionary` - return await this.httpRequest.get(url) + const url = `indexes/${this.uid}/settings/dictionary`; + return await this.httpRequest.get(url); } /** @@ -1228,10 +1228,10 @@ class Index = Record> { * @returns Promise containing an EnqueuedTask or null */ async updateDictionary(dictionary: Dictionary): Promise { - const url = `indexes/${this.uid}/settings/dictionary` - const task = await this.httpRequest.put(url, dictionary) + const url = `indexes/${this.uid}/settings/dictionary`; + const task = await this.httpRequest.put(url, dictionary); - return new EnqueuedTask(task) + return new EnqueuedTask(task); } /** @@ -1240,12 +1240,12 @@ class Index = Record> { * @returns Promise containing an EnqueuedTask */ async resetDictionary(): Promise { - const url = `indexes/${this.uid}/settings/dictionary` - const task = await this.httpRequest.delete(url) + const url = `indexes/${this.uid}/settings/dictionary`; + const task = await this.httpRequest.delete(url); - task.enqueuedAt = new Date(task.enqueuedAt) + task.enqueuedAt = new Date(task.enqueuedAt); - return task + return task; } /// @@ -1258,8 +1258,8 @@ class Index = Record> { * @returns Promise containing the proximity precision settings */ async getProximityPrecision(): Promise { - const url = `indexes/${this.uid}/settings/proximity-precision` - return await this.httpRequest.get(url) + const url = `indexes/${this.uid}/settings/proximity-precision`; + return await this.httpRequest.get(url); } /** @@ -1270,12 +1270,12 @@ class Index = Record> { * @returns Promise containing an EnqueuedTask or null */ async updateProximityPrecision( - proximityPrecision: ProximityPrecision + proximityPrecision: ProximityPrecision, ): Promise { - const url = `indexes/${this.uid}/settings/proximity-precision` - const task = await this.httpRequest.put(url, proximityPrecision) + const url = `indexes/${this.uid}/settings/proximity-precision`; + const task = await this.httpRequest.put(url, proximityPrecision); - return new EnqueuedTask(task) + return new EnqueuedTask(task); } /** @@ -1284,12 +1284,12 @@ class Index = Record> { * @returns Promise containing an EnqueuedTask */ async resetProximityPrecision(): Promise { - const url = `indexes/${this.uid}/settings/proximity-precision` - const task = await this.httpRequest.delete(url) + const url = `indexes/${this.uid}/settings/proximity-precision`; + const task = await this.httpRequest.delete(url); - task.enqueuedAt = new Date(task.enqueuedAt) + task.enqueuedAt = new Date(task.enqueuedAt); - return task + return task; } /// @@ -1302,8 +1302,8 @@ class Index = Record> { * @returns Promise containing the embedders settings */ async getEmbedders(): Promise { - const url = `indexes/${this.uid}/settings/embedders` - return await this.httpRequest.get(url) + const url = `indexes/${this.uid}/settings/embedders`; + return await this.httpRequest.get(url); } /** @@ -1313,10 +1313,10 @@ class Index = Record> { * @returns Promise containing an EnqueuedTask or null */ async updateEmbedders(embedders: Embedders): Promise { - const url = `indexes/${this.uid}/settings/embedders` - const task = await this.httpRequest.patch(url, embedders) + const url = `indexes/${this.uid}/settings/embedders`; + const task = await this.httpRequest.patch(url, embedders); - return new EnqueuedTask(task) + return new EnqueuedTask(task); } /** @@ -1325,12 +1325,12 @@ class Index = Record> { * @returns Promise containing an EnqueuedTask */ async resetEmbedders(): Promise { - const url = `indexes/${this.uid}/settings/embedders` - const task = await this.httpRequest.delete(url) + const url = `indexes/${this.uid}/settings/embedders`; + const task = await this.httpRequest.delete(url); - task.enqueuedAt = new Date(task.enqueuedAt) + task.enqueuedAt = new Date(task.enqueuedAt); - return task + return task; } /// @@ -1343,8 +1343,8 @@ class Index = Record> { * @returns Promise containing object of SearchCutoffMs settings */ async getSearchCutoffMs(): Promise { - const url = `indexes/${this.uid}/settings/search-cutoff-ms` - return await this.httpRequest.get(url) + const url = `indexes/${this.uid}/settings/search-cutoff-ms`; + return await this.httpRequest.get(url); } /** @@ -1354,12 +1354,12 @@ class Index = Record> { * @returns Promise containing an EnqueuedTask */ async updateSearchCutoffMs( - searchCutoffMs: SearchCutoffMs + searchCutoffMs: SearchCutoffMs, ): Promise { - const url = `indexes/${this.uid}/settings/search-cutoff-ms` - const task = await this.httpRequest.put(url, searchCutoffMs) + const url = `indexes/${this.uid}/settings/search-cutoff-ms`; + const task = await this.httpRequest.put(url, searchCutoffMs); - return new EnqueuedTask(task) + return new EnqueuedTask(task); } /** @@ -1368,11 +1368,11 @@ class Index = Record> { * @returns Promise containing an EnqueuedTask */ async resetSearchCutoffMs(): Promise { - const url = `indexes/${this.uid}/settings/search-cutoff-ms` - const task = await this.httpRequest.delete(url) + const url = `indexes/${this.uid}/settings/search-cutoff-ms`; + const task = await this.httpRequest.delete(url); - return new EnqueuedTask(task) + return new EnqueuedTask(task); } } -export { Index } +export { Index }; diff --git a/src/package-version.ts b/src/package-version.ts index 59c013df5..8e07bf8b6 100644 --- a/src/package-version.ts +++ b/src/package-version.ts @@ -1 +1 @@ -export const PACKAGE_VERSION = '0.40.0' +export const PACKAGE_VERSION = '0.40.0'; diff --git a/src/task.ts b/src/task.ts index eda9a0c89..d2a77bf17 100644 --- a/src/task.ts +++ b/src/task.ts @@ -1,4 +1,4 @@ -import { MeiliSearchTimeOutError } from './errors' +import { MeiliSearchTimeOutError } from './errors'; import { Config, WaitOptions, @@ -9,45 +9,45 @@ import { CancelTasksQuery, TasksResultsObject, DeleteTasksQuery, -} from './types' -import { HttpRequests, toQueryParams } from './http-requests' -import { sleep } from './utils' -import { EnqueuedTask } from './enqueued-task' +} from './types'; +import { HttpRequests, toQueryParams } from './http-requests'; +import { sleep } from './utils'; +import { EnqueuedTask } from './enqueued-task'; class Task { - indexUid: TaskObject['indexUid'] - status: TaskObject['status'] - type: TaskObject['type'] - uid: TaskObject['uid'] - canceledBy: TaskObject['canceledBy'] - details: TaskObject['details'] - error: TaskObject['error'] - duration: TaskObject['duration'] - startedAt: Date - enqueuedAt: Date - finishedAt: Date + indexUid: TaskObject['indexUid']; + status: TaskObject['status']; + type: TaskObject['type']; + uid: TaskObject['uid']; + canceledBy: TaskObject['canceledBy']; + details: TaskObject['details']; + error: TaskObject['error']; + duration: TaskObject['duration']; + startedAt: Date; + enqueuedAt: Date; + finishedAt: Date; constructor(task: TaskObject) { - this.indexUid = task.indexUid - this.status = task.status - this.type = task.type - this.uid = task.uid - this.details = task.details - this.canceledBy = task.canceledBy - this.error = task.error - this.duration = task.duration - - this.startedAt = new Date(task.startedAt) - this.enqueuedAt = new Date(task.enqueuedAt) - this.finishedAt = new Date(task.finishedAt) + this.indexUid = task.indexUid; + this.status = task.status; + this.type = task.type; + this.uid = task.uid; + this.details = task.details; + this.canceledBy = task.canceledBy; + this.error = task.error; + this.duration = task.duration; + + this.startedAt = new Date(task.startedAt); + this.enqueuedAt = new Date(task.enqueuedAt); + this.finishedAt = new Date(task.finishedAt); } } class TaskClient { - httpRequest: HttpRequests + httpRequest: HttpRequests; constructor(config: Config) { - this.httpRequest = new HttpRequests(config) + this.httpRequest = new HttpRequests(config); } /** @@ -57,9 +57,9 @@ class TaskClient { * @returns */ async getTask(uid: number): Promise { - const url = `tasks/${uid}` - const taskItem = await this.httpRequest.get(url) - return new Task(taskItem) + const url = `tasks/${uid}`; + const taskItem = await this.httpRequest.get(url); + return new Task(taskItem); } /** @@ -69,17 +69,17 @@ class TaskClient { * @returns Promise containing all tasks */ async getTasks(parameters: TasksQuery = {}): Promise { - const url = `tasks` + const url = `tasks`; const tasks = await this.httpRequest.get>( url, - toQueryParams(parameters) - ) + toQueryParams(parameters), + ); return { ...tasks, results: tasks.results.map((task) => new Task(task)), - } + }; } /** @@ -91,11 +91,11 @@ class TaskClient { */ async waitForTask( taskUid: number, - { timeOutMs = 5000, intervalMs = 50 }: WaitOptions = {} + { timeOutMs = 5000, intervalMs = 50 }: WaitOptions = {}, ): Promise { - const startingTime = Date.now() + const startingTime = Date.now(); while (Date.now() - startingTime < timeOutMs) { - const response = await this.getTask(taskUid) + const response = await this.getTask(taskUid); if ( !( [ @@ -104,12 +104,12 @@ class TaskClient { ] as readonly string[] ).includes(response.status) ) - return response - await sleep(intervalMs) + return response; + await sleep(intervalMs); } throw new MeiliSearchTimeOutError( - `timeout of ${timeOutMs}ms has exceeded on process ${taskUid} when waiting a task to be resolved.` - ) + `timeout of ${timeOutMs}ms has exceeded on process ${taskUid} when waiting a task to be resolved.`, + ); } /** @@ -121,17 +121,17 @@ class TaskClient { */ async waitForTasks( taskUids: number[], - { timeOutMs = 5000, intervalMs = 50 }: WaitOptions = {} + { timeOutMs = 5000, intervalMs = 50 }: WaitOptions = {}, ): Promise { - const tasks: Task[] = [] + const tasks: Task[] = []; for (const taskUid of taskUids) { const task = await this.waitForTask(taskUid, { timeOutMs, intervalMs, - }) - tasks.push(task) + }); + tasks.push(task); } - return tasks + return tasks; } /** @@ -141,15 +141,15 @@ class TaskClient { * @returns Promise containing an EnqueuedTask */ async cancelTasks(parameters: CancelTasksQuery = {}): Promise { - const url = `tasks/cancel` + const url = `tasks/cancel`; const task = await this.httpRequest.post( url, {}, - toQueryParams(parameters) - ) + toQueryParams(parameters), + ); - return new EnqueuedTask(task) + return new EnqueuedTask(task); } /** @@ -159,15 +159,15 @@ class TaskClient { * @returns Promise containing an EnqueuedTask */ async deleteTasks(parameters: DeleteTasksQuery = {}): Promise { - const url = `tasks` + const url = `tasks`; const task = await this.httpRequest.delete( url, {}, - toQueryParams(parameters) - ) - return new EnqueuedTask(task) + toQueryParams(parameters), + ); + return new EnqueuedTask(task); } } -export { TaskClient, Task } +export { TaskClient, Task }; diff --git a/src/token.ts b/src/token.ts index ee0170adc..1066a0ad2 100644 --- a/src/token.ts +++ b/src/token.ts @@ -1,9 +1,9 @@ -import { Config, TokenSearchRules, TokenOptions } from './types' -import { MeiliSearchError } from './errors' -import { validateUuid4 } from './utils' +import { Config, TokenSearchRules, TokenOptions } from './types'; +import { MeiliSearchError } from './errors'; +import { validateUuid4 } from './utils'; function encode64(data: any) { - return Buffer.from(JSON.stringify(data)).toString('base64') + return Buffer.from(JSON.stringify(data)).toString('base64'); } /** @@ -17,16 +17,16 @@ function encode64(data: any) { async function sign( apiKey: string, encodedHeader: string, - encodedPayload: string + encodedPayload: string, ) { - const { createHmac } = await import('crypto') + const { createHmac } = await import('crypto'); return createHmac('sha256', apiKey) .update(`${encodedHeader}.${encodedPayload}`) .digest('base64') .replace(/\+/g, '-') .replace(/\//g, '_') - .replace(/=/g, '') + .replace(/=/g, ''); } /** @@ -38,9 +38,9 @@ function createHeader() { const header = { alg: 'HS256', typ: 'JWT', - } + }; - return encode64(header).replace(/=/g, '') + return encode64(header).replace(/=/g, ''); } /** @@ -52,49 +52,49 @@ function createHeader() { * @param expiresAt - Date at which the token expires. */ function validateTokenParameters(tokenParams: { - searchRules: TokenSearchRules - uid: string - apiKey: string - expiresAt?: Date + searchRules: TokenSearchRules; + uid: string; + apiKey: string; + expiresAt?: Date; }) { - const { searchRules, uid, apiKey, expiresAt } = tokenParams + const { searchRules, uid, apiKey, expiresAt } = tokenParams; if (expiresAt) { if (!(expiresAt instanceof Date)) { throw new MeiliSearchError( - `Meilisearch: The expiredAt field must be an instance of Date.` - ) + `Meilisearch: The expiredAt field must be an instance of Date.`, + ); } else if (expiresAt.getTime() < Date.now()) { throw new MeiliSearchError( - `Meilisearch: The expiresAt field must be a date in the future.` - ) + `Meilisearch: The expiresAt field must be a date in the future.`, + ); } } if (searchRules) { if (!(typeof searchRules === 'object' || Array.isArray(searchRules))) { throw new MeiliSearchError( - `Meilisearch: The search rules added in the token generation must be of type array or object.` - ) + `Meilisearch: The search rules added in the token generation must be of type array or object.`, + ); } } if (!apiKey || typeof apiKey !== 'string') { throw new MeiliSearchError( - `Meilisearch: The API key used for the token generation must exist and be of type string.` - ) + `Meilisearch: The API key used for the token generation must exist and be of type string.`, + ); } if (!uid || typeof uid !== 'string') { throw new MeiliSearchError( - `Meilisearch: The uid of the api key used for the token generation must exist, be of type string and comply to the uuid4 format.` - ) + `Meilisearch: The uid of the api key used for the token generation must exist, be of type string and comply to the uuid4 format.`, + ); } if (!validateUuid4(uid)) { throw new MeiliSearchError( - `Meilisearch: The uid of your key is not a valid uuid4. To find out the uid of your key use getKey().` - ) + `Meilisearch: The uid of your key is not a valid uuid4. To find out the uid of your key use getKey().`, + ); } } @@ -107,26 +107,26 @@ function validateTokenParameters(tokenParams: { * @returns The payload encoded in base64. */ function createPayload(payloadParams: { - searchRules: TokenSearchRules - uid: string - expiresAt?: Date + searchRules: TokenSearchRules; + uid: string; + expiresAt?: Date; }): string { - const { searchRules, uid, expiresAt } = payloadParams + const { searchRules, uid, expiresAt } = payloadParams; const payload = { searchRules, apiKeyUid: uid, exp: expiresAt ? Math.floor(expiresAt.getTime() / 1000) : undefined, - } + }; - return encode64(payload).replace(/=/g, '') + return encode64(payload).replace(/=/g, ''); } class Token { - config: Config + config: Config; constructor(config: Config) { - this.config = config + this.config = config; } /** @@ -140,19 +140,19 @@ class Token { async generateTenantToken( apiKeyUid: string, searchRules: TokenSearchRules, - options?: TokenOptions + options?: TokenOptions, ): Promise { - const apiKey = options?.apiKey || this.config.apiKey || '' - const uid = apiKeyUid || '' - const expiresAt = options?.expiresAt + const apiKey = options?.apiKey || this.config.apiKey || ''; + const uid = apiKeyUid || ''; + const expiresAt = options?.expiresAt; - validateTokenParameters({ apiKey, uid, expiresAt, searchRules }) + validateTokenParameters({ apiKey, uid, expiresAt, searchRules }); - const encodedHeader = createHeader() - const encodedPayload = createPayload({ searchRules, uid, expiresAt }) - const signature = await sign(apiKey, encodedHeader, encodedPayload) + const encodedHeader = createHeader(); + const encodedPayload = createPayload({ searchRules, uid, expiresAt }); + const signature = await sign(apiKey, encodedHeader, encodedPayload); - return `${encodedHeader}.${encodedPayload}.${signature}` + return `${encodedHeader}.${encodedPayload}.${signature}`; } } -export { Token } +export { Token }; diff --git a/src/types/index.ts b/src/types/index.ts index c9f6f047d..fcb073fef 100644 --- a/src/types/index.ts +++ b/src/types/index.ts @@ -1 +1 @@ -export * from './types' +export * from './types'; diff --git a/src/types/types.ts b/src/types/types.ts index ae1224644..a6d916b11 100644 --- a/src/types/types.ts +++ b/src/types/types.ts @@ -4,57 +4,57 @@ // Definitions: https://github.com/meilisearch/meilisearch-js // TypeScript Version: ^3.8.3 -import { Task } from '../task' +import { Task } from '../task'; export type Config = { - host: string - apiKey?: string - clientAgents?: string[] - requestConfig?: Partial> - httpClient?: (input: string, init?: RequestInit) => Promise - timeout?: number -} + host: string; + apiKey?: string; + clientAgents?: string[]; + requestConfig?: Partial>; + httpClient?: (input: string, init?: RequestInit) => Promise; + timeout?: number; +}; /// /// Resources /// export type Pagination = { - offset?: number - limit?: number -} + offset?: number; + limit?: number; +}; // TODO fix // eslint-disable-next-line @typescript-eslint/ban-types -export type ResourceQuery = Pagination & {} +export type ResourceQuery = Pagination & {}; export type ResourceResults = Pagination & { - results: T - total: number -} + results: T; + total: number; +}; /// /// Indexes /// export type IndexOptions = { - primaryKey?: string -} + primaryKey?: string; +}; export type IndexObject = { - uid: string - primaryKey?: string - createdAt: Date - updatedAt: Date -} + uid: string; + primaryKey?: string; + createdAt: Date; + updatedAt: Date; +}; // TODO fix // eslint-disable-next-line @typescript-eslint/ban-types -export type IndexesQuery = ResourceQuery & {} +export type IndexesQuery = ResourceQuery & {}; // TODO fix // eslint-disable-next-line @typescript-eslint/ban-types -export type IndexesResults = ResourceResults & {} +export type IndexesResults = ResourceResults & {}; /* * SEARCH PARAMETERS @@ -63,70 +63,70 @@ export type IndexesResults = ResourceResults & {} export const MatchingStrategies = { ALL: 'all', LAST: 'last', -} as const +} as const; export type MatchingStrategies = - (typeof MatchingStrategies)[keyof typeof MatchingStrategies] + (typeof MatchingStrategies)[keyof typeof MatchingStrategies]; -export type Filter = string | Array +export type Filter = string | Array; export type Query = { - q?: string | null -} + q?: string | null; +}; export type Highlight = { - attributesToHighlight?: string[] - highlightPreTag?: string - highlightPostTag?: string -} + attributesToHighlight?: string[]; + highlightPreTag?: string; + highlightPostTag?: string; +}; export type Crop = { - attributesToCrop?: string[] - cropLength?: number - cropMarker?: string -} + attributesToCrop?: string[]; + cropLength?: number; + cropMarker?: string; +}; // `facetName` becomes mandatory when using `searchForFacetValues` export type SearchForFacetValuesParams = Omit & { - facetName: string -} + facetName: string; +}; export type FacetHit = { - value: string - count: number -} + value: string; + count: number; +}; export type SearchForFacetValuesResponse = { - facetHits: FacetHit[] - facetQuery: string | null - processingTimeMs: number -} + facetHits: FacetHit[]; + facetQuery: string | null; + processingTimeMs: number; +}; export type HybridSearch = { - embedder?: string - semanticRatio?: number -} + embedder?: string; + semanticRatio?: number; +}; export type SearchParams = Query & Pagination & Highlight & Crop & { - filter?: Filter - sort?: string[] - facets?: string[] - attributesToRetrieve?: string[] - showMatchesPosition?: boolean - matchingStrategy?: MatchingStrategies - hitsPerPage?: number - page?: number - facetName?: string - facetQuery?: string - vector?: number[] | null - showRankingScore?: boolean - showRankingScoreDetails?: boolean - attributesToSearchOn?: string[] | null - hybrid?: HybridSearch - } + filter?: Filter; + sort?: string[]; + facets?: string[]; + attributesToRetrieve?: string[]; + showMatchesPosition?: boolean; + matchingStrategy?: MatchingStrategies; + hitsPerPage?: number; + page?: number; + facetName?: string; + facetQuery?: string; + vector?: number[] | null; + showRankingScore?: boolean; + showRankingScoreDetails?: boolean; + attributesToSearchOn?: string[] | null; + hybrid?: HybridSearch; + }; // Search parameters for searches made with the GET method // Are different than the parameters for the POST method @@ -134,133 +134,133 @@ export type SearchRequestGET = Pagination & Query & Omit & Omit & { - filter?: string - sort?: string - facets?: string - attributesToRetrieve?: string - attributesToHighlight?: string - attributesToCrop?: string - showMatchesPosition?: boolean - vector?: string | null - attributesToSearchOn?: string | null - hybridEmbedder?: string - hybridSemanticRatio?: number - } - -export type MultiSearchQuery = SearchParams & { indexUid: string } + filter?: string; + sort?: string; + facets?: string; + attributesToRetrieve?: string; + attributesToHighlight?: string; + attributesToCrop?: string; + showMatchesPosition?: boolean; + vector?: string | null; + attributesToSearchOn?: string | null; + hybridEmbedder?: string; + hybridSemanticRatio?: number; + }; + +export type MultiSearchQuery = SearchParams & { indexUid: string }; export type MultiSearchParams = { - queries: MultiSearchQuery[] -} + queries: MultiSearchQuery[]; +}; export type CategoriesDistribution = { - [category: string]: number -} + [category: string]: number; +}; -export type Facet = string -export type FacetDistribution = Record +export type Facet = string; +export type FacetDistribution = Record; export type MatchesPosition = Partial< Record> -> +>; export type Hit> = T & { - _formatted?: Partial - _matchesPosition?: MatchesPosition - _rankingScore?: number - _rankingScoreDetails?: RankingScoreDetails -} + _formatted?: Partial; + _matchesPosition?: MatchesPosition; + _rankingScore?: number; + _rankingScoreDetails?: RankingScoreDetails; +}; export type RankingScoreDetails = { words?: { - order: number - matchingWords: number - maxMatchingWords: number - score: number - } + order: number; + matchingWords: number; + maxMatchingWords: number; + score: number; + }; typo?: { - order: number - typoCount: number - maxTypoCount: number - score: number - } + order: number; + typoCount: number; + maxTypoCount: number; + score: number; + }; proximity?: { - order: number - score: number - } + order: number; + score: number; + }; attribute?: { - order: number - attributes_ranking_order: number - attributes_query_word_order: number - score: number - } + order: number; + attributes_ranking_order: number; + attributes_query_word_order: number; + score: number; + }; exactness?: { - order: number - matchType: string - score: number - } - [key: string]: Record | undefined -} + order: number; + matchType: string; + score: number; + }; + [key: string]: Record | undefined; +}; -export type Hits> = Array> +export type Hits> = Array>; -export type FacetStat = { min: number; max: number } -export type FacetStats = Record +export type FacetStat = { min: number; max: number }; +export type FacetStats = Record; export type SearchResponse< T = Record, S extends SearchParams | undefined = undefined, > = { - hits: Hits - processingTimeMs: number - query: string - facetDistribution?: FacetDistribution - facetStats?: FacetStats + hits: Hits; + processingTimeMs: number; + query: string; + facetDistribution?: FacetDistribution; + facetStats?: FacetStats; } & (undefined extends S ? Partial : true extends IsFinitePagination> ? FinitePagination - : InfinitePagination) + : InfinitePagination); type FinitePagination = { - totalHits: number - hitsPerPage: number - page: number - totalPages: number -} + totalHits: number; + hitsPerPage: number; + page: number; + totalPages: number; +}; type InfinitePagination = { - offset: number - limit: number - estimatedTotalHits: number -} + offset: number; + limit: number; + estimatedTotalHits: number; +}; type IsFinitePagination = Or< HasHitsPerPage, HasPage -> +>; type Or = true extends A ? true : true extends B ? true - : false + : false; type HasHitsPerPage = undefined extends S['hitsPerPage'] ? false - : true + : true; type HasPage = undefined extends S['page'] ? false - : true + : true; -export type MultiSearchResult = SearchResponse & { indexUid: string } +export type MultiSearchResult = SearchResponse & { indexUid: string }; export type MultiSearchResponse> = { - results: Array> -} + results: Array>; +}; export type FieldDistribution = { - [field: string]: number -} + [field: string]: number; +}; /* ** Documents @@ -268,122 +268,122 @@ export type FieldDistribution = { type Fields> = | Array> - | Extract + | Extract; export type DocumentOptions = { - primaryKey?: string -} + primaryKey?: string; +}; export const ContentTypeEnum: Readonly> = { JSON: 'application/json', CSV: 'text/csv', NDJSON: 'application/x-ndjson', -} +}; export type ContentType = | 'text/csv' | 'application/x-ndjson' - | 'application/json' + | 'application/json'; export type RawDocumentAdditionOptions = DocumentOptions & { - csvDelimiter?: string -} + csvDelimiter?: string; +}; export type DocumentsQuery> = ResourceQuery & { - fields?: Fields - filter?: Filter - limit?: number - offset?: number -} + fields?: Fields; + filter?: Filter; + limit?: number; + offset?: number; +}; export type DocumentQuery> = { - fields?: Fields -} + fields?: Fields; +}; export type DocumentsDeletionQuery = { - filter: Filter -} + filter: Filter; +}; -export type DocumentsIds = string[] | number[] +export type DocumentsIds = string[] | number[]; /* ** Settings */ -export type FilterableAttributes = string[] | null -export type DistinctAttribute = string | null -export type SearchableAttributes = string[] | null -export type SortableAttributes = string[] | null -export type DisplayedAttributes = string[] | null -export type RankingRules = string[] | null -export type StopWords = string[] | null +export type FilterableAttributes = string[] | null; +export type DistinctAttribute = string | null; +export type SearchableAttributes = string[] | null; +export type SortableAttributes = string[] | null; +export type DisplayedAttributes = string[] | null; +export type RankingRules = string[] | null; +export type StopWords = string[] | null; export type Synonyms = { - [field: string]: string[] -} | null + [field: string]: string[]; +} | null; export type TypoTolerance = { - enabled?: boolean | null - disableOnAttributes?: string[] | null - disableOnWords?: string[] | null + enabled?: boolean | null; + disableOnAttributes?: string[] | null; + disableOnWords?: string[] | null; minWordSizeForTypos?: { - oneTypo?: number | null - twoTypos?: number | null - } -} | null -export type SeparatorTokens = string[] | null -export type NonSeparatorTokens = string[] | null -export type Dictionary = string[] | null -export type ProximityPrecision = 'byWord' | 'byAttribute' + oneTypo?: number | null; + twoTypos?: number | null; + }; +} | null; +export type SeparatorTokens = string[] | null; +export type NonSeparatorTokens = string[] | null; +export type Dictionary = string[] | null; +export type ProximityPrecision = 'byWord' | 'byAttribute'; export type Distribution = { - mean: number - sigma: number -} + mean: number; + sigma: number; +}; export type OpenAiEmbedder = { - source: 'openAi' - model?: string - apiKey?: string - documentTemplate?: string - dimensions?: number - distribution?: Distribution -} + source: 'openAi'; + model?: string; + apiKey?: string; + documentTemplate?: string; + dimensions?: number; + distribution?: Distribution; +}; export type HuggingFaceEmbedder = { - source: 'huggingFace' - model?: string - revision?: string - documentTemplate?: string - distribution?: Distribution -} + source: 'huggingFace'; + model?: string; + revision?: string; + documentTemplate?: string; + distribution?: Distribution; +}; export type UserProvidedEmbedder = { - source: 'userProvided' - dimensions: number - distribution?: Distribution -} + source: 'userProvided'; + dimensions: number; + distribution?: Distribution; +}; export type RestEmbedder = { - source: 'rest' - url: string - apiKey?: string - dimensions?: number - documentTemplate?: string - inputField?: string[] | null - inputType?: 'text' | 'textArray' - query?: Record | null - pathToEmbeddings?: string[] | null - embeddingObject?: string[] | null - distribution?: Distribution -} + source: 'rest'; + url: string; + apiKey?: string; + dimensions?: number; + documentTemplate?: string; + inputField?: string[] | null; + inputType?: 'text' | 'textArray'; + query?: Record | null; + pathToEmbeddings?: string[] | null; + embeddingObject?: string[] | null; + distribution?: Distribution; +}; export type OllamaEmbedder = { - source: 'ollama' - url?: string - apiKey?: string - model?: string - documentTemplate?: string - distribution?: Distribution -} + source: 'ollama'; + url?: string; + apiKey?: string; + model?: string; + documentTemplate?: string; + distribution?: Distribution; +}; export type Embedder = | OpenAiEmbedder @@ -391,42 +391,42 @@ export type Embedder = | UserProvidedEmbedder | RestEmbedder | OllamaEmbedder - | null + | null; -export type Embedders = Record | null +export type Embedders = Record | null; -export type FacetOrder = 'alpha' | 'count' +export type FacetOrder = 'alpha' | 'count'; export type Faceting = { - maxValuesPerFacet?: number | null - sortFacetValuesBy?: Record | null -} + maxValuesPerFacet?: number | null; + sortFacetValuesBy?: Record | null; +}; export type PaginationSettings = { - maxTotalHits?: number | null -} + maxTotalHits?: number | null; +}; -export type SearchCutoffMs = number | null +export type SearchCutoffMs = number | null; export type Settings = { - filterableAttributes?: FilterableAttributes - distinctAttribute?: DistinctAttribute - sortableAttributes?: SortableAttributes - searchableAttributes?: SearchableAttributes - displayedAttributes?: DisplayedAttributes - rankingRules?: RankingRules - stopWords?: StopWords - synonyms?: Synonyms - typoTolerance?: TypoTolerance - faceting?: Faceting - pagination?: PaginationSettings - separatorTokens?: SeparatorTokens - nonSeparatorTokens?: NonSeparatorTokens - dictionary?: Dictionary - proximityPrecision?: ProximityPrecision - embedders?: Embedders - searchCutoffMs?: SearchCutoffMs -} + filterableAttributes?: FilterableAttributes; + distinctAttribute?: DistinctAttribute; + sortableAttributes?: SortableAttributes; + searchableAttributes?: SearchableAttributes; + displayedAttributes?: DisplayedAttributes; + rankingRules?: RankingRules; + stopWords?: StopWords; + synonyms?: Synonyms; + typoTolerance?: TypoTolerance; + faceting?: Faceting; + pagination?: PaginationSettings; + separatorTokens?: SeparatorTokens; + nonSeparatorTokens?: NonSeparatorTokens; + dictionary?: Dictionary; + proximityPrecision?: ProximityPrecision; + embedders?: Embedders; + searchCutoffMs?: SearchCutoffMs; +}; /* ** TASKS @@ -438,9 +438,9 @@ export const TaskStatus = { TASK_FAILED: 'failed', TASK_ENQUEUED: 'enqueued', TASK_CANCELED: 'canceled', -} as const +} as const; -export type TaskStatus = (typeof TaskStatus)[keyof typeof TaskStatus] +export type TaskStatus = (typeof TaskStatus)[keyof typeof TaskStatus]; export const TaskTypes = { DOCUMENTS_ADDITION_OR_UPDATE: 'documentAdditionOrUpdate', @@ -454,215 +454,215 @@ export const TaskTypes = { SNAPSHOT_CREATION: 'snapshotCreation', TASK_CANCELATION: 'taskCancelation', TASK_DELETION: 'taskDeletion', -} as const +} as const; -export type TaskTypes = (typeof TaskTypes)[keyof typeof TaskTypes] +export type TaskTypes = (typeof TaskTypes)[keyof typeof TaskTypes]; export type TasksQuery = { - indexUids?: string[] - uids?: number[] - types?: TaskTypes[] - statuses?: TaskStatus[] - canceledBy?: number[] - beforeEnqueuedAt?: Date - afterEnqueuedAt?: Date - beforeStartedAt?: Date - afterStartedAt?: Date - beforeFinishedAt?: Date - afterFinishedAt?: Date - limit?: number - from?: number -} + indexUids?: string[]; + uids?: number[]; + types?: TaskTypes[]; + statuses?: TaskStatus[]; + canceledBy?: number[]; + beforeEnqueuedAt?: Date; + afterEnqueuedAt?: Date; + beforeStartedAt?: Date; + afterStartedAt?: Date; + beforeFinishedAt?: Date; + afterFinishedAt?: Date; + limit?: number; + from?: number; +}; // TODO fix // eslint-disable-next-line @typescript-eslint/ban-types -export type CancelTasksQuery = Omit & {} +export type CancelTasksQuery = Omit & {}; // TODO fix // eslint-disable-next-line @typescript-eslint/ban-types -export type DeleteTasksQuery = Omit & {} +export type DeleteTasksQuery = Omit & {}; export type EnqueuedTaskObject = { - taskUid: number - indexUid?: string - status: TaskStatus - type: TaskTypes - enqueuedAt: string - canceledBy: number -} + taskUid: number; + indexUid?: string; + status: TaskStatus; + type: TaskTypes; + enqueuedAt: string; + canceledBy: number; +}; export type TaskObject = Omit & { - uid: number + uid: number; details: { // Number of documents sent - receivedDocuments?: number + receivedDocuments?: number; // Number of documents successfully indexed/updated in Meilisearch - indexedDocuments?: number + indexedDocuments?: number; // Number of deleted documents - deletedDocuments?: number + deletedDocuments?: number; // Number of documents found on a batch-delete - providedIds?: number + providedIds?: number; // Primary key on index creation - primaryKey?: string + primaryKey?: string; // Ranking rules on settings actions - rankingRules?: RankingRules + rankingRules?: RankingRules; // Searchable attributes on settings actions - searchableAttributes?: SearchableAttributes + searchableAttributes?: SearchableAttributes; // Displayed attributes on settings actions - displayedAttributes?: DisplayedAttributes + displayedAttributes?: DisplayedAttributes; // Filterable attributes on settings actions - filterableAttributes?: FilterableAttributes + filterableAttributes?: FilterableAttributes; // Sortable attributes on settings actions - sortableAttributes?: SortableAttributes + sortableAttributes?: SortableAttributes; // Stop words on settings actions - stopWords?: StopWords + stopWords?: StopWords; // Stop words on settings actions - synonyms?: Synonyms + synonyms?: Synonyms; // Distinct attribute on settings actions - distinctAttribute?: DistinctAttribute + distinctAttribute?: DistinctAttribute; // Object containing the payload originating the `indexSwap` task creation - swaps?: SwapIndexesParams + swaps?: SwapIndexesParams; // Number of tasks that matched the originalQuery filter - matchedTasks?: number + matchedTasks?: number; // Number of tasks that were canceled - canceledTasks?: number + canceledTasks?: number; // Number of tasks that were deleted - deletedTasks?: number + deletedTasks?: number; // Query parameters used to filter the tasks - originalFilter?: string - } - error: MeiliSearchErrorResponse | null - duration: string - startedAt: string - finishedAt: string -} + originalFilter?: string; + }; + error: MeiliSearchErrorResponse | null; + duration: string; + startedAt: string; + finishedAt: string; +}; export type SwapIndexesParams = Array<{ - indexes: string[] -}> + indexes: string[]; +}>; type CursorResults = { - results: T[] - limit: number - from: number - next: number - total: number -} + results: T[]; + limit: number; + from: number; + next: number; + total: number; +}; -export type TasksResults = CursorResults -export type TasksResultsObject = CursorResults +export type TasksResults = CursorResults; +export type TasksResultsObject = CursorResults; export type WaitOptions = { - timeOutMs?: number - intervalMs?: number -} + timeOutMs?: number; + intervalMs?: number; +}; /* *** HEALTH */ export type Health = { - status: 'available' -} + status: 'available'; +}; /* *** STATS */ export type IndexStats = { - numberOfDocuments: number - isIndexing: boolean - fieldDistribution: FieldDistribution -} + numberOfDocuments: number; + isIndexing: boolean; + fieldDistribution: FieldDistribution; +}; export type Stats = { - databaseSize: number - lastUpdate: string + databaseSize: number; + lastUpdate: string; indexes: { - [index: string]: IndexStats - } -} + [index: string]: IndexStats; + }; +}; /* ** Keys */ export type Key = { - uid: string - description: string - name: string | null - key: string - actions: string[] - indexes: string[] - expiresAt: Date - createdAt: Date - updatedAt: Date -} + uid: string; + description: string; + name: string | null; + key: string; + actions: string[]; + indexes: string[]; + expiresAt: Date; + createdAt: Date; + updatedAt: Date; +}; export type KeyCreation = { - uid?: string - name?: string - description?: string - actions: string[] - indexes: string[] - expiresAt: Date | null -} + uid?: string; + name?: string; + description?: string; + actions: string[]; + indexes: string[]; + expiresAt: Date | null; +}; export type KeyUpdate = { - name?: string - description?: string -} + name?: string; + description?: string; +}; // TODO fix // eslint-disable-next-line @typescript-eslint/ban-types -export type KeysQuery = ResourceQuery & {} +export type KeysQuery = ResourceQuery & {}; // TODO fix // eslint-disable-next-line @typescript-eslint/ban-types -export type KeysResults = ResourceResults & {} +export type KeysResults = ResourceResults & {}; /* ** version */ export type Version = { - commitSha: string - commitDate: string - pkgVersion: string -} + commitSha: string; + commitDate: string; + pkgVersion: string; +}; /* ** ERROR HANDLER */ export interface FetchError extends Error { - type: string - errno: string - code: string + type: string; + errno: string; + code: string; } export type MeiliSearchErrorResponse = { - message: string + message: string; // @TODO: Could be typed, but will it be kept updated? https://www.meilisearch.com/docs/reference/errors/error_codes - code: string + code: string; // @TODO: Could be typed https://www.meilisearch.com/docs/reference/errors/overview#errors - type: string - link: string -} + type: string; + link: string; +}; // @TODO: This doesn't seem to be up to date, and its usefullness comes into question. export const ErrorStatusCode = { @@ -1013,18 +1013,20 @@ export const ErrorStatusCode = { /** @see https://www.meilisearch.com/docs/reference/errors/error_codes#invalid_facet_search_facet_query */ INVALID_FACET_SEARCH_FACET_QUERY: 'invalid_facet_search_facet_query', -} +}; export type ErrorStatusCode = - (typeof ErrorStatusCode)[keyof typeof ErrorStatusCode] + (typeof ErrorStatusCode)[keyof typeof ErrorStatusCode]; export type TokenIndexRules = { - [field: string]: any - filter?: Filter -} -export type TokenSearchRules = Record | string[] + [field: string]: any; + filter?: Filter; +}; +export type TokenSearchRules = + | Record + | string[]; export type TokenOptions = { - apiKey?: string - expiresAt?: Date -} + apiKey?: string; + expiresAt?: Date; +}; diff --git a/src/utils.ts b/src/utils.ts index 9daecda67..fdaf26344 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -2,36 +2,36 @@ function removeUndefinedFromObject(obj: Record): object { return Object.entries(obj).reduce( (acc, curEntry) => { - const [key, val] = curEntry - if (val !== undefined) acc[key] = val - return acc + const [key, val] = curEntry; + if (val !== undefined) acc[key] = val; + return acc; }, - {} as Record - ) + {} as Record, + ); } async function sleep(ms: number): Promise { - return await new Promise((resolve) => setTimeout(resolve, ms)) + return await new Promise((resolve) => setTimeout(resolve, ms)); } function addProtocolIfNotPresent(host: string): string { if (!(host.startsWith('https://') || host.startsWith('http://'))) { - return `http://${host}` + return `http://${host}`; } - return host + return host; } function addTrailingSlash(url: string): string { if (!url.endsWith('/')) { - url += '/' + url += '/'; } - return url + return url; } function validateUuid4(uuid: string): boolean { const regexExp = - /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/gi - return regexExp.test(uuid) + /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/gi; + return regexExp.test(uuid); } export { @@ -40,4 +40,4 @@ export { addProtocolIfNotPresent, addTrailingSlash, validateUuid4, -} +}; diff --git a/tests/client.test.ts b/tests/client.test.ts index f0f72df0b..ab34088fa 100644 --- a/tests/client.test.ts +++ b/tests/client.test.ts @@ -1,5 +1,5 @@ -import { ErrorStatusCode, Health, Version, Stats, TaskTypes } from '../src' -import { PACKAGE_VERSION } from '../src/package-version' +import { ErrorStatusCode, Health, Version, Stats, TaskTypes } from '../src'; +import { PACKAGE_VERSION } from '../src/package-version'; import { clearAllIndexes, getKey, @@ -8,27 +8,27 @@ import { MeiliSearch, BAD_HOST, HOST, -} from './utils/meilisearch-test-utils' +} from './utils/meilisearch-test-utils'; 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) -}) + return clearAllIndexes(config); +}); describe.each([ { permission: 'Master' }, @@ -36,21 +36,21 @@ describe.each([ { permission: 'Search' }, ])('Test on client instance', ({ permission }) => { beforeEach(() => { - return clearAllIndexes(config) - }) + return clearAllIndexes(config); + }); test(`${permission} key: Create client with api key`, async () => { - const key = await getKey(permission) + const key = await getKey(permission); const client = new MeiliSearch({ ...config, apiKey: key, - }) - const health = await client.isHealthy() - expect(health).toBe(true) - }) + }); + const health = await client.isHealthy(); + expect(health).toBe(true); + }); test(`${permission} key: Create client with custom headers (object)`, async () => { - const key = await getKey(permission) + const key = await getKey(permission); const client = new MeiliSearch({ ...config, apiKey: key, @@ -59,145 +59,145 @@ describe.each([ 'Hello-There!': 'General Kenobi', }, }, - }) - expect(client.httpRequest.headers['Hello-There!']).toBe('General Kenobi') - const health = await client.isHealthy() - expect(health).toBe(true) - }) + }); + expect(client.httpRequest.headers['Hello-There!']).toBe('General Kenobi'); + const health = await client.isHealthy(); + expect(health).toBe(true); + }); test(`${permission} key: Create client with custom headers (array)`, async () => { - const key = await getKey(permission) + const key = await getKey(permission); const client = new MeiliSearch({ ...config, apiKey: key, requestConfig: { headers: [['Hello-There!', 'General Kenobi']], }, - }) - expect(client.httpRequest.headers['Hello-There!']).toBe('General Kenobi') - const health = await client.isHealthy() - expect(health).toBe(true) - }) + }); + expect(client.httpRequest.headers['Hello-There!']).toBe('General Kenobi'); + const health = await client.isHealthy(); + expect(health).toBe(true); + }); test(`${permission} key: Create client with custom headers (Headers)`, async () => { - const key = await getKey(permission) - const headers = new Headers() - headers.append('Hello-There!', 'General Kenobi') + const key = await getKey(permission); + const headers = new Headers(); + headers.append('Hello-There!', 'General Kenobi'); const client = new MeiliSearch({ ...config, apiKey: key, requestConfig: { headers, }, - }) - expect(client.httpRequest.headers['hello-there!']).toBe('General Kenobi') - const health = await client.isHealthy() - expect(health).toBe(true) - }) + }); + expect(client.httpRequest.headers['hello-there!']).toBe('General Kenobi'); + const health = await client.isHealthy(); + expect(health).toBe(true); + }); test(`${permission} key: No double slash when on host with domain and path and trailing slash`, async () => { - const key = await getKey(permission) + const key = await getKey(permission); try { - const customHost = `${BAD_HOST}/api/` + const customHost = `${BAD_HOST}/api/`; const client = new MeiliSearch({ host: customHost, apiKey: key, - }) - const health = await client.isHealthy() - expect(health).toBe(false) // Left here to trigger failed test if error is not thrown + }); + const health = await client.isHealthy(); + expect(health).toBe(false); // Left here to trigger failed test if error is not thrown } catch (e: any) { - expect(e.message).toMatch(`${BAD_HOST}/api/health`) - expect(e.name).toBe('MeiliSearchRequestError') + expect(e.message).toMatch(`${BAD_HOST}/api/health`); + expect(e.name).toBe('MeiliSearchRequestError'); } - }) + }); test(`${permission} key: No double slash when on host with domain and path and no trailing slash`, async () => { - const key = await getKey(permission) + const key = await getKey(permission); try { - const customHost = `${BAD_HOST}/api` + const customHost = `${BAD_HOST}/api`; const client = new MeiliSearch({ host: customHost, apiKey: key, - }) - const health = await client.isHealthy() - expect(health).toBe(false) // Left here to trigger failed test if error is not thrown + }); + const health = await client.isHealthy(); + expect(health).toBe(false); // Left here to trigger failed test if error is not thrown } catch (e: any) { - expect(e.message).toMatch(`${BAD_HOST}/api/health`) - expect(e.name).toBe('MeiliSearchRequestError') + expect(e.message).toMatch(`${BAD_HOST}/api/health`); + expect(e.name).toBe('MeiliSearchRequestError'); } - }) + }); test(`${permission} key: host with double slash should keep double slash`, async () => { - const key = await getKey(permission) + const key = await getKey(permission); try { - const customHost = `${BAD_HOST}//` + const customHost = `${BAD_HOST}//`; const client = new MeiliSearch({ host: customHost, apiKey: key, - }) - const health = await client.isHealthy() - expect(health).toBe(false) // Left here to trigger failed test if error is not thrown + }); + const health = await client.isHealthy(); + expect(health).toBe(false); // Left here to trigger failed test if error is not thrown } catch (e: any) { - expect(e.message).toMatch(`${BAD_HOST}//health`) - expect(e.name).toBe('MeiliSearchRequestError') + expect(e.message).toMatch(`${BAD_HOST}//health`); + expect(e.name).toBe('MeiliSearchRequestError'); } - }) + }); test(`${permission} key: host with one slash should not double slash`, async () => { - const key = await getKey(permission) + const key = await getKey(permission); try { - const customHost = `${BAD_HOST}/` + const customHost = `${BAD_HOST}/`; const client = new MeiliSearch({ host: customHost, apiKey: key, - }) - const health = await client.isHealthy() - expect(health).toBe(false) // Left here to trigger failed test if error is not thrown + }); + const health = await client.isHealthy(); + expect(health).toBe(false); // Left here to trigger failed test if error is not thrown } catch (e: any) { - expect(e.message).toMatch(`${BAD_HOST}/health`) - expect(e.name).toBe('MeiliSearchRequestError') + expect(e.message).toMatch(`${BAD_HOST}/health`); + expect(e.name).toBe('MeiliSearchRequestError'); } - }) + }); test(`${permission} key: bad host raise CommunicationError`, async () => { - const client = new MeiliSearch({ host: 'http://localhost:9345' }) + const client = new MeiliSearch({ host: 'http://localhost:9345' }); try { - await client.health() + await client.health(); } catch (e: any) { - expect(e.name).toEqual('MeiliSearchRequestError') + expect(e.name).toEqual('MeiliSearchRequestError'); } - }) + }); test(`${permission} key: host without HTTP should not throw Invalid URL Error`, () => { - const strippedHost = HOST.replace('http://', '') + const strippedHost = HOST.replace('http://', ''); expect(() => { - new MeiliSearch({ host: strippedHost }) - }).not.toThrow('The provided host is not valid.') - }) + new MeiliSearch({ host: strippedHost }); + }).not.toThrow('The provided host is not valid.'); + }); test(`${permission} key: host without HTTP and port should not throw Invalid URL Error`, () => { - const strippedHost = HOST.replace('http://', '').replace(':7700', '') + const strippedHost = HOST.replace('http://', '').replace(':7700', ''); expect(() => { - new MeiliSearch({ host: strippedHost }) - }).not.toThrow('The provided host is not valid.') - }) + new MeiliSearch({ host: strippedHost }); + }).not.toThrow('The provided host is not valid.'); + }); test(`${permission} key: Empty string host should throw an error`, () => { expect(() => { - new MeiliSearch({ host: '' }) - }).toThrow('The provided host is not valid.') - }) -}) + new MeiliSearch({ host: '' }); + }).toThrow('The provided host is not valid.'); + }); +}); describe.each([{ permission: 'Master' }, { permission: 'Admin' }])( 'Test on client w/ master and admin key', ({ permission }) => { beforeEach(() => { - return clearAllIndexes(config) - }) + return clearAllIndexes(config); + }); test(`${permission} key: Create client with custom headers`, async () => { - const key = await getKey(permission) + const key = await getKey(permission); const client = new MeiliSearch({ ...config, apiKey: key, @@ -206,517 +206,517 @@ describe.each([{ permission: 'Master' }, { permission: 'Admin' }])( 'Hello-There!': 'General Kenobi', }, }, - }) + }); expect(client.config.requestConfig?.headers).toStrictEqual({ 'Hello-There!': 'General Kenobi', - }) - const health = await client.isHealthy() + }); + const health = await client.isHealthy(); - expect(health).toBe(true) + expect(health).toBe(true); - const task = await client.createIndex('test') - await client.waitForTask(task.taskUid) + const task = await client.createIndex('test'); + await client.waitForTask(task.taskUid); - const { results } = await client.getIndexes() + const { results } = await client.getIndexes(); - expect(results.length).toBe(1) - }) + expect(results.length).toBe(1); + }); test(`${permission} key: Create client with custom http client`, async () => { - const key = await getKey(permission) + const key = await getKey(permission); const client = new MeiliSearch({ ...config, apiKey: key, async httpClient(url, init) { - const result = await fetch(url, init) - return result.json() + const result = await fetch(url, init); + return result.json(); }, - }) - const health = await client.isHealthy() + }); + const health = await client.isHealthy(); - expect(health).toBe(true) + expect(health).toBe(true); - const task = await client.createIndex('test') - await client.waitForTask(task.taskUid) + const task = await client.createIndex('test'); + await client.waitForTask(task.taskUid); - const { results } = await client.getIndexes() + const { results } = await client.getIndexes(); - expect(results.length).toBe(1) + expect(results.length).toBe(1); - const index = await client.getIndex('test') + const index = await client.getIndex('test'); const { taskUid } = await index.addDocuments([ { id: 1, title: 'index_2' }, - ]) - await client.waitForTask(taskUid) + ]); + await client.waitForTask(taskUid); - const { results: documents } = await index.getDocuments() - expect(documents.length).toBe(1) - }) + const { results: documents } = await index.getDocuments(); + expect(documents.length).toBe(1); + }); test(`${permission} key: Create client with no custom client agents`, async () => { - const key = await getKey(permission) + const key = await getKey(permission); const client = new MeiliSearch({ ...config, apiKey: key, requestConfig: { headers: {}, }, - }) + }); expect(client.httpRequest.headers['X-Meilisearch-Client']).toStrictEqual( - `Meilisearch JavaScript (v${PACKAGE_VERSION})` - ) - }) + `Meilisearch JavaScript (v${PACKAGE_VERSION})`, + ); + }); test(`${permission} key: Create client with empty custom client agents`, async () => { - const key = await getKey(permission) + const key = await getKey(permission); const client = new MeiliSearch({ ...config, apiKey: key, clientAgents: [], - }) + }); expect(client.httpRequest.headers['X-Meilisearch-Client']).toStrictEqual( - `Meilisearch JavaScript (v${PACKAGE_VERSION})` - ) - }) + `Meilisearch JavaScript (v${PACKAGE_VERSION})`, + ); + }); test(`${permission} key: Create client with custom client agents`, async () => { - const key = await getKey(permission) + const key = await getKey(permission); const client = new MeiliSearch({ ...config, apiKey: key, clientAgents: ['random plugin 1', 'random plugin 2'], - }) + }); expect(client.httpRequest.headers['X-Meilisearch-Client']).toStrictEqual( - `random plugin 1 ; random plugin 2 ; Meilisearch JavaScript (v${PACKAGE_VERSION})` - ) - }) + `random plugin 1 ; random plugin 2 ; Meilisearch JavaScript (v${PACKAGE_VERSION})`, + ); + }); describe('Test on indexes methods', () => { test(`${permission} key: create with no primary key`, async () => { - const client = await getClient(permission) - const task = await client.createIndex(indexNoPk.uid) - await client.waitForTask(task.taskUid) + const client = await getClient(permission); + const task = await client.createIndex(indexNoPk.uid); + await client.waitForTask(task.taskUid); - const newIndex = await client.getIndex(indexNoPk.uid) - expect(newIndex).toHaveProperty('uid', indexNoPk.uid) - expect(newIndex).toHaveProperty('primaryKey', null) + 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 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) - }) + 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) + const client = await getClient(permission); const { taskUid } = await client.createIndex(indexPk.uid, { primaryKey: indexPk.primaryKey, - }) - await client.waitForTask(taskUid) + }); + await client.waitForTask(taskUid); - const newIndex = await client.getIndex(indexPk.uid) + const newIndex = await client.getIndex(indexPk.uid); - expect(newIndex).toHaveProperty('uid', indexPk.uid) - expect(newIndex).toHaveProperty('primaryKey', indexPk.primaryKey) + 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 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) - }) + 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) + const client = await getClient(permission); - const { taskUid } = await client.createIndex(indexPk.uid) - await client.waitForTask(taskUid) + const { taskUid } = await client.createIndex(indexPk.uid); + await client.waitForTask(taskUid); - const { results } = await client.getRawIndexes() - const indexes = results.map((index) => index.uid) - expect(indexes).toEqual(expect.arrayContaining([indexPk.uid])) - expect(indexes.length).toEqual(1) - }) + 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) + const client = await getClient(permission); - const { taskUid } = await client.createIndex(indexPk.uid) - await client.waitForTask(taskUid) + const { taskUid } = await client.createIndex(indexPk.uid); + await client.waitForTask(taskUid); - const response = await client.getIndex(indexPk.uid) + const response = await client.getIndex(indexPk.uid); - expect(response).toHaveProperty('uid', indexPk.uid) - }) + expect(response).toHaveProperty('uid', indexPk.uid); + }); test(`${permission} key: Get index that does not exist`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect(client.getIndex('does_not_exist')).rejects.toHaveProperty( 'cause.code', - ErrorStatusCode.INDEX_NOT_FOUND - ) - }) + ErrorStatusCode.INDEX_NOT_FOUND, + ); + }); test(`${permission} key: update primary key`, async () => { - const client = await getClient(permission) - const { taskUid: createTask } = await client.createIndex(indexPk.uid) - await client.waitForTask(createTask) + const client = await getClient(permission); + const { taskUid: createTask } = await client.createIndex(indexPk.uid); + await client.waitForTask(createTask); const { taskUid: updateTask } = await client.updateIndex(indexPk.uid, { primaryKey: 'newPrimaryKey', - }) - await client.waitForTask(updateTask) + }); + await client.waitForTask(updateTask); - const index = await client.getIndex(indexPk.uid) + const index = await client.getIndex(indexPk.uid); - expect(index).toHaveProperty('uid', indexPk.uid) - expect(index).toHaveProperty('primaryKey', 'newPrimaryKey') - }) + 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) + const client = await getClient(permission); const { taskUid: createTask } = await client.createIndex(indexPk.uid, { primaryKey: indexPk.primaryKey, - }) - await client.waitForTask(createTask) + }); + await client.waitForTask(createTask); const { taskUid: updateTask } = await client.updateIndex(indexPk.uid, { primaryKey: 'newPrimaryKey', - }) - await client.waitForTask(updateTask) + }); + await client.waitForTask(updateTask); - const index = await client.getIndex(indexPk.uid) + const index = await client.getIndex(indexPk.uid); - expect(index).toHaveProperty('uid', indexPk.uid) - expect(index).toHaveProperty('primaryKey', 'newPrimaryKey') - }) + expect(index).toHaveProperty('uid', indexPk.uid); + expect(index).toHaveProperty('primaryKey', 'newPrimaryKey'); + }); test(`${permission} key: delete index`, async () => { - const client = await getClient(permission) - const { taskUid: createTask } = await client.createIndex(indexNoPk.uid) - await client.waitForTask(createTask) + const client = await getClient(permission); + const { taskUid: createTask } = await client.createIndex(indexNoPk.uid); + await client.waitForTask(createTask); - const { taskUid: deleteTask } = await client.deleteIndex(indexNoPk.uid) - await client.waitForTask(deleteTask) - const { results } = await client.getIndexes() + const { taskUid: deleteTask } = await client.deleteIndex(indexNoPk.uid); + await client.waitForTask(deleteTask); + const { results } = await client.getIndexes(); - expect(results).toHaveLength(0) - }) + expect(results).toHaveLength(0); + }); test(`${permission} key: create index with already existing uid should fail`, async () => { - const client = await getClient(permission) - const { taskUid: firstCreate } = await client.createIndex(indexPk.uid) - await client.waitForTask(firstCreate) + const client = await getClient(permission); + const { taskUid: firstCreate } = await client.createIndex(indexPk.uid); + await client.waitForTask(firstCreate); - const { taskUid: secondCreate } = await client.createIndex(indexPk.uid) - const task = await client.waitForTask(secondCreate) + const { taskUid: secondCreate } = await client.createIndex(indexPk.uid); + const task = await client.waitForTask(secondCreate); - expect(task.status).toBe('failed') - }) + 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 { taskUid } = await index.delete() + const client = await getClient(permission); + const index = client.index(indexNoPk.uid); + const { taskUid } = await index.delete(); - const task = await client.waitForTask(taskUid) + const task = await client.waitForTask(taskUid); - expect(task.status).toEqual('failed') - }) + 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) + const client = await getClient(permission); + const index = client.index(indexPk.uid); await expect(index.getRawInfo()).rejects.toHaveProperty( 'cause.code', - ErrorStatusCode.INDEX_NOT_FOUND - ) - }) + ErrorStatusCode.INDEX_NOT_FOUND, + ); + }); test(`${permission} key: Swap two indexes`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await client .index(index.uid) - .addDocuments([{ id: 1, title: `index_1` }]) + .addDocuments([{ id: 1, title: `index_1` }]); const { taskUid } = await client .index(index2.uid) - .addDocuments([{ id: 1, title: 'index_2' }]) - await client.waitForTask(taskUid) + .addDocuments([{ id: 1, title: 'index_2' }]); + await client.waitForTask(taskUid); const swaps = [ { indexes: [index.uid, index2.uid], }, - ] + ]; - const swapTask = await client.swapIndexes(swaps) - const resolvedTask = await client.waitForTask(swapTask.taskUid) - const docIndex1 = await client.index(index.uid).getDocument(1) - const docIndex2 = await client.index(index2.uid).getDocument(1) + const swapTask = await client.swapIndexes(swaps); + const resolvedTask = await client.waitForTask(swapTask.taskUid); + 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(TaskTypes.INDEXES_SWAP) - expect(resolvedTask.details.swaps).toEqual(swaps) - }) + expect(docIndex1.title).toEqual('index_2'); + expect(docIndex2.title).toEqual('index_1'); + expect(resolvedTask.type).toEqual(TaskTypes.INDEXES_SWAP); + expect(resolvedTask.details.swaps).toEqual(swaps); + }); test(`${permission} key: Swap two indexes with one that does not exist`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const { taskUid } = await client .index(index2.uid) - .addDocuments([{ id: 1, title: 'index_2' }]) + .addDocuments([{ id: 1, title: 'index_2' }]); - await client.waitForTask(taskUid) + await client.waitForTask(taskUid); const swaps = [ { indexes: ['does_not_exist', index2.uid], }, - ] + ]; - const swapTask = await client.swapIndexes(swaps) - const resolvedTask = await client.waitForTask(swapTask.taskUid) + const swapTask = await client.swapIndexes(swaps); + const resolvedTask = await client.waitForTask(swapTask.taskUid); - expect(resolvedTask.type).toEqual(TaskTypes.INDEXES_SWAP) + expect(resolvedTask.type).toEqual(TaskTypes.INDEXES_SWAP); expect(resolvedTask.error?.code).toEqual( - ErrorStatusCode.INDEX_NOT_FOUND - ) - expect(resolvedTask.details.swaps).toEqual(swaps) - }) + 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 client = await getClient(permission); const swaps = [ { indexes: [index.uid, index.uid], }, - ] + ]; await expect(client.swapIndexes(swaps)).rejects.toHaveProperty( 'cause.code', - ErrorStatusCode.INVALID_SWAP_DUPLICATE_INDEX_FOUND - ) - }) - }) + ErrorStatusCode.INVALID_SWAP_DUPLICATE_INDEX_FOUND, + ); + }); + }); describe('Test on base routes', () => { test(`${permission} key: get health`, async () => { - const client = await getClient(permission) - const response: Health = await client.health() + const client = await getClient(permission); + const response: Health = await client.health(); expect(response).toHaveProperty( 'status', - expect.stringMatching('available') - ) - }) + expect.stringMatching('available'), + ); + }); test(`${permission} key: is server healthy`, async () => { - const client = await getClient(permission) - const response: boolean = await client.isHealthy() - expect(response).toBe(true) - }) + const client = await getClient(permission); + const response: boolean = await client.isHealthy(); + expect(response).toBe(true); + }); test(`${permission} key: is healthy return false on bad host`, async () => { - const client = new MeiliSearch({ host: 'http://localhost:9345' }) - const response: boolean = await client.isHealthy() - expect(response).toBe(false) - }) + const client = new MeiliSearch({ host: 'http://localhost:9345' }); + const response: boolean = await client.isHealthy(); + expect(response).toBe(false); + }); test(`${permission} key: get version`, async () => { - const client = await getClient(permission) - const response: Version = await client.getVersion() - expect(response).toHaveProperty('commitSha', expect.any(String)) - expect(response).toHaveProperty('commitDate', expect.any(String)) - expect(response).toHaveProperty('pkgVersion', expect.any(String)) - }) + const client = await getClient(permission); + const response: Version = await client.getVersion(); + expect(response).toHaveProperty('commitSha', expect.any(String)); + expect(response).toHaveProperty('commitDate', expect.any(String)); + expect(response).toHaveProperty('pkgVersion', expect.any(String)); + }); test(`${permission} key: get /stats information`, async () => { - const client = await getClient(permission) - const response: Stats = await client.getStats() - expect(response).toHaveProperty('databaseSize', expect.any(Number)) - expect(response).toHaveProperty('lastUpdate') // TODO: Could be null, find out why - expect(response).toHaveProperty('indexes', expect.any(Object)) - }) - }) - } -) + const client = await getClient(permission); + const response: Stats = await client.getStats(); + expect(response).toHaveProperty('databaseSize', expect.any(Number)); + expect(response).toHaveProperty('lastUpdate'); // TODO: Could be null, find out why + expect(response).toHaveProperty('indexes', expect.any(Object)); + }); + }); + }, +); describe.each([{ permission: 'Search' }])( 'Test on misc client methods w/ search apikey', ({ permission }) => { beforeEach(() => { - return clearAllIndexes(config) - }) + 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) + const client = await getClient(permission); await expect(client.getIndexes()).rejects.toHaveProperty( 'cause.code', - ErrorStatusCode.INVALID_API_KEY - ) - }) + ErrorStatusCode.INVALID_API_KEY, + ); + }); test(`${permission} key: try to create Index with primary key and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect( client.createIndex(indexPk.uid, { primaryKey: indexPk.primaryKey, - }) - ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY) - }) + }), + ).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) + const client = await getClient(permission); await expect(client.createIndex(indexNoPk.uid)).rejects.toHaveProperty( 'cause.code', - ErrorStatusCode.INVALID_API_KEY - ) - }) + ErrorStatusCode.INVALID_API_KEY, + ); + }); test(`${permission} key: try to delete index and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect(client.deleteIndex(indexPk.uid)).rejects.toHaveProperty( 'cause.code', - ErrorStatusCode.INVALID_API_KEY - ) - }) + ErrorStatusCode.INVALID_API_KEY, + ); + }); test(`${permission} key: try to update index and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect( client.updateIndex(indexPk.uid, { primaryKey: indexPk.primaryKey, - }) - ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY) - }) - }) + }), + ).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) - const response: Health = await client.health() + const client = await getClient(permission); + const response: Health = await client.health(); expect(response).toHaveProperty( 'status', - expect.stringMatching('available') - ) - }) + expect.stringMatching('available'), + ); + }); test(`${permission} key: try to get version and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect(client.getVersion()).rejects.toHaveProperty( 'cause.code', - ErrorStatusCode.INVALID_API_KEY - ) - }) + ErrorStatusCode.INVALID_API_KEY, + ); + }); test(`${permission} key: try to get /stats information and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect(client.getStats()).rejects.toHaveProperty( 'cause.code', - ErrorStatusCode.INVALID_API_KEY - ) - }) - }) - } -) + ErrorStatusCode.INVALID_API_KEY, + ); + }); + }); + }, +); describe.each([{ permission: 'No' }])( 'Test on misc client methods w/ no apiKey client', ({ permission }) => { beforeEach(() => { - return clearAllIndexes(config) - }) + 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) + const client = await getClient(permission); await expect(client.getIndexes()).rejects.toHaveProperty( 'cause.code', - ErrorStatusCode.MISSING_AUTHORIZATION_HEADER - ) - }) + ErrorStatusCode.MISSING_AUTHORIZATION_HEADER, + ); + }); test(`${permission} key: try to create Index with primary key and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect( client.createIndex(indexPk.uid, { primaryKey: indexPk.primaryKey, - }) + }), ).rejects.toHaveProperty( 'cause.code', - ErrorStatusCode.MISSING_AUTHORIZATION_HEADER - ) - }) + ErrorStatusCode.MISSING_AUTHORIZATION_HEADER, + ); + }); test(`${permission} key: try to create Index with NO primary key and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect(client.createIndex(indexNoPk.uid)).rejects.toHaveProperty( 'cause.code', - ErrorStatusCode.MISSING_AUTHORIZATION_HEADER - ) - }) + ErrorStatusCode.MISSING_AUTHORIZATION_HEADER, + ); + }); test(`${permission} key: try to delete index and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect(client.deleteIndex(indexPk.uid)).rejects.toHaveProperty( 'cause.code', - ErrorStatusCode.MISSING_AUTHORIZATION_HEADER - ) - }) + ErrorStatusCode.MISSING_AUTHORIZATION_HEADER, + ); + }); test(`${permission} key: try to update index and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect( client.updateIndex(indexPk.uid, { primaryKey: indexPk.primaryKey, - }) + }), ).rejects.toHaveProperty( 'cause.code', - ErrorStatusCode.MISSING_AUTHORIZATION_HEADER - ) - }) - }) + ErrorStatusCode.MISSING_AUTHORIZATION_HEADER, + ); + }); + }); describe('Test on misc client methods', () => { test(`${permission} key: get health`, async () => { - const client = await getClient(permission) - const response: Health = await client.health() + const client = await getClient(permission); + const response: Health = await client.health(); expect(response).toHaveProperty( 'status', - expect.stringMatching('available') - ) - }) + expect.stringMatching('available'), + ); + }); test(`${permission} key: try to get version and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect(client.getVersion()).rejects.toHaveProperty( 'cause.code', - ErrorStatusCode.MISSING_AUTHORIZATION_HEADER - ) - }) + ErrorStatusCode.MISSING_AUTHORIZATION_HEADER, + ); + }); test(`${permission} key: try to get /stats information and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect(client.getStats()).rejects.toHaveProperty( 'cause.code', - ErrorStatusCode.MISSING_AUTHORIZATION_HEADER - ) - }) - }) - } -) + ErrorStatusCode.MISSING_AUTHORIZATION_HEADER, + ); + }); + }); + }, +); describe.each([ { host: BAD_HOST, trailing: false }, @@ -724,92 +724,92 @@ describe.each([ { host: `${BAD_HOST}/trailing/`, trailing: true }, ])('Tests on url construction', ({ host, trailing }) => { test(`Test getIndex route`, async () => { - const route = `indexes/${indexPk.uid}` - const client = new MeiliSearch({ host }) - const strippedHost = trailing ? host.slice(0, -1) : host + 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` - ) - }) + `Request to ${strippedHost}/${route} has failed`, + ); + }); test(`Test createIndex route`, async () => { - const route = `indexes` - const client = new MeiliSearch({ host }) - const strippedHost = trailing ? host.slice(0, -1) : host + 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` - ) - }) + `Request to ${strippedHost}/${route} has failed`, + ); + }); test(`Test updateIndex route`, async () => { - const route = `indexes/${indexPk.uid}` - const client = new MeiliSearch({ host }) - const strippedHost = trailing ? host.slice(0, -1) : host + 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` - ) - }) + `Request to ${strippedHost}/${route} has failed`, + ); + }); test(`Test deleteIndex route`, async () => { - const route = `indexes/${indexPk.uid}` - const client = new MeiliSearch({ host }) - const strippedHost = trailing ? host.slice(0, -1) : host + 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` - ) - }) + `Request to ${strippedHost}/${route} has failed`, + ); + }); test(`Test get indexes route`, async () => { - const route = `indexes` - const client = new MeiliSearch({ host }) - const strippedHost = trailing ? host.slice(0, -1) : host + 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` - ) - }) + `Request to ${strippedHost}/${route} has failed`, + ); + }); test(`Test getKeys route`, async () => { - const route = `keys` - const client = new MeiliSearch({ host }) - const strippedHost = trailing ? host.slice(0, -1) : host + const route = `keys`; + const client = new MeiliSearch({ host }); + const strippedHost = trailing ? host.slice(0, -1) : host; await expect(client.getKeys()).rejects.toHaveProperty( 'message', - `Request to ${strippedHost}/${route} has failed` - ) - }) + `Request to ${strippedHost}/${route} has failed`, + ); + }); test(`Test health route`, async () => { - const route = `health` - const client = new MeiliSearch({ host }) - const strippedHost = trailing ? host.slice(0, -1) : host + const route = `health`; + const client = new MeiliSearch({ host }); + const strippedHost = trailing ? host.slice(0, -1) : host; await expect(client.health()).rejects.toHaveProperty( 'message', - `Request to ${strippedHost}/${route} has failed` - ) - }) + `Request to ${strippedHost}/${route} has failed`, + ); + }); test(`Test stats route`, async () => { - const route = `stats` - const client = new MeiliSearch({ host }) - const strippedHost = trailing ? host.slice(0, -1) : host + const route = `stats`; + const client = new MeiliSearch({ host }); + const strippedHost = trailing ? host.slice(0, -1) : host; await expect(client.getStats()).rejects.toHaveProperty( 'message', - `Request to ${strippedHost}/${route} has failed` - ) - }) + `Request to ${strippedHost}/${route} has failed`, + ); + }); test(`Test version route`, async () => { - const route = `version` - const client = new MeiliSearch({ host }) - const strippedHost = trailing ? host.slice(0, -1) : host + const route = `version`; + const client = new MeiliSearch({ host }); + const strippedHost = trailing ? host.slice(0, -1) : host; await expect(client.getVersion()).rejects.toHaveProperty( 'message', - `Request to ${strippedHost}/${route} has failed` - ) - }) -}) + `Request to ${strippedHost}/${route} has failed`, + ); + }); +}); diff --git a/tests/dictionary.test.ts b/tests/dictionary.test.ts index 1fa67c143..4da655462 100644 --- a/tests/dictionary.test.ts +++ b/tests/dictionary.test.ts @@ -1,4 +1,4 @@ -import { EnqueuedTask } from '../src/enqueued-task' +import { EnqueuedTask } from '../src/enqueued-task'; import { clearAllIndexes, config, @@ -6,71 +6,73 @@ import { MeiliSearch, getClient, dataset, -} from './utils/meilisearch-test-utils' +} from './utils/meilisearch-test-utils'; const index = { uid: 'movies_test', -} +}; -jest.setTimeout(100 * 1000) +jest.setTimeout(100 * 1000); afterAll(() => { - return clearAllIndexes(config) -}) + return clearAllIndexes(config); +}); describe.each([{ permission: 'Master' }, { permission: 'Admin' }])( 'Test on dictionary', ({ permission }) => { beforeEach(async () => { - const client = await getClient('Master') - const { taskUid } = await client.index(index.uid).addDocuments(dataset) - await client.waitForTask(taskUid) - }) + const client = await getClient('Master'); + const { taskUid } = await client.index(index.uid).addDocuments(dataset); + await client.waitForTask(taskUid); + }); test(`${permission} key: Get default dictionary`, async () => { - const client = await getClient(permission) - const response: string[] = await client.index(index.uid).getDictionary() + const client = await getClient(permission); + const response: string[] = await client.index(index.uid).getDictionary(); - expect(response).toEqual([]) - }) + expect(response).toEqual([]); + }); test(`${permission} key: Update dictionary`, async () => { - const client = await getClient(permission) - const newDictionary = ['J. K.', 'J. R. R.'] + const client = await getClient(permission); + const newDictionary = ['J. K.', 'J. R. R.']; const task: EnqueuedTask = await client .index(index.uid) - .updateDictionary(newDictionary) - await client.index(index.uid).waitForTask(task.taskUid) + .updateDictionary(newDictionary); + await client.index(index.uid).waitForTask(task.taskUid); - const response: string[] = await client.index(index.uid).getDictionary() + const response: string[] = await client.index(index.uid).getDictionary(); - expect(response).toEqual(newDictionary) - }) + expect(response).toEqual(newDictionary); + }); test(`${permission} key: Update dictionary with null value`, async () => { - const client = await getClient(permission) - const newDictionary = null + const client = await getClient(permission); + const newDictionary = null; const task: EnqueuedTask = await client .index(index.uid) - .updateDictionary(newDictionary) - await client.index(index.uid).waitForTask(task.taskUid) + .updateDictionary(newDictionary); + await client.index(index.uid).waitForTask(task.taskUid); - const response: string[] = await client.index(index.uid).getDictionary() + const response: string[] = await client.index(index.uid).getDictionary(); - expect(response).toEqual([]) - }) + expect(response).toEqual([]); + }); test(`${permission} key: Reset dictionary`, async () => { - const client = await getClient(permission) - const task: EnqueuedTask = await client.index(index.uid).resetDictionary() - await client.index(index.uid).waitForTask(task.taskUid) + const client = await getClient(permission); + const task: EnqueuedTask = await client + .index(index.uid) + .resetDictionary(); + await client.index(index.uid).waitForTask(task.taskUid); - const response: string[] = await client.index(index.uid).getDictionary() + const response: string[] = await client.index(index.uid).getDictionary(); - expect(response).toEqual([]) - }) - } -) + expect(response).toEqual([]); + }); + }, +); describe.each([ { host: BAD_HOST, trailing: false }, @@ -78,38 +80,38 @@ describe.each([ { host: `${BAD_HOST}/trailing/`, trailing: true }, ])('Tests on url construction', ({ host, trailing }) => { test(`Test getDictionary route`, async () => { - const route = `indexes/${index.uid}/settings/dictionary` - const client = new MeiliSearch({ host }) - const strippedHost = trailing ? host.slice(0, -1) : host + const route = `indexes/${index.uid}/settings/dictionary`; + const client = new MeiliSearch({ host }); + const strippedHost = trailing ? host.slice(0, -1) : host; await expect( - client.index(index.uid).getDictionary() + client.index(index.uid).getDictionary(), ).rejects.toHaveProperty( 'message', - `Request to ${strippedHost}/${route} has failed` - ) - }) + `Request to ${strippedHost}/${route} has failed`, + ); + }); test(`Test updateDictionary route`, async () => { - const route = `indexes/${index.uid}/settings/dictionary` - const client = new MeiliSearch({ host }) - const strippedHost = trailing ? host.slice(0, -1) : host + const route = `indexes/${index.uid}/settings/dictionary`; + const client = new MeiliSearch({ host }); + const strippedHost = trailing ? host.slice(0, -1) : host; await expect( - client.index(index.uid).updateDictionary([]) + client.index(index.uid).updateDictionary([]), ).rejects.toHaveProperty( 'message', - `Request to ${strippedHost}/${route} has failed` - ) - }) + `Request to ${strippedHost}/${route} has failed`, + ); + }); test(`Test resetDictionary route`, async () => { - const route = `indexes/${index.uid}/settings/dictionary` - const client = new MeiliSearch({ host }) - const strippedHost = trailing ? host.slice(0, -1) : host + const route = `indexes/${index.uid}/settings/dictionary`; + const client = new MeiliSearch({ host }); + const strippedHost = trailing ? host.slice(0, -1) : host; await expect( - client.index(index.uid).resetDictionary() + client.index(index.uid).resetDictionary(), ).rejects.toHaveProperty( 'message', - `Request to ${strippedHost}/${route} has failed` - ) - }) -}) + `Request to ${strippedHost}/${route} has failed`, + ); + }); +}); diff --git a/tests/displayed_attributes.test.ts b/tests/displayed_attributes.test.ts index 36566fa10..938df5856 100644 --- a/tests/displayed_attributes.test.ts +++ b/tests/displayed_attributes.test.ts @@ -1,4 +1,4 @@ -import { ErrorStatusCode } from '../src/types' +import { ErrorStatusCode } from '../src/types'; import { clearAllIndexes, config, @@ -6,146 +6,148 @@ import { MeiliSearch, getClient, dataset, -} from './utils/meilisearch-test-utils' +} from './utils/meilisearch-test-utils'; const index = { uid: 'movies_test', -} +}; -jest.setTimeout(100 * 1000) +jest.setTimeout(100 * 1000); afterAll(() => { - return clearAllIndexes(config) -}) + return clearAllIndexes(config); +}); describe.each([{ permission: 'Master' }, { permission: 'Admin' }])( 'Test on displayed attributes', ({ permission }) => { beforeEach(async () => { - await clearAllIndexes(config) - const client = await getClient('Master') - const { taskUid } = await client.index(index.uid).addDocuments(dataset) - await client.waitForTask(taskUid) - }) + await clearAllIndexes(config); + const client = await getClient('Master'); + const { taskUid } = await client.index(index.uid).addDocuments(dataset); + await client.waitForTask(taskUid); + }); test(`${permission} key: Get default displayed attributes`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); - const response = await client.index(index.uid).getDisplayedAttributes() - expect(response).toEqual(['*']) - }) + const response = await client.index(index.uid).getDisplayedAttributes(); + expect(response).toEqual(['*']); + }); test(`${permission} key: Update displayed attributes`, async () => { - const client = await getClient(permission) - const newDisplayedAttribute = ['title'] + const client = await getClient(permission); + const newDisplayedAttribute = ['title']; const task = await client .index(index.uid) - .updateDisplayedAttributes(newDisplayedAttribute) - await client.index(index.uid).waitForTask(task.taskUid) + .updateDisplayedAttributes(newDisplayedAttribute); + await client.index(index.uid).waitForTask(task.taskUid); - const response = await client.index(index.uid).getDisplayedAttributes() + const response = await client.index(index.uid).getDisplayedAttributes(); - expect(response).toEqual(newDisplayedAttribute) - }) + expect(response).toEqual(newDisplayedAttribute); + }); test(`${permission} key: Update displayed attributes at null`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); - const task = await client.index(index.uid).updateDisplayedAttributes(null) - await client.index(index.uid).waitForTask(task.taskUid) + const task = await client + .index(index.uid) + .updateDisplayedAttributes(null); + await client.index(index.uid).waitForTask(task.taskUid); - const response = await client.index(index.uid).getDisplayedAttributes() + const response = await client.index(index.uid).getDisplayedAttributes(); - expect(response).toEqual(['*']) - }) + expect(response).toEqual(['*']); + }); test(`${permission} key: Reset displayed attributes`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); - const task = await client.index(index.uid).resetDisplayedAttributes() - await client.index(index.uid).waitForTask(task.taskUid) + const task = await client.index(index.uid).resetDisplayedAttributes(); + await client.index(index.uid).waitForTask(task.taskUid); - const response = await client.index(index.uid).getDisplayedAttributes() + const response = await client.index(index.uid).getDisplayedAttributes(); - expect(response).toEqual(['*']) - }) - } -) + expect(response).toEqual(['*']); + }); + }, +); describe.each([{ permission: 'Search' }])( 'Test on displayed attributes', ({ permission }) => { beforeEach(async () => { - await clearAllIndexes(config) - const client = await getClient('Master') - const { taskUid } = await client.createIndex(index.uid) - await client.waitForTask(taskUid) - }) + await clearAllIndexes(config); + const client = await getClient('Master'); + const { taskUid } = await client.createIndex(index.uid); + await client.waitForTask(taskUid); + }); test(`${permission} key: try to get displayed attributes and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect( - client.index(index.uid).getDisplayedAttributes() - ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY) - }) + client.index(index.uid).getDisplayedAttributes(), + ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY); + }); test(`${permission} key: try to update displayed attributes and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect( - client.index(index.uid).updateDisplayedAttributes([]) - ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY) - }) + client.index(index.uid).updateDisplayedAttributes([]), + ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY); + }); test(`${permission} key: try to reset displayed attributes and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect( - client.index(index.uid).resetDisplayedAttributes() - ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY) - }) - } -) + client.index(index.uid).resetDisplayedAttributes(), + ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY); + }); + }, +); describe.each([{ permission: 'No' }])( 'Test on displayed attributes', ({ permission }) => { beforeEach(async () => { - await clearAllIndexes(config) - const client = await getClient('Master') - const { taskUid } = await client.createIndex(index.uid) - await client.waitForTask(taskUid) - }) + await clearAllIndexes(config); + const client = await getClient('Master'); + const { taskUid } = await client.createIndex(index.uid); + await client.waitForTask(taskUid); + }); test(`${permission} key: try to get displayed attributes and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect( - client.index(index.uid).getDisplayedAttributes() + client.index(index.uid).getDisplayedAttributes(), ).rejects.toHaveProperty( 'cause.code', - ErrorStatusCode.MISSING_AUTHORIZATION_HEADER - ) - }) + ErrorStatusCode.MISSING_AUTHORIZATION_HEADER, + ); + }); test(`${permission} key: try to update displayed attributes and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect( - client.index(index.uid).updateDisplayedAttributes([]) + client.index(index.uid).updateDisplayedAttributes([]), ).rejects.toHaveProperty( 'cause.code', - ErrorStatusCode.MISSING_AUTHORIZATION_HEADER - ) - }) + ErrorStatusCode.MISSING_AUTHORIZATION_HEADER, + ); + }); test(`${permission} key: try to reset displayed attributes and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect( - client.index(index.uid).resetDisplayedAttributes() + client.index(index.uid).resetDisplayedAttributes(), ).rejects.toHaveProperty( 'cause.code', - ErrorStatusCode.MISSING_AUTHORIZATION_HEADER - ) - }) - } -) + ErrorStatusCode.MISSING_AUTHORIZATION_HEADER, + ); + }); + }, +); describe.each([ { host: BAD_HOST, trailing: false }, @@ -153,38 +155,38 @@ describe.each([ { host: `${BAD_HOST}/trailing/`, trailing: true }, ])('Tests on url construction', ({ host, trailing }) => { test(`Test getDisplayedAttributes route`, async () => { - const route = `indexes/${index.uid}/settings/displayed-attributes` - const client = new MeiliSearch({ host }) - const strippedHost = trailing ? host.slice(0, -1) : host + const route = `indexes/${index.uid}/settings/displayed-attributes`; + const client = new MeiliSearch({ host }); + const strippedHost = trailing ? host.slice(0, -1) : host; await expect( - client.index(index.uid).getDisplayedAttributes() + client.index(index.uid).getDisplayedAttributes(), ).rejects.toHaveProperty( 'message', - `Request to ${strippedHost}/${route} has failed` - ) - }) + `Request to ${strippedHost}/${route} has failed`, + ); + }); test(`Test updateDisplayedAttributes route`, async () => { - const route = `indexes/${index.uid}/settings/displayed-attributes` - const client = new MeiliSearch({ host }) - const strippedHost = trailing ? host.slice(0, -1) : host + const route = `indexes/${index.uid}/settings/displayed-attributes`; + const client = new MeiliSearch({ host }); + const strippedHost = trailing ? host.slice(0, -1) : host; await expect( - client.index(index.uid).updateDisplayedAttributes([]) + client.index(index.uid).updateDisplayedAttributes([]), ).rejects.toHaveProperty( 'message', - `Request to ${strippedHost}/${route} has failed` - ) - }) + `Request to ${strippedHost}/${route} has failed`, + ); + }); test(`Test resetDisplayedAttributes route`, async () => { - const route = `indexes/${index.uid}/settings/displayed-attributes` - const client = new MeiliSearch({ host }) - const strippedHost = trailing ? host.slice(0, -1) : host + const route = `indexes/${index.uid}/settings/displayed-attributes`; + const client = new MeiliSearch({ host }); + const strippedHost = trailing ? host.slice(0, -1) : host; await expect( - client.index(index.uid).resetDisplayedAttributes() + client.index(index.uid).resetDisplayedAttributes(), ).rejects.toHaveProperty( 'message', - `Request to ${strippedHost}/${route} has failed` - ) - }) -}) + `Request to ${strippedHost}/${route} has failed`, + ); + }); +}); diff --git a/tests/distinct_attribute.test.ts b/tests/distinct_attribute.test.ts index 568883361..0797ab18a 100644 --- a/tests/distinct_attribute.test.ts +++ b/tests/distinct_attribute.test.ts @@ -1,4 +1,4 @@ -import { ErrorStatusCode } from '../src/types' +import { ErrorStatusCode } from '../src/types'; import { clearAllIndexes, config, @@ -6,138 +6,138 @@ import { MeiliSearch, getClient, dataset, -} from './utils/meilisearch-test-utils' +} from './utils/meilisearch-test-utils'; const index = { uid: 'movies_test', -} +}; -jest.setTimeout(100 * 1000) +jest.setTimeout(100 * 1000); afterAll(() => { - return clearAllIndexes(config) -}) + return clearAllIndexes(config); +}); describe.each([{ permission: 'Master' }, { permission: 'Admin' }])( 'Test on distinct attribute', ({ permission }) => { beforeEach(async () => { - await clearAllIndexes(config) - const client = await getClient('master') + await clearAllIndexes(config); + const client = await getClient('master'); - const { taskUid } = await client.index(index.uid).addDocuments(dataset) - await client.waitForTask(taskUid) - }) + const { taskUid } = await client.index(index.uid).addDocuments(dataset); + await client.waitForTask(taskUid); + }); test(`${permission} key: Get default distinct attribute`, async () => { - const client = await getClient(permission) - const response = await client.index(index.uid).getDistinctAttribute() - expect(response).toEqual(null) - }) + const client = await getClient(permission); + const response = await client.index(index.uid).getDistinctAttribute(); + expect(response).toEqual(null); + }); test(`${permission} key: Update distinct attribute`, async () => { - const client = await getClient(permission) - const newDistinctAttribute = 'title' + const client = await getClient(permission); + const newDistinctAttribute = 'title'; const task = await client .index(index.uid) - .updateDistinctAttribute(newDistinctAttribute) - await client.index(index.uid).waitForTask(task.taskUid) + .updateDistinctAttribute(newDistinctAttribute); + await client.index(index.uid).waitForTask(task.taskUid); - const response = await client.index(index.uid).getDistinctAttribute() + const response = await client.index(index.uid).getDistinctAttribute(); - expect(response).toEqual(newDistinctAttribute) - }) + expect(response).toEqual(newDistinctAttribute); + }); test(`${permission} key: Update distinct attribute at null`, async () => { - const client = await getClient(permission) - const task = await client.index(index.uid).updateDistinctAttribute(null) - await client.index(index.uid).waitForTask(task.taskUid) + const client = await getClient(permission); + const task = await client.index(index.uid).updateDistinctAttribute(null); + await client.index(index.uid).waitForTask(task.taskUid); - const response = await client.index(index.uid).getDistinctAttribute() + const response = await client.index(index.uid).getDistinctAttribute(); - expect(response).toEqual(null) - }) + expect(response).toEqual(null); + }); test(`${permission} key: Reset distinct attribute`, async () => { - const client = await getClient(permission) - const task = await client.index(index.uid).resetDistinctAttribute() - await client.index(index.uid).waitForTask(task.taskUid) + const client = await getClient(permission); + const task = await client.index(index.uid).resetDistinctAttribute(); + await client.index(index.uid).waitForTask(task.taskUid); - const response = await client.index(index.uid).getDistinctAttribute() + const response = await client.index(index.uid).getDistinctAttribute(); - expect(response).toEqual(null) - }) - } -) + expect(response).toEqual(null); + }); + }, +); describe.each([{ permission: 'Search' }])( 'Test on distinct attribute', ({ permission }) => { beforeEach(async () => { - await clearAllIndexes(config) - }) + await clearAllIndexes(config); + }); test(`${permission} key: try to get distinct attribute and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect( - client.index(index.uid).getDistinctAttribute() - ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY) - }) + client.index(index.uid).getDistinctAttribute(), + ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY); + }); test(`${permission} key: try to update distinct attribute and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect( - client.index(index.uid).updateDistinctAttribute('title') - ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY) - }) + client.index(index.uid).updateDistinctAttribute('title'), + ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY); + }); test(`${permission} key: try to reset distinct attribute and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect( - client.index(index.uid).resetDistinctAttribute() - ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY) - }) - } -) + client.index(index.uid).resetDistinctAttribute(), + ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY); + }); + }, +); describe.each([{ permission: 'No' }])( 'Test on distinct attribute', ({ permission }) => { beforeEach(async () => { - await clearAllIndexes(config) - }) + await clearAllIndexes(config); + }); test(`${permission} key: try to get distinct attribute and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect( - client.index(index.uid).getDistinctAttribute() + client.index(index.uid).getDistinctAttribute(), ).rejects.toHaveProperty( 'cause.code', - ErrorStatusCode.MISSING_AUTHORIZATION_HEADER - ) - }) + ErrorStatusCode.MISSING_AUTHORIZATION_HEADER, + ); + }); test(`${permission} key: try to update distinct attribute and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect( - client.index(index.uid).updateDistinctAttribute('title') + client.index(index.uid).updateDistinctAttribute('title'), ).rejects.toHaveProperty( 'cause.code', - ErrorStatusCode.MISSING_AUTHORIZATION_HEADER - ) - }) + ErrorStatusCode.MISSING_AUTHORIZATION_HEADER, + ); + }); test(`${permission} key: try to reset distinct attribute and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect( - client.index(index.uid).resetDistinctAttribute() + client.index(index.uid).resetDistinctAttribute(), ).rejects.toHaveProperty( 'cause.code', - ErrorStatusCode.MISSING_AUTHORIZATION_HEADER - ) - }) - } -) + ErrorStatusCode.MISSING_AUTHORIZATION_HEADER, + ); + }); + }, +); describe.each([ { host: BAD_HOST, trailing: false }, @@ -145,38 +145,38 @@ describe.each([ { host: `${BAD_HOST}/trailing/`, trailing: true }, ])('Tests on url construction', ({ host, trailing }) => { test(`Test getDistinctAttribute route`, async () => { - const route = `indexes/${index.uid}/settings/distinct-attribute` - const client = new MeiliSearch({ host }) - const strippedHost = trailing ? host.slice(0, -1) : host + const route = `indexes/${index.uid}/settings/distinct-attribute`; + const client = new MeiliSearch({ host }); + const strippedHost = trailing ? host.slice(0, -1) : host; await expect( - client.index(index.uid).getDistinctAttribute() + client.index(index.uid).getDistinctAttribute(), ).rejects.toHaveProperty( 'message', - `Request to ${strippedHost}/${route} has failed` - ) - }) + `Request to ${strippedHost}/${route} has failed`, + ); + }); test(`Test updateDistinctAttribute route`, async () => { - const route = `indexes/${index.uid}/settings/distinct-attribute` - const client = new MeiliSearch({ host }) - const strippedHost = trailing ? host.slice(0, -1) : host + const route = `indexes/${index.uid}/settings/distinct-attribute`; + const client = new MeiliSearch({ host }); + const strippedHost = trailing ? host.slice(0, -1) : host; await expect( - client.index(index.uid).updateDistinctAttribute('a') + client.index(index.uid).updateDistinctAttribute('a'), ).rejects.toHaveProperty( 'message', - `Request to ${strippedHost}/${route} has failed` - ) - }) + `Request to ${strippedHost}/${route} has failed`, + ); + }); test(`Test resetDistinctAttribute route`, async () => { - const route = `indexes/${index.uid}/settings/distinct-attribute` - const client = new MeiliSearch({ host }) - const strippedHost = trailing ? host.slice(0, -1) : host + const route = `indexes/${index.uid}/settings/distinct-attribute`; + const client = new MeiliSearch({ host }); + const strippedHost = trailing ? host.slice(0, -1) : host; await expect( - client.index(index.uid).resetDistinctAttribute() + client.index(index.uid).resetDistinctAttribute(), ).rejects.toHaveProperty( 'message', - `Request to ${strippedHost}/${route} has failed` - ) - }) -}) + `Request to ${strippedHost}/${route} has failed`, + ); + }); +}); diff --git a/tests/documents.test.ts b/tests/documents.test.ts index b91eed06a..5340147b7 100644 --- a/tests/documents.test.ts +++ b/tests/documents.test.ts @@ -1,4 +1,4 @@ -import { ErrorStatusCode, TaskStatus, TaskTypes } from '../src/types' +import { ErrorStatusCode, TaskStatus, TaskTypes } from '../src/types'; import { clearAllIndexes, config, @@ -9,801 +9,813 @@ import { Book, getKey, HOST, -} from './utils/meilisearch-test-utils' +} from './utils/meilisearch-test-utils'; const indexNoPk = { uid: 'movies_test', -} +}; const indexPk = { uid: 'movies_test2', primaryKey: 'id', -} +}; -jest.setTimeout(100 * 1000) +jest.setTimeout(100 * 1000); afterAll(() => { - return clearAllIndexes(config) -}) + return clearAllIndexes(config); +}); describe('Documents tests', () => { describe.each([{ permission: 'Master' }, { permission: 'Admin' }])( 'Test on documents', ({ permission }) => { beforeEach(async () => { - await clearAllIndexes(config) - const client = await getClient('Master') + await clearAllIndexes(config); + const client = await getClient('Master'); const { taskUid: taskCreateNoPk } = await client.createIndex( - indexNoPk.uid - ) - await client.waitForTask(taskCreateNoPk) + indexNoPk.uid, + ); + await client.waitForTask(taskCreateNoPk); const { taskUid: taskCreateWithPk } = await client.createIndex( indexPk.uid, { primaryKey: indexPk.primaryKey, - } - ) - await client.waitForTask(taskCreateWithPk) - }) + }, + ); + await client.waitForTask(taskCreateWithPk); + }); test(`${permission} key: Add documents to uid with primary key in batch`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const tasks = await client .index(indexPk.uid) - .addDocumentsInBatches(dataset, 4) + .addDocumentsInBatches(dataset, 4); - expect(tasks).toHaveLength(2) + expect(tasks).toHaveLength(2); for (const task of tasks) { - const { type, status } = await client.waitForTask(task.taskUid) - expect(status).toBe(TaskStatus.TASK_SUCCEEDED) - expect(type).toBe(TaskTypes.DOCUMENTS_ADDITION_OR_UPDATE) + const { type, status } = await client.waitForTask(task.taskUid); + expect(status).toBe(TaskStatus.TASK_SUCCEEDED); + expect(type).toBe(TaskTypes.DOCUMENTS_ADDITION_OR_UPDATE); } - }) + }); test(`${permission} key: Get one document `, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const { taskUid } = await client .index(indexNoPk.uid) - .addDocuments(dataset) - await client.index(indexNoPk.uid).waitForTask(taskUid) + .addDocuments(dataset); + await client.index(indexNoPk.uid).waitForTask(taskUid); - const documentId = 1 + const documentId = 1; const document = await client .index(indexNoPk.uid) - .getDocument(documentId) + .getDocument(documentId); - expect(document.title).toEqual('Alice In Wonderland') - }) + expect(document.title).toEqual('Alice In Wonderland'); + }); test(`${permission} key: Get one document with fields parameter`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const { taskUid } = await client .index(indexNoPk.uid) - .addDocuments(dataset) - await client.index(indexNoPk.uid).waitForTask(taskUid) + .addDocuments(dataset); + await client.index(indexNoPk.uid).waitForTask(taskUid); - const documentId = 1 + const documentId = 1; const document = await client .index(indexNoPk.uid) - .getDocument(documentId, { fields: ['title'] }) + .getDocument(documentId, { fields: ['title'] }); - expect(document.title).toEqual('Alice In Wonderland') - expect(document.id).toBeUndefined() - }) + expect(document.title).toEqual('Alice In Wonderland'); + expect(document.id).toBeUndefined(); + }); test(`${permission} key: Get documents with string fields`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const documents = await client.index(indexNoPk.uid).getDocuments({ fields: 'id', - }) + }); expect( - documents.results.find((x) => Object.keys(x).length !== 1) - ).toBeUndefined() - }) + documents.results.find((x) => Object.keys(x).length !== 1), + ).toBeUndefined(); + }); test(`${permission} key: Get documents with array fields`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const { taskUid } = await client .index(indexPk.uid) - .addDocuments(dataset) - await client.waitForTask(taskUid) + .addDocuments(dataset); + await client.waitForTask(taskUid); const documents = await client.index(indexPk.uid).getDocuments({ fields: ['id'], - }) + }); const onlyIdFields = Array.from( new Set( documents.results.reduce( (acc, document) => [...acc, ...Object.keys(document)], - [] - ) - ) - ) + [], + ), + ), + ); - expect(onlyIdFields.length).toEqual(1) - expect(onlyIdFields[0]).toEqual('id') - }) + expect(onlyIdFields.length).toEqual(1); + expect(onlyIdFields[0]).toEqual('id'); + }); test(`${permission} key: Get documents with pagination`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const { taskUid } = await client .index(indexPk.uid) - .addDocuments(dataset) - await client.waitForTask(taskUid) + .addDocuments(dataset); + await client.waitForTask(taskUid); const documents = await client.index(indexPk.uid).getDocuments({ limit: 1, offset: 2, - }) + }); - expect(documents.results.length).toEqual(1) - expect(documents.limit).toEqual(1) - expect(documents.offset).toEqual(2) - }) + expect(documents.results.length).toEqual(1); + expect(documents.limit).toEqual(1); + expect(documents.offset).toEqual(2); + }); test(`${permission} key: Get documents with filters`, async () => { - const client = await getClient(permission) - await client.index(indexPk.uid).updateFilterableAttributes(['id']) + const client = await getClient(permission); + await client.index(indexPk.uid).updateFilterableAttributes(['id']); const { taskUid } = await client .index(indexPk.uid) - .addDocuments(dataset) - await client.waitForTask(taskUid) + .addDocuments(dataset); + await client.waitForTask(taskUid); const documents = await client.index(indexPk.uid).getDocuments({ filter: [['id = 1', 'id = 2']], - }) + }); - expect(documents.results.length).toEqual(2) - }) + expect(documents.results.length).toEqual(2); + }); test(`${permission} key: Get documents should trigger error with a MeilisearchRequestError`, async () => { - const apiKey = await getKey(permission) - const client = new MeiliSearch({ host: `${HOST}/indexes`, apiKey }) + const apiKey = await getKey(permission); + const client = new MeiliSearch({ host: `${HOST}/indexes`, apiKey }); try { - await client.index(indexPk.uid).getDocuments({ filter: '' }) + await client.index(indexPk.uid).getDocuments({ filter: '' }); fail( - 'getDocuments should have raised an error when the route does not exist' - ) + 'getDocuments should have raised an error when the route does not exist', + ); } catch (e: any) { expect(e.message).toEqual( - "404: Not Found\nHint: It might not be working because maybe you're not up to date with the Meilisearch version that getDocuments call requires." - ) + "404: Not Found\nHint: It might not be working because maybe you're not up to date with the Meilisearch version that getDocuments call requires.", + ); } - }) + }); test(`${permission} key: Get documents should trigger error with a hint on a MeilisearchApiError`, async () => { - const apiKey = await getKey(permission) - const client = new MeiliSearch({ host: `${HOST}`, apiKey }) + const apiKey = await getKey(permission); + const client = new MeiliSearch({ host: `${HOST}`, apiKey }); try { - await client.index(indexPk.uid).getDocuments({ filter: 'id = 1' }) + await client.index(indexPk.uid).getDocuments({ filter: 'id = 1' }); fail( - 'getDocuments should have raised an error when the filter is badly formatted' - ) + 'getDocuments should have raised an error when the filter is badly formatted', + ); } catch (e: any) { expect(e.message).toEqual( `Attribute \`id\` is not filterable. This index does not have configured filterable attributes. 1:3 id = 1 -Hint: It might not be working because maybe you're not up to date with the Meilisearch version that getDocuments call requires.` - ) +Hint: It might not be working because maybe you're not up to date with the Meilisearch version that getDocuments call requires.`, + ); } - }) + }); test(`${permission} key: Get documents from index that has NO primary key`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const { taskUid } = await client .index(indexNoPk.uid) - .addDocuments(dataset) - await client.index(indexNoPk.uid).waitForTask(taskUid) + .addDocuments(dataset); + await client.index(indexNoPk.uid).waitForTask(taskUid); const documents = await client.index(indexNoPk.uid).getDocuments({ fields: 'id', - }) + }); - expect(documents.results.length).toEqual(dataset.length) - }) + expect(documents.results.length).toEqual(dataset.length); + }); test(`${permission} key: Get documents from index that has a primary key`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const { taskUid } = await client .index(indexPk.uid) - .addDocuments(dataset) - await client.index(indexPk.uid).waitForTask(taskUid) + .addDocuments(dataset); + await client.index(indexPk.uid).waitForTask(taskUid); - const documents = await client.index(indexPk.uid).getDocuments() - expect(documents.results.length).toEqual(dataset.length) - }) + const documents = await client.index(indexPk.uid).getDocuments(); + expect(documents.results.length).toEqual(dataset.length); + }); test(`${permission} key: Replace documents from index that has NO primary key`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const { taskUid: addDocTask } = await client .index(indexNoPk.uid) - .addDocuments(dataset) - await client.index(indexNoPk.uid).waitForTask(addDocTask) - const id = 2 - const title = 'The Red And The Black' + .addDocuments(dataset); + await client.index(indexNoPk.uid).waitForTask(addDocTask); + const id = 2; + const title = 'The Red And The Black'; const task = await client .index(indexNoPk.uid) - .addDocuments([{ id, title }]) - await client.index(indexNoPk.uid).waitForTask(task.taskUid) - const response = await client.index(indexNoPk.uid).getDocument(id) + .addDocuments([{ id, title }]); + await client.index(indexNoPk.uid).waitForTask(task.taskUid); + const response = await client.index(indexNoPk.uid).getDocument(id); - expect(response).toHaveProperty('id', id) - expect(response).toHaveProperty('title', title) - }) + expect(response).toHaveProperty('id', id); + expect(response).toHaveProperty('title', title); + }); test(`${permission} key: Replace documents from index that has a primary key`, async () => { - const client = await getClient(permission) - const id = 2 - const title = 'The Red And The Black' + const client = await getClient(permission); + const id = 2; + const title = 'The Red And The Black'; const task = await client .index(indexPk.uid) - .addDocuments([{ id, title }]) - await client.index(indexPk.uid).waitForTask(task.taskUid) - const response = await client.index(indexPk.uid).getDocument(id) + .addDocuments([{ id, title }]); + await client.index(indexPk.uid).waitForTask(task.taskUid); + const response = await client.index(indexPk.uid).getDocument(id); - expect(response).toHaveProperty('id', id) - expect(response).toHaveProperty('title', title) - }) + expect(response).toHaveProperty('id', id); + expect(response).toHaveProperty('title', title); + }); test(`${permission} key: Update document from index that has NO primary key`, async () => { - const client = await getClient(permission) - const id = 456 - const title = 'The Little Prince' + const client = await getClient(permission); + const id = 456; + const title = 'The Little Prince'; const task = await client .index(indexNoPk.uid) - .updateDocuments([{ id, title }]) - await client.index(indexNoPk.uid).waitForTask(task.taskUid) - const response = await client.index(indexNoPk.uid).getDocument(id) + .updateDocuments([{ id, title }]); + await client.index(indexNoPk.uid).waitForTask(task.taskUid); + const response = await client.index(indexNoPk.uid).getDocument(id); - expect(response).toHaveProperty('id', id) - expect(response).toHaveProperty('title', title) - }) + expect(response).toHaveProperty('id', id); + expect(response).toHaveProperty('title', title); + }); test(`${permission} key: Update document from index that has a primary key`, async () => { - const client = await getClient(permission) - const id = 456 - const title = 'The Little Prince' + const client = await getClient(permission); + const id = 456; + const title = 'The Little Prince'; const task = await client .index(indexPk.uid) - .updateDocuments([{ id, title }]) - await client.index(indexPk.uid).waitForTask(task.taskUid) - const response = await client.index(indexPk.uid).getDocument(id) + .updateDocuments([{ id, title }]); + await client.index(indexPk.uid).waitForTask(task.taskUid); + const response = await client.index(indexPk.uid).getDocument(id); - expect(response).toHaveProperty('id', id) - expect(response).toHaveProperty('title', title) - }) + expect(response).toHaveProperty('id', id); + expect(response).toHaveProperty('title', title); + }); test(`${permission} key: Partial update of a document`, async () => { - const client = await getClient(permission) - const id = 456 + const client = await getClient(permission); + const id = 456; const task = await client .index(indexPk.uid) - .updateDocuments([{ id }]) - await client.index(indexPk.uid).waitForTask(task.taskUid) + .updateDocuments([{ id }]); + await client.index(indexPk.uid).waitForTask(task.taskUid); - const response = await client.index(indexPk.uid).getDocument(id) + const response = await client.index(indexPk.uid).getDocument(id); - expect(response).toHaveProperty('id', id) - expect(response).not.toHaveProperty('title') - }) + expect(response).toHaveProperty('id', id); + expect(response).not.toHaveProperty('title'); + }); test(`${permission} key: Update document from index that has a primary key in batch`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const tasks = await client .index(indexPk.uid) - .updateDocumentsInBatches(dataset, 2) + .updateDocumentsInBatches(dataset, 2); for (const EnqueuedTask of tasks) { const task = await client .index(indexPk.uid) - .waitForTask(EnqueuedTask.taskUid) - expect(task.status).toBe(TaskStatus.TASK_SUCCEEDED) - expect(task.type).toBe(TaskTypes.DOCUMENTS_ADDITION_OR_UPDATE) + .waitForTask(EnqueuedTask.taskUid); + expect(task.status).toBe(TaskStatus.TASK_SUCCEEDED); + expect(task.type).toBe(TaskTypes.DOCUMENTS_ADDITION_OR_UPDATE); } - expect(tasks).toHaveLength(4) - }) + expect(tasks).toHaveLength(4); + }); test(`${permission} key: Partial update of a document in batch`, async () => { - const client = await getClient(permission) - const partialDocument = { id: 1 } + const client = await getClient(permission); + const partialDocument = { id: 1 }; const tasks = await client .index(indexPk.uid) - .updateDocumentsInBatches([partialDocument], 2) + .updateDocumentsInBatches([partialDocument], 2); for (const EnqueuedTask of tasks) { const task = await client .index(indexPk.uid) - .waitForTask(EnqueuedTask.taskUid) + .waitForTask(EnqueuedTask.taskUid); - expect(task.status).toBe(TaskStatus.TASK_SUCCEEDED) - expect(task.type).toBe(TaskTypes.DOCUMENTS_ADDITION_OR_UPDATE) + expect(task.status).toBe(TaskStatus.TASK_SUCCEEDED); + expect(task.type).toBe(TaskTypes.DOCUMENTS_ADDITION_OR_UPDATE); } - expect(tasks).toHaveLength(1) - }) + expect(tasks).toHaveLength(1); + }); test(`${permission} key: Add document with update documents function from index that has NO primary key`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const { taskUid: addDocTask } = await client .index(indexNoPk.uid) - .addDocuments(dataset) - await client.index(indexNoPk.uid).waitForTask(addDocTask) - const id = 9 - const title = '1984' + .addDocuments(dataset); + await client.index(indexNoPk.uid).waitForTask(addDocTask); + const id = 9; + const title = '1984'; const task = await client .index(indexNoPk.uid) - .updateDocuments([{ id, title }]) - await client.index(indexNoPk.uid).waitForTask(task.taskUid) - const document = await client.index(indexNoPk.uid).getDocument(id) - const documents = await client.index(indexNoPk.uid).getDocuments() + .updateDocuments([{ id, title }]); + await client.index(indexNoPk.uid).waitForTask(task.taskUid); + const document = await client.index(indexNoPk.uid).getDocument(id); + const documents = await client + .index(indexNoPk.uid) + .getDocuments(); - expect(document).toHaveProperty('id', id) - expect(document).toHaveProperty('title', title) - expect(documents.results.length).toEqual(dataset.length + 1) - }) + expect(document).toHaveProperty('id', id); + expect(document).toHaveProperty('title', title); + expect(documents.results.length).toEqual(dataset.length + 1); + }); test(`${permission} key: Add document with update documents function from index that has a primary key`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const { taskUid: addDocTask } = await client .index(indexPk.uid) - .addDocuments(dataset) - await client.index(indexPk.uid).waitForTask(addDocTask) - const id = 9 - const title = '1984' + .addDocuments(dataset); + await client.index(indexPk.uid).waitForTask(addDocTask); + const id = 9; + const title = '1984'; const task = await client .index(indexPk.uid) - .updateDocuments([{ id, title }]) - await client.index(indexPk.uid).waitForTask(task.taskUid) + .updateDocuments([{ id, title }]); + await client.index(indexPk.uid).waitForTask(task.taskUid); - const document = await client.index(indexPk.uid).getDocument(id) - const documents = await client.index(indexPk.uid).getDocuments() + const document = await client.index(indexPk.uid).getDocument(id); + const documents = await client.index(indexPk.uid).getDocuments(); - expect(document).toHaveProperty('id', id) - expect(document).toHaveProperty('title', title) - expect(documents.results.length).toEqual(dataset.length + 1) - }) + expect(document).toHaveProperty('id', id); + expect(document).toHaveProperty('title', title); + expect(documents.results.length).toEqual(dataset.length + 1); + }); test(`${permission} key: Add document and infer correct "_id" primary key`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const doc = { title: 'hello', _id: 1, - } + }; const { taskUid: addDocTask } = await client .index(indexNoPk.uid) - .addDocuments([doc]) - await client.index(indexNoPk.uid).waitForTask(addDocTask) + .addDocuments([doc]); + await client.index(indexNoPk.uid).waitForTask(addDocTask); - const index = await client.index(indexNoPk.uid).fetchInfo() + const index = await client.index(indexNoPk.uid).fetchInfo(); - expect(index).toHaveProperty('primaryKey', '_id') - }) + expect(index).toHaveProperty('primaryKey', '_id'); + }); test(`${permission} key: Add document and infer correct "findmeid" primary key`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const doc = { title: 'hello', findmeid: 1, - } + }; const { taskUid: addDocTask } = await client .index(indexNoPk.uid) - .addDocuments([doc]) - await client.index(indexNoPk.uid).waitForTask(addDocTask) + .addDocuments([doc]); + await client.index(indexNoPk.uid).waitForTask(addDocTask); - const index = await client.index(indexNoPk.uid).fetchInfo() + const index = await client.index(indexNoPk.uid).fetchInfo(); - expect(index).toHaveProperty('primaryKey', 'findmeid') - }) + expect(index).toHaveProperty('primaryKey', 'findmeid'); + }); test(`${permission} key: Add document with two inferable primary key`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const doc = { title: 'hello', id: 1, _id: 1, - } + }; const { taskUid: addDocTask } = await client .index(indexNoPk.uid) - .addDocuments([doc]) - const task = await client.index(indexNoPk.uid).waitForTask(addDocTask) - const index = await client.index(indexNoPk.uid).fetchInfo() + .addDocuments([doc]); + const task = await client.index(indexNoPk.uid).waitForTask(addDocTask); + const index = await client.index(indexNoPk.uid).fetchInfo(); expect(task.error?.code).toEqual( - 'index_primary_key_multiple_candidates_found' - ) - expect(index).toHaveProperty('primaryKey', null) - }) + 'index_primary_key_multiple_candidates_found', + ); + expect(index).toHaveProperty('primaryKey', null); + }); test(`${permission} key: Add document with none inferable primary key`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const doc = { title: 'hello', idfindme: 1, - } + }; const { taskUid: addDocTask } = await client .index(indexNoPk.uid) - .addDocuments([doc]) - const task = await client.index(indexNoPk.uid).waitForTask(addDocTask) - const index = await client.index(indexNoPk.uid).fetchInfo() + .addDocuments([doc]); + const task = await client.index(indexNoPk.uid).waitForTask(addDocTask); + const index = await client.index(indexNoPk.uid).fetchInfo(); - expect(task.error?.code).toEqual('index_primary_key_no_candidate_found') - expect(index).toHaveProperty('primaryKey', null) - }) + expect(task.error?.code).toEqual( + 'index_primary_key_no_candidate_found', + ); + expect(index).toHaveProperty('primaryKey', null); + }); test(`${permission} key: Delete a document from index that has NO primary key`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const { taskUid: addDocTask } = await client .index(indexNoPk.uid) - .addDocuments(dataset) - await client.index(indexNoPk.uid).waitForTask(addDocTask) - const id = 9 + .addDocuments(dataset); + await client.index(indexNoPk.uid).waitForTask(addDocTask); + const id = 9; - const task = await client.index(indexNoPk.uid).deleteDocument(id) - await client.index(indexNoPk.uid).waitForTask(task.taskUid) - const documents = await client.index(indexNoPk.uid).getDocuments() + const task = await client.index(indexNoPk.uid).deleteDocument(id); + await client.index(indexNoPk.uid).waitForTask(task.taskUid); + const documents = await client + .index(indexNoPk.uid) + .getDocuments(); - expect(documents.results.length).toEqual(dataset.length) - }) + expect(documents.results.length).toEqual(dataset.length); + }); test(`${permission} key: Delete a document from index that has a primary key`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const { taskUid: addDocTask } = await client .index(indexPk.uid) - .addDocuments(dataset) - await client.index(indexPk.uid).waitForTask(addDocTask) + .addDocuments(dataset); + await client.index(indexPk.uid).waitForTask(addDocTask); - const id = 9 - const task = await client.index(indexPk.uid).deleteDocument(id) - await client.index(indexPk.uid).waitForTask(task.taskUid) - const response = await client.index(indexPk.uid).getDocuments() + const id = 9; + const task = await client.index(indexPk.uid).deleteDocument(id); + await client.index(indexPk.uid).waitForTask(task.taskUid); + const response = await client.index(indexPk.uid).getDocuments(); - expect(response.results.length).toEqual(dataset.length) - }) + expect(response.results.length).toEqual(dataset.length); + }); test(`${permission} key: Delete some documents with string filters`, async () => { - const client = await getClient(permission) - await client.index(indexPk.uid).updateFilterableAttributes(['id']) + const client = await getClient(permission); + await client.index(indexPk.uid).updateFilterableAttributes(['id']); const { taskUid: addDocTask } = await client .index(indexPk.uid) - .addDocuments(dataset) - await client.index(indexPk.uid).waitForTask(addDocTask) + .addDocuments(dataset); + await client.index(indexPk.uid).waitForTask(addDocTask); const task = await client .index(indexPk.uid) - .deleteDocuments({ filter: 'id IN [1, 2]' }) + .deleteDocuments({ filter: 'id IN [1, 2]' }); const resolvedTask = await client .index(indexPk.uid) - .waitForTask(task.taskUid) - const documents = await client.index(indexPk.uid).getDocuments() + .waitForTask(task.taskUid); + const documents = await client.index(indexPk.uid).getDocuments(); - expect(resolvedTask.details.deletedDocuments).toEqual(2) - expect(documents.results.length).toEqual(dataset.length - 2) - }) + expect(resolvedTask.details.deletedDocuments).toEqual(2); + expect(documents.results.length).toEqual(dataset.length - 2); + }); test(`${permission} key: Delete some documents with array filters`, async () => { - const client = await getClient(permission) - await client.index(indexPk.uid).updateFilterableAttributes(['id']) + const client = await getClient(permission); + await client.index(indexPk.uid).updateFilterableAttributes(['id']); const { taskUid: addDocTask } = await client .index(indexPk.uid) - .addDocuments(dataset) - await client.index(indexPk.uid).waitForTask(addDocTask) + .addDocuments(dataset); + await client.index(indexPk.uid).waitForTask(addDocTask); const task = await client .index(indexPk.uid) - .deleteDocuments({ filter: [['id = 1', 'id = 2']] }) + .deleteDocuments({ filter: [['id = 1', 'id = 2']] }); const resolvedTask = await client .index(indexPk.uid) - .waitForTask(task.taskUid) - const documents = await client.index(indexPk.uid).getDocuments() + .waitForTask(task.taskUid); + const documents = await client.index(indexPk.uid).getDocuments(); - expect(resolvedTask.details.deletedDocuments).toEqual(2) - expect(documents.results.length).toEqual(dataset.length - 2) - }) + expect(resolvedTask.details.deletedDocuments).toEqual(2); + expect(documents.results.length).toEqual(dataset.length - 2); + }); test(`${permission} key: Delete some documents from index that has NO primary key`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const { taskUid: addDocTask } = await client .index(indexNoPk.uid) - .addDocuments(dataset) - await client.index(indexNoPk.uid).waitForTask(addDocTask) + .addDocuments(dataset); + await client.index(indexNoPk.uid).waitForTask(addDocTask); - const ids = [1, 2] - const task = await client.index(indexNoPk.uid).deleteDocuments(ids) + const ids = [1, 2]; + const task = await client.index(indexNoPk.uid).deleteDocuments(ids); const resolvedTask = await client .index(indexNoPk.uid) - .waitForTask(task.taskUid) + .waitForTask(task.taskUid); - const documents = await client.index(indexNoPk.uid).getDocuments() - const returnedIds = documents.results.map((x) => x.id) + const documents = await client + .index(indexNoPk.uid) + .getDocuments(); + const returnedIds = documents.results.map((x) => x.id); - expect(resolvedTask.details.deletedDocuments).toEqual(2) - expect(resolvedTask.details.providedIds).toEqual(2) - expect(documents.results.length).toEqual(dataset.length - 2) - expect(returnedIds).not.toContain(ids[0]) - expect(returnedIds).not.toContain(ids[1]) - }) + expect(resolvedTask.details.deletedDocuments).toEqual(2); + expect(resolvedTask.details.providedIds).toEqual(2); + expect(documents.results.length).toEqual(dataset.length - 2); + expect(returnedIds).not.toContain(ids[0]); + expect(returnedIds).not.toContain(ids[1]); + }); test(`${permission} key: Delete some documents from index that has a primary key`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const { taskUid: addDocTask } = await client .index(indexPk.uid) - .addDocuments(dataset) - await client.index(indexPk.uid).waitForTask(addDocTask) + .addDocuments(dataset); + await client.index(indexPk.uid).waitForTask(addDocTask); - const ids = [1, 2] - const task = await client.index(indexPk.uid).deleteDocuments(ids) - await client.index(indexPk.uid).waitForTask(task.taskUid) - const documents = await client.index(indexPk.uid).getDocuments() - const returnedIds = documents.results.map((x) => x.id) + const ids = [1, 2]; + const task = await client.index(indexPk.uid).deleteDocuments(ids); + await client.index(indexPk.uid).waitForTask(task.taskUid); + const documents = await client.index(indexPk.uid).getDocuments(); + const returnedIds = documents.results.map((x) => x.id); - expect(documents.results.length).toEqual(dataset.length - 2) - expect(returnedIds).not.toContain(ids[0]) - expect(returnedIds).not.toContain(ids[1]) - }) + expect(documents.results.length).toEqual(dataset.length - 2); + expect(returnedIds).not.toContain(ids[0]); + expect(returnedIds).not.toContain(ids[1]); + }); test(`${permission} key: Delete some documents should trigger error with a hint on a MeilisearchApiError`, async () => { - const client = await getClient(permission) - const task = await client.createIndex(indexPk.uid) - await client.waitForTask(task.taskUid) + const client = await getClient(permission); + const task = await client.createIndex(indexPk.uid); + await client.waitForTask(task.taskUid); try { - await client.index(indexPk.uid).deleteDocuments({ filter: '' }) + await client.index(indexPk.uid).deleteDocuments({ filter: '' }); fail( - 'deleteDocuments should have raised an error when the parameters are wrong' - ) + 'deleteDocuments should have raised an error when the parameters are wrong', + ); } catch (e: any) { expect(e.message).toEqual( - "Sending an empty filter is forbidden.\nHint: It might not be working because maybe you're not up to date with the Meilisearch version that deleteDocuments call requires." - ) + "Sending an empty filter is forbidden.\nHint: It might not be working because maybe you're not up to date with the Meilisearch version that deleteDocuments call requires.", + ); } - }) + }); test(`${permission} key: Delete some documents should trigger error with a hint on a MeilisearchRequestError`, async () => { - const apiKey = await getKey(permission) - const client = new MeiliSearch({ host: `${HOST}/indexes`, apiKey }) + const apiKey = await getKey(permission); + const client = new MeiliSearch({ host: `${HOST}/indexes`, apiKey }); try { - await client.index(indexPk.uid).deleteDocuments({ filter: 'id = 1' }) + await client.index(indexPk.uid).deleteDocuments({ filter: 'id = 1' }); fail( - 'deleteDocuments should have raised an error when the route does not exist' - ) + 'deleteDocuments should have raised an error when the route does not exist', + ); } catch (e: any) { expect(e.message).toEqual( - "404: Not Found\nHint: It might not be working because maybe you're not up to date with the Meilisearch version that deleteDocuments call requires." - ) + "404: Not Found\nHint: It might not be working because maybe you're not up to date with the Meilisearch version that deleteDocuments call requires.", + ); } - }) + }); test(`${permission} key: Delete all document from index that has NO primary key`, async () => { - const client = await getClient(permission) - const task = await client.index(indexNoPk.uid).deleteAllDocuments() - await client.index(indexNoPk.uid).waitForTask(task.taskUid) + const client = await getClient(permission); + const task = await client.index(indexNoPk.uid).deleteAllDocuments(); + await client.index(indexNoPk.uid).waitForTask(task.taskUid); - const documents = await client.index(indexNoPk.uid).getDocuments() - expect(documents.results.length).toEqual(0) - }) + const documents = await client + .index(indexNoPk.uid) + .getDocuments(); + expect(documents.results.length).toEqual(0); + }); test(`${permission} key: Delete all document from index that has a primary key`, async () => { - const client = await getClient(permission) - const task = await client.index(indexPk.uid).deleteAllDocuments() - await client.index(indexPk.uid).waitForTask(task.taskUid) + const client = await getClient(permission); + const task = await client.index(indexPk.uid).deleteAllDocuments(); + await client.index(indexPk.uid).waitForTask(task.taskUid); - const documents = await client.index(indexPk.uid).getDocuments() - expect(documents.results.length).toEqual(0) - }) + const documents = await client.index(indexPk.uid).getDocuments(); + expect(documents.results.length).toEqual(0); + }); test(`${permission} key: Try to get deleted document from index that has NO primary key`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect( - client.index(indexNoPk.uid).getDocument(1) + client.index(indexNoPk.uid).getDocument(1), ).rejects.toHaveProperty( 'cause.code', - ErrorStatusCode.DOCUMENT_NOT_FOUND - ) - }) + ErrorStatusCode.DOCUMENT_NOT_FOUND, + ); + }); test(`${permission} key: Try to get deleted document from index that has a primary key`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect( - client.index(indexPk.uid).getDocument(1) + client.index(indexPk.uid).getDocument(1), ).rejects.toHaveProperty( 'cause.code', - ErrorStatusCode.DOCUMENT_NOT_FOUND - ) - }) + ErrorStatusCode.DOCUMENT_NOT_FOUND, + ); + }); test(`${permission} key: Add documents from index with no primary key by giving a primary key as parameter`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const docs = [ { id: 1, unique: 2, title: 'Le Rouge et le Noir', }, - ] - const pkIndex = 'update_pk' - const { taskUid } = await client.createIndex(pkIndex) - await client.waitForTask(taskUid) + ]; + const pkIndex = 'update_pk'; + const { taskUid } = await client.createIndex(pkIndex); + await client.waitForTask(taskUid); const task = await client .index(pkIndex) - .addDocuments(docs, { primaryKey: 'unique' }) - await client.waitForTask(task.taskUid) + .addDocuments(docs, { primaryKey: 'unique' }); + await client.waitForTask(task.taskUid); - const response = await client.index(pkIndex).getRawInfo() - expect(response).toHaveProperty('uid', pkIndex) - expect(response).toHaveProperty('primaryKey', 'unique') - }) + const response = await client.index(pkIndex).getRawInfo(); + expect(response).toHaveProperty('uid', pkIndex); + expect(response).toHaveProperty('primaryKey', 'unique'); + }); test(`${permission} key: Add a document without a primary key and check response in task status`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const docs = [ { title: 'Le Rouge et le Noir', }, - ] + ]; - const { taskUid } = await client.index(indexNoPk.uid).addDocuments(docs) - const { error } = await client.waitForTask(taskUid) + const { taskUid } = await client + .index(indexNoPk.uid) + .addDocuments(docs); + const { error } = await client.waitForTask(taskUid); - expect(error).toHaveProperty('code') - expect(error).toHaveProperty('link') - expect(error).toHaveProperty('message') - expect(error).toHaveProperty('type') - }) + expect(error).toHaveProperty('code'); + expect(error).toHaveProperty('link'); + expect(error).toHaveProperty('message'); + expect(error).toHaveProperty('type'); + }); test(`${permission} key: Try to add documents from index with no primary key with NO valid primary key, task should fail`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const { taskUid } = await client.index(indexNoPk.uid).addDocuments([ { unique: 2, title: 'Le Rouge et le Noir', }, - ]) + ]); - const task = await client.waitForTask(taskUid) - const index = await client.index(indexNoPk.uid).getRawInfo() + const task = await client.waitForTask(taskUid); + const index = await client.index(indexNoPk.uid).getRawInfo(); - expect(index.uid).toEqual(indexNoPk.uid) - expect(index.primaryKey).toEqual(null) - expect(task.status).toEqual('failed') - }) - } - ) + expect(index.uid).toEqual(indexNoPk.uid); + expect(index.primaryKey).toEqual(null); + expect(task.status).toEqual('failed'); + }); + }, + ); describe.each([{ permission: 'Search' }])( 'Test on documents', ({ permission }) => { beforeEach(() => { - return clearAllIndexes(config) - }) + return clearAllIndexes(config); + }); test(`${permission} key: Try to add documents and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect( - client.index(indexPk.uid).addDocuments([]) - ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY) - }) + client.index(indexPk.uid).addDocuments([]), + ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY); + }); test(`${permission} key: Try to update documents and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect( - client.index(indexPk.uid).updateDocuments([]) - ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY) - }) + client.index(indexPk.uid).updateDocuments([]), + ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY); + }); test(`${permission} key: Try to get documents and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect( - client.index(indexPk.uid).getDocuments() - ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY) - }) + client.index(indexPk.uid).getDocuments(), + ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY); + }); test(`${permission} key: Try to delete one document and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect( - client.index(indexPk.uid).deleteDocument(1) - ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY) - }) + client.index(indexPk.uid).deleteDocument(1), + ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY); + }); test(`${permission} key: Try to delete some documents and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect( - client.index(indexPk.uid).deleteDocuments([1, 2]) - ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY) - }) + client.index(indexPk.uid).deleteDocuments([1, 2]), + ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY); + }); test(`${permission} key: Try to delete all documents and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect( - client.index(indexPk.uid).deleteAllDocuments() - ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY) - }) - } - ) + client.index(indexPk.uid).deleteAllDocuments(), + ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY); + }); + }, + ); describe.each([{ permission: 'No' }])( 'Test on documents', ({ permission }) => { beforeEach(() => { - return clearAllIndexes(config) - }) + return clearAllIndexes(config); + }); test(`${permission} key: Try to add documents and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect( - client.index(indexPk.uid).addDocuments([]) + client.index(indexPk.uid).addDocuments([]), ).rejects.toHaveProperty( 'cause.code', - ErrorStatusCode.MISSING_AUTHORIZATION_HEADER - ) - }) + ErrorStatusCode.MISSING_AUTHORIZATION_HEADER, + ); + }); test(`${permission} key: Try to update documents and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect( - client.index(indexPk.uid).updateDocuments([]) + client.index(indexPk.uid).updateDocuments([]), ).rejects.toHaveProperty( 'cause.code', - ErrorStatusCode.MISSING_AUTHORIZATION_HEADER - ) - }) + ErrorStatusCode.MISSING_AUTHORIZATION_HEADER, + ); + }); test(`${permission} key: Try to get documents and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect( - client.index(indexPk.uid).getDocuments() + client.index(indexPk.uid).getDocuments(), ).rejects.toHaveProperty( 'cause.code', - ErrorStatusCode.MISSING_AUTHORIZATION_HEADER - ) - }) + ErrorStatusCode.MISSING_AUTHORIZATION_HEADER, + ); + }); test(`${permission} key: Try to delete one document and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect( - client.index(indexPk.uid).deleteDocument(1) + client.index(indexPk.uid).deleteDocument(1), ).rejects.toHaveProperty( 'cause.code', - ErrorStatusCode.MISSING_AUTHORIZATION_HEADER - ) - }) + ErrorStatusCode.MISSING_AUTHORIZATION_HEADER, + ); + }); test(`${permission} key: Try to delete some documents and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect( - client.index(indexPk.uid).deleteDocuments([1, 2]) + client.index(indexPk.uid).deleteDocuments([1, 2]), ).rejects.toHaveProperty( 'cause.code', - ErrorStatusCode.MISSING_AUTHORIZATION_HEADER - ) - }) + ErrorStatusCode.MISSING_AUTHORIZATION_HEADER, + ); + }); test(`${permission} key: Try to delete all documents and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect( - client.index(indexPk.uid).deleteAllDocuments() + client.index(indexPk.uid).deleteAllDocuments(), ).rejects.toHaveProperty( 'cause.code', - ErrorStatusCode.MISSING_AUTHORIZATION_HEADER - ) - }) - } - ) + ErrorStatusCode.MISSING_AUTHORIZATION_HEADER, + ); + }); + }, + ); describe.each([ { host: BAD_HOST, trailing: false }, @@ -811,87 +823,87 @@ Hint: It might not be working because maybe you're not up to date with the Meili { host: `${BAD_HOST}/trailing/`, trailing: true }, ])('Tests on url construction', ({ host, trailing }) => { test(`Test getDocument route`, async () => { - const route = `indexes/${indexPk.uid}/documents/1` - const client = new MeiliSearch({ host }) - const strippedHost = trailing ? host.slice(0, -1) : host + const route = `indexes/${indexPk.uid}/documents/1`; + const client = new MeiliSearch({ host }); + const strippedHost = trailing ? host.slice(0, -1) : host; await expect( - client.index(indexPk.uid).getDocument(1) + client.index(indexPk.uid).getDocument(1), ).rejects.toHaveProperty( 'message', - `Request to ${strippedHost}/${route} has failed` - ) - }) + `Request to ${strippedHost}/${route} has failed`, + ); + }); test(`Test getDocuments route`, async () => { - const route = `indexes/${indexPk.uid}/documents` - const client = new MeiliSearch({ host }) - const strippedHost = trailing ? host.slice(0, -1) : host + const route = `indexes/${indexPk.uid}/documents`; + const client = new MeiliSearch({ host }); + const strippedHost = trailing ? host.slice(0, -1) : host; await expect( - client.index(indexPk.uid).getDocuments() + client.index(indexPk.uid).getDocuments(), ).rejects.toHaveProperty( 'message', - `Request to ${strippedHost}/${route} has failed` - ) - }) + `Request to ${strippedHost}/${route} has failed`, + ); + }); test(`Test addDocuments route`, async () => { - const route = `indexes/${indexPk.uid}/documents` - const client = new MeiliSearch({ host }) - const strippedHost = trailing ? host.slice(0, -1) : host + const route = `indexes/${indexPk.uid}/documents`; + const client = new MeiliSearch({ host }); + const strippedHost = trailing ? host.slice(0, -1) : host; await expect( - client.index(indexPk.uid).addDocuments([]) + client.index(indexPk.uid).addDocuments([]), ).rejects.toHaveProperty( 'message', - `Request to ${strippedHost}/${route} has failed` - ) - }) + `Request to ${strippedHost}/${route} has failed`, + ); + }); test(`Test updateDocuments route`, async () => { - const route = `indexes/${indexPk.uid}/documents` - const client = new MeiliSearch({ host }) - const strippedHost = trailing ? host.slice(0, -1) : host + const route = `indexes/${indexPk.uid}/documents`; + const client = new MeiliSearch({ host }); + const strippedHost = trailing ? host.slice(0, -1) : host; await expect( - client.index(indexPk.uid).updateDocuments([]) + client.index(indexPk.uid).updateDocuments([]), ).rejects.toHaveProperty( 'message', - `Request to ${strippedHost}/${route} has failed` - ) - }) + `Request to ${strippedHost}/${route} has failed`, + ); + }); test(`Test deleteDocument route`, async () => { - const route = `indexes/${indexPk.uid}/documents/1` - const client = new MeiliSearch({ host }) - const strippedHost = trailing ? host.slice(0, -1) : host + const route = `indexes/${indexPk.uid}/documents/1`; + const client = new MeiliSearch({ host }); + const strippedHost = trailing ? host.slice(0, -1) : host; await expect( - client.index(indexPk.uid).deleteDocument('1') + client.index(indexPk.uid).deleteDocument('1'), ).rejects.toHaveProperty( 'message', - `Request to ${strippedHost}/${route} has failed` - ) - }) + `Request to ${strippedHost}/${route} has failed`, + ); + }); test(`Test deleteDocuments route`, async () => { - const route = `indexes/${indexPk.uid}/documents/delete-batch` - const client = new MeiliSearch({ host }) - const strippedHost = trailing ? host.slice(0, -1) : host + const route = `indexes/${indexPk.uid}/documents/delete-batch`; + const client = new MeiliSearch({ host }); + const strippedHost = trailing ? host.slice(0, -1) : host; await expect( - client.index(indexPk.uid).deleteDocuments([]) + client.index(indexPk.uid).deleteDocuments([]), ).rejects.toHaveProperty( 'message', - `Request to ${strippedHost}/${route} has failed` - ) - }) + `Request to ${strippedHost}/${route} has failed`, + ); + }); test(`Test deleteAllDocuments route`, async () => { - const route = `indexes/${indexPk.uid}/documents` - const client = new MeiliSearch({ host }) - const strippedHost = trailing ? host.slice(0, -1) : host + const route = `indexes/${indexPk.uid}/documents`; + const client = new MeiliSearch({ host }); + const strippedHost = trailing ? host.slice(0, -1) : host; await expect( - client.index(indexPk.uid).deleteAllDocuments() + client.index(indexPk.uid).deleteAllDocuments(), ).rejects.toHaveProperty( 'message', - `Request to ${strippedHost}/${route} has failed` - ) - }) - }) -}) + `Request to ${strippedHost}/${route} has failed`, + ); + }); + }); +}); diff --git a/tests/dump.test.ts b/tests/dump.test.ts index 7cae4610d..f23872aef 100644 --- a/tests/dump.test.ts +++ b/tests/dump.test.ts @@ -1,53 +1,53 @@ -import { ErrorStatusCode } from '../src/types' +import { ErrorStatusCode } from '../src/types'; import { clearAllIndexes, config, MeiliSearch, BAD_HOST, getClient, -} from './utils/meilisearch-test-utils' +} from './utils/meilisearch-test-utils'; beforeEach(async () => { - await clearAllIndexes(config) -}) + await clearAllIndexes(config); +}); describe.each([{ permission: 'Master' }, { permission: 'Admin' }])( 'Test on dump', ({ permission }) => { test(`${permission} key: create a new dump`, async () => { - const client = await getClient(permission) - const { taskUid } = await client.createDump() + const client = await getClient(permission); + const { taskUid } = await client.createDump(); - await client.waitForTask(taskUid) - }) - } -) + await client.waitForTask(taskUid); + }); + }, +); describe.each([{ permission: 'Search' }])( 'Test on dump with search api key should not have access', ({ permission }) => { test(`${permission} key: try to create dump with search key and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect(client.createDump()).rejects.toHaveProperty( 'cause.code', - ErrorStatusCode.INVALID_API_KEY - ) - }) - } -) + ErrorStatusCode.INVALID_API_KEY, + ); + }); + }, +); describe.each([{ permission: 'No' }])( 'Test on dump without api key should not have access', ({ permission }) => { test(`${permission} key: try to create dump with no key and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect(client.createDump()).rejects.toHaveProperty( 'cause.code', - ErrorStatusCode.MISSING_AUTHORIZATION_HEADER - ) - }) - } -) + ErrorStatusCode.MISSING_AUTHORIZATION_HEADER, + ); + }); + }, +); describe.each([ { host: BAD_HOST, trailing: false }, @@ -55,13 +55,13 @@ describe.each([ { host: `${BAD_HOST}/trailing/`, trailing: true }, ])('Tests on url construction', ({ host, trailing }) => { test(`Test createDump route`, async () => { - const route = `dumps` - const client = new MeiliSearch({ host }) - const strippedHost = trailing ? host.slice(0, -1) : host + const route = `dumps`; + const client = new MeiliSearch({ host }); + const strippedHost = trailing ? host.slice(0, -1) : host; await expect(client.createDump()).rejects.toHaveProperty( 'message', - `Request to ${strippedHost}/${route} has failed` - ) - }) -}) + `Request to ${strippedHost}/${route} has failed`, + ); + }); +}); diff --git a/tests/embedders.test.ts b/tests/embedders.test.ts index e4341538f..450641d5a 100644 --- a/tests/embedders.test.ts +++ b/tests/embedders.test.ts @@ -1,5 +1,5 @@ -import { EnqueuedTask } from '../src/enqueued-task' -import { Embedders } from '../src/types' +import { EnqueuedTask } from '../src/enqueued-task'; +import { Embedders } from '../src/types'; import { clearAllIndexes, config, @@ -8,25 +8,25 @@ import { MeiliSearch, getClient, getKey, -} from './utils/meilisearch-test-utils' +} from './utils/meilisearch-test-utils'; const index = { uid: 'movies_test', -} +}; -jest.setTimeout(100 * 1000) +jest.setTimeout(100 * 1000); afterAll(() => { - return clearAllIndexes(config) -}) + return clearAllIndexes(config); +}); describe.each([{ permission: 'Master' }, { permission: 'Admin' }])( 'Test on embedders', ({ permission }) => { beforeEach(async () => { - await clearAllIndexes(config) - const client = await getClient(permission) - const key = await getKey(permission) + await clearAllIndexes(config); + const client = await getClient(permission); + const key = await getKey(permission); await fetch(`${HOST}/experimental-features`, { body: JSON.stringify({ vectorStore: true }), @@ -35,21 +35,21 @@ describe.each([{ permission: 'Master' }, { permission: 'Admin' }])( 'Content-Type': 'application/json', }, method: 'PATCH', - }) + }); - const task = await client.createIndex(index.uid) - await client.waitForTask(task.taskUid) - }) + const task = await client.createIndex(index.uid); + await client.waitForTask(task.taskUid); + }); test(`${permission} key: Get default embedders`, async () => { - const client = await getClient(permission) - const response: Embedders = await client.index(index.uid).getEmbedders() + const client = await getClient(permission); + const response: Embedders = await client.index(index.uid).getEmbedders(); - expect(response).toEqual(null) - }) + expect(response).toEqual(null); + }); test(`${permission} key: Update embedders with 'userProvided' source`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const newEmbedder: Embedders = { default: { source: 'userProvided', @@ -59,20 +59,20 @@ describe.each([{ permission: 'Master' }, { permission: 'Admin' }])( sigma: 0.3, }, }, - } + }; const task: EnqueuedTask = await client .index(index.uid) - .updateEmbedders(newEmbedder) + .updateEmbedders(newEmbedder); - await client.waitForTask(task.taskUid) + await client.waitForTask(task.taskUid); - const response: Embedders = await client.index(index.uid).getEmbedders() + const response: Embedders = await client.index(index.uid).getEmbedders(); - expect(response).toEqual(newEmbedder) - }) + expect(response).toEqual(newEmbedder); + }); test(`${permission} key: Update embedders with 'openAi' source`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const newEmbedder: Embedders = { default: { source: 'openAi', @@ -86,24 +86,24 @@ describe.each([{ permission: 'Master' }, { permission: 'Admin' }])( sigma: 0.3, }, }, - } + }; const task: EnqueuedTask = await client .index(index.uid) - .updateEmbedders(newEmbedder) - await client.waitForTask(task.taskUid) + .updateEmbedders(newEmbedder); + await client.waitForTask(task.taskUid); - const response: Embedders = await client.index(index.uid).getEmbedders() + const response: Embedders = await client.index(index.uid).getEmbedders(); expect(response).toEqual({ default: { ...newEmbedder.default, apiKey: ' { - const client = await getClient(permission) + const client = await getClient(permission); const newEmbedder: Embedders = { default: { source: 'huggingFace', @@ -115,19 +115,19 @@ describe.each([{ permission: 'Master' }, { permission: 'Admin' }])( sigma: 0.3, }, }, - } + }; const task: EnqueuedTask = await client .index(index.uid) - .updateEmbedders(newEmbedder) - await client.waitForTask(task.taskUid, { timeOutMs: 60_000 }) + .updateEmbedders(newEmbedder); + await client.waitForTask(task.taskUid, { timeOutMs: 60_000 }); - const response: Embedders = await client.index(index.uid).getEmbedders() + const response: Embedders = await client.index(index.uid).getEmbedders(); - expect(response).toEqual(newEmbedder) - }) + expect(response).toEqual(newEmbedder); + }); test(`${permission} key: Update embedders with 'rest' source`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const newEmbedder: Embedders = { default: { source: 'rest', @@ -148,24 +148,24 @@ describe.each([{ permission: 'Master' }, { permission: 'Admin' }])( sigma: 0.3, }, }, - } + }; const task: EnqueuedTask = await client .index(index.uid) - .updateEmbedders(newEmbedder) - await client.waitForTask(task.taskUid) + .updateEmbedders(newEmbedder); + await client.waitForTask(task.taskUid); - const response: Embedders = await client.index(index.uid).getEmbedders() + const response: Embedders = await client.index(index.uid).getEmbedders(); expect(response).toEqual({ default: { ...newEmbedder.default, apiKey: ' { - const client = await getClient(permission) + const client = await getClient(permission); const newEmbedder: Embedders = { default: { source: 'ollama', @@ -178,53 +178,53 @@ describe.each([{ permission: 'Master' }, { permission: 'Admin' }])( sigma: 0.3, }, }, - } + }; const task: EnqueuedTask = await client .index(index.uid) - .updateEmbedders(newEmbedder) - await client.waitForTask(task.taskUid) + .updateEmbedders(newEmbedder); + await client.waitForTask(task.taskUid); - const response: Embedders = await client.index(index.uid).getEmbedders() + const response: Embedders = await client.index(index.uid).getEmbedders(); expect(response).toEqual({ default: { ...newEmbedder.default, apiKey: ' { - const client = await getClient(permission) + const client = await getClient(permission); const newEmbedder: Embedders = { image: { source: 'userProvided', dimensions: 512, }, - } + }; const task: EnqueuedTask = await client .index(index.uid) - .updateEmbedders(newEmbedder) + .updateEmbedders(newEmbedder); - await client.waitForTask(task.taskUid) + await client.waitForTask(task.taskUid); - const response: Embedders = await client.index(index.uid).getEmbedders() + const response: Embedders = await client.index(index.uid).getEmbedders(); - expect(response).toEqual(newEmbedder) - }) + expect(response).toEqual(newEmbedder); + }); test(`${permission} key: Reset embedders`, async () => { - const client = await getClient(permission) - const task: EnqueuedTask = await client.index(index.uid).resetEmbedders() - await client.waitForTask(task.taskUid) + const client = await getClient(permission); + const task: EnqueuedTask = await client.index(index.uid).resetEmbedders(); + await client.waitForTask(task.taskUid); - const response: Embedders = await client.index(index.uid).getEmbedders() + const response: Embedders = await client.index(index.uid).getEmbedders(); - expect(response).toEqual(null) - }) - } -) + expect(response).toEqual(null); + }); + }, +); describe.each([ { host: BAD_HOST, trailing: false }, @@ -232,36 +232,36 @@ describe.each([ { host: `${BAD_HOST}/trailing/`, trailing: true }, ])('Tests on url construction', ({ host, trailing }) => { test(`Test getEmbedders route`, async () => { - const route = `indexes/${index.uid}/settings/embedders` - const client = new MeiliSearch({ host }) - const strippedHost = trailing ? host.slice(0, -1) : host + const route = `indexes/${index.uid}/settings/embedders`; + const client = new MeiliSearch({ host }); + const strippedHost = trailing ? host.slice(0, -1) : host; await expect(client.index(index.uid).getEmbedders()).rejects.toHaveProperty( 'message', - `Request to ${strippedHost}/${route} has failed` - ) - }) + `Request to ${strippedHost}/${route} has failed`, + ); + }); test(`Test updateEmbedders route`, async () => { - const route = `indexes/${index.uid}/settings/embedders` - const client = new MeiliSearch({ host }) - const strippedHost = trailing ? host.slice(0, -1) : host + const route = `indexes/${index.uid}/settings/embedders`; + const client = new MeiliSearch({ host }); + const strippedHost = trailing ? host.slice(0, -1) : host; await expect( - client.index(index.uid).updateEmbedders({}) + client.index(index.uid).updateEmbedders({}), ).rejects.toHaveProperty( 'message', - `Request to ${strippedHost}/${route} has failed` - ) - }) + `Request to ${strippedHost}/${route} has failed`, + ); + }); test(`Test resetEmbedders route`, async () => { - const route = `indexes/${index.uid}/settings/embedders` - const client = new MeiliSearch({ host }) - const strippedHost = trailing ? host.slice(0, -1) : host + const route = `indexes/${index.uid}/settings/embedders`; + const client = new MeiliSearch({ host }); + const strippedHost = trailing ? host.slice(0, -1) : host; await expect( - client.index(index.uid).resetEmbedders() + client.index(index.uid).resetEmbedders(), ).rejects.toHaveProperty( 'message', - `Request to ${strippedHost}/${route} has failed` - ) - }) -}) + `Request to ${strippedHost}/${route} has failed`, + ); + }); +}); diff --git a/tests/errors.test.ts b/tests/errors.test.ts index f461bb870..4b6541f88 100644 --- a/tests/errors.test.ts +++ b/tests/errors.test.ts @@ -1,32 +1,32 @@ -import { MeiliSearch } from './utils/meilisearch-test-utils' +import { MeiliSearch } from './utils/meilisearch-test-utils'; import { MeiliSearchError, MeiliSearchApiError, MeiliSearchRequestError, MeiliSearchTimeOutError, -} from '../src/errors' -import 'jest-fetch-mock' -import fetchMock from 'jest-fetch-mock' +} from '../src/errors'; +import 'jest-fetch-mock'; +import fetchMock from 'jest-fetch-mock'; -fetchMock.enableMocks() +fetchMock.enableMocks(); -jest.setTimeout(100 * 1000) +jest.setTimeout(100 * 1000); // @TODO: Have to review this in more detail describe('Test on updates', () => { beforeEach(() => { - fetchMock.mockReset() - }) + fetchMock.mockReset(); + }); test(`Throw MeilisearchRequestError when throwned error is not MeiliSearchApiError`, async () => { - fetchMock.mockReject(new Error('fake error message')) - const client = new MeiliSearch({ host: 'http://localhost:9345' }) + fetchMock.mockReject(new Error('fake error message')); + const client = new MeiliSearch({ host: 'http://localhost:9345' }); try { - await client.health() + await client.health(); } catch (e: any) { - expect(e.name).toEqual('MeiliSearchRequestError') + expect(e.name).toEqual('MeiliSearchRequestError'); } - }) + }); test('MeiliSearchApiError can be compared with the instanceof operator', () => { expect( @@ -35,33 +35,33 @@ describe('Test on updates', () => { code: 'some_error', type: 'random_error', link: 'a link', - }) instanceof MeiliSearchApiError - ).toEqual(true) - }) + }) instanceof MeiliSearchApiError, + ).toEqual(true); + }); test('MeilisearchRequestError can be compared with the instanceof operator', async () => { - fetchMock.mockReject(new Error('fake error message')) - const client = new MeiliSearch({ host: 'http://localhost:9345' }) + fetchMock.mockReject(new Error('fake error message')); + const client = new MeiliSearch({ host: 'http://localhost:9345' }); try { - await client.health() + await client.health(); } catch (e: any) { - expect(e instanceof MeiliSearchRequestError).toEqual(true) + expect(e instanceof MeiliSearchRequestError).toEqual(true); } - }) + }); test('MeiliSearchError can be compared with the instanceof operator', () => { try { - throw new MeiliSearchError('message') + throw new MeiliSearchError('message'); } catch (e: any) { - expect(e instanceof MeiliSearchError).toEqual(true) + expect(e instanceof MeiliSearchError).toEqual(true); } - }) + }); test('MeiliSearchTimeOutError can be compared with the instanceof operator', () => { try { - throw new MeiliSearchTimeOutError('message') + throw new MeiliSearchTimeOutError('message'); } catch (e: any) { - expect(e instanceof MeiliSearchTimeOutError).toEqual(true) + expect(e instanceof MeiliSearchTimeOutError).toEqual(true); } - }) -}) + }); +}); diff --git a/tests/facet_search.test.ts b/tests/facet_search.test.ts index 5d62a6f3a..027dbde7f 100644 --- a/tests/facet_search.test.ts +++ b/tests/facet_search.test.ts @@ -2,11 +2,11 @@ import { clearAllIndexes, config, getClient, -} from './utils/meilisearch-test-utils' +} from './utils/meilisearch-test-utils'; const index = { uid: 'movies_test', -} +}; const dataset = [ { @@ -29,7 +29,7 @@ const dataset = [ title: 'Alice In Wonderland', genres: ['adventure'], }, -] +]; describe.each([ { permission: 'Master' }, @@ -37,71 +37,71 @@ describe.each([ { permission: 'Search' }, ])('Test on POST search', ({ permission }) => { beforeAll(async () => { - await clearAllIndexes(config) - const client = await getClient('Master') - const newFilterableAttributes = ['genres', 'title'] - await client.createIndex(index.uid) + await clearAllIndexes(config); + const client = await getClient('Master'); + const newFilterableAttributes = ['genres', 'title']; + await client.createIndex(index.uid); await client.index(index.uid).updateSettings({ filterableAttributes: newFilterableAttributes, - }) - const { taskUid } = await client.index(index.uid).addDocuments(dataset) - await client.waitForTask(taskUid) - }) + }); + const { taskUid } = await client.index(index.uid).addDocuments(dataset); + await client.waitForTask(taskUid); + }); test(`${permission} key: basic facet value search`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const params = { facetQuery: 'a', facetName: 'genres', - } - const response = await client.index(index.uid).searchForFacetValues(params) + }; + const response = await client.index(index.uid).searchForFacetValues(params); - expect(response).toMatchSnapshot() - }) + expect(response).toMatchSnapshot(); + }); test(`${permission} key: facet value search with no facet query`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const params = { facetName: 'genres', - } - const response = await client.index(index.uid).searchForFacetValues(params) + }; + const response = await client.index(index.uid).searchForFacetValues(params); - expect(response).toMatchSnapshot() - }) + expect(response).toMatchSnapshot(); + }); test(`${permission} key: facet value search with filter`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const params = { facetName: 'genres', facetQuery: 'a', filter: ['genres = action'], - } + }; - const response = await client.index(index.uid).searchForFacetValues(params) + const response = await client.index(index.uid).searchForFacetValues(params); - expect(response).toMatchSnapshot() - }) + expect(response).toMatchSnapshot(); + }); test(`${permission} key: facet value search with search query`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const params = { facetName: 'genres', facetQuery: 'a', q: 'Alice', - } - const response = await client.index(index.uid).searchForFacetValues(params) + }; + const response = await client.index(index.uid).searchForFacetValues(params); // @TODO: This is flaky, processingTimeMs is not guaranteed - expect(response).toMatchSnapshot() - }) -}) + expect(response).toMatchSnapshot(); + }); +}); -jest.setTimeout(100 * 1000) +jest.setTimeout(100 * 1000); afterAll(() => { - return clearAllIndexes(config) -}) + return clearAllIndexes(config); +}); diff --git a/tests/faceting.test.ts b/tests/faceting.test.ts index ab586a034..5144659eb 100644 --- a/tests/faceting.test.ts +++ b/tests/faceting.test.ts @@ -1,4 +1,4 @@ -import { ErrorStatusCode } from '../src/types' +import { ErrorStatusCode } from '../src/types'; import { clearAllIndexes, config, @@ -6,69 +6,69 @@ import { MeiliSearch, getClient, dataset, -} from './utils/meilisearch-test-utils' +} from './utils/meilisearch-test-utils'; const index = { uid: 'movies_test', -} +}; -jest.setTimeout(100 * 1000) +jest.setTimeout(100 * 1000); afterAll(() => { - return clearAllIndexes(config) -}) + return clearAllIndexes(config); +}); describe.each([{ permission: 'Master' }, { permission: 'Admin' }])( 'Test on faceting', ({ permission }) => { beforeEach(async () => { - await clearAllIndexes(config) - const client = await getClient('Master') - const { taskUid } = await client.createIndex(index.uid) - await client.waitForTask(taskUid) + await clearAllIndexes(config); + const client = await getClient('Master'); + const { taskUid } = await client.createIndex(index.uid); + await client.waitForTask(taskUid); const { taskUid: docTask } = await client .index(index.uid) - .addDocuments(dataset) - await client.waitForTask(docTask) - }) + .addDocuments(dataset); + await client.waitForTask(docTask); + }); test(`${permission} key: Get default faceting object`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); - const response = await client.index(index.uid).getFaceting() + const response = await client.index(index.uid).getFaceting(); - expect(response).toMatchSnapshot() - }) + expect(response).toMatchSnapshot(); + }); test(`${permission} key: Update faceting settings`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const newFaceting = { maxValuesPerFacet: 12, sortFacetValuesBy: { test: 'count' as 'count' }, - } - const task = await client.index(index.uid).updateFaceting(newFaceting) - await client.index(index.uid).waitForTask(task.taskUid) + }; + const task = await client.index(index.uid).updateFaceting(newFaceting); + await client.index(index.uid).waitForTask(task.taskUid); - const response = await client.index(index.uid).getFaceting() + const response = await client.index(index.uid).getFaceting(); - expect(response).toMatchSnapshot() - }) + expect(response).toMatchSnapshot(); + }); test(`${permission} key: Update faceting at null`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const task = await client .index(index.uid) - .updateFaceting({ maxValuesPerFacet: null }) - await client.index(index.uid).waitForTask(task.taskUid) + .updateFaceting({ maxValuesPerFacet: null }); + await client.index(index.uid).waitForTask(task.taskUid); - const response = await client.index(index.uid).getFaceting() + const response = await client.index(index.uid).getFaceting(); - expect(response).toMatchSnapshot() - }) + expect(response).toMatchSnapshot(); + }); test(`${permission} key: Reset faceting`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await client .index(index.uid) .waitForTask( @@ -76,85 +76,85 @@ describe.each([{ permission: 'Master' }, { permission: 'Admin' }])( await client .index(index.uid) .updateFaceting({ maxValuesPerFacet: 12 }) - ).taskUid - ) - const task = await client.index(index.uid).resetFaceting() - await client.index(index.uid).waitForTask(task.taskUid) + ).taskUid, + ); + const task = await client.index(index.uid).resetFaceting(); + await client.index(index.uid).waitForTask(task.taskUid); - const response = await client.index(index.uid).getFaceting() + const response = await client.index(index.uid).getFaceting(); - expect(response).toMatchSnapshot() - }) - } -) + expect(response).toMatchSnapshot(); + }); + }, +); describe.each([{ permission: 'Search' }])( 'Test on faceting', ({ permission }) => { beforeEach(async () => { - const client = await getClient('Master') - const { taskUid } = await client.createIndex(index.uid) - await client.waitForTask(taskUid) - }) + const client = await getClient('Master'); + const { taskUid } = await client.createIndex(index.uid); + await client.waitForTask(taskUid); + }); test(`${permission} key: try to get faceting and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect( - client.index(index.uid).getFaceting() - ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY) - }) + client.index(index.uid).getFaceting(), + ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY); + }); test(`${permission} key: try to update faceting and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect( - client.index(index.uid).updateFaceting({ maxValuesPerFacet: 13 }) - ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY) - }) + client.index(index.uid).updateFaceting({ maxValuesPerFacet: 13 }), + ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY); + }); test(`${permission} key: try to reset faceting and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect( - client.index(index.uid).resetFaceting() - ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY) - }) - } -) + client.index(index.uid).resetFaceting(), + ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY); + }); + }, +); describe.each([{ permission: 'No' }])('Test on faceting', ({ permission }) => { beforeAll(async () => { - const client = await getClient('Master') - const { taskUid } = await client.createIndex(index.uid) - await client.waitForTask(taskUid) - }) + const client = await getClient('Master'); + const { taskUid } = await client.createIndex(index.uid); + await client.waitForTask(taskUid); + }); test(`${permission} key: try to get faceting and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect(client.index(index.uid).getFaceting()).rejects.toHaveProperty( 'cause.code', - ErrorStatusCode.MISSING_AUTHORIZATION_HEADER - ) - }) + ErrorStatusCode.MISSING_AUTHORIZATION_HEADER, + ); + }); test(`${permission} key: try to update faceting and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect( - client.index(index.uid).updateFaceting({ maxValuesPerFacet: 13 }) + client.index(index.uid).updateFaceting({ maxValuesPerFacet: 13 }), ).rejects.toHaveProperty( 'cause.code', - ErrorStatusCode.MISSING_AUTHORIZATION_HEADER - ) - }) + ErrorStatusCode.MISSING_AUTHORIZATION_HEADER, + ); + }); test(`${permission} key: try to reset faceting and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect( - client.index(index.uid).resetFaceting() + client.index(index.uid).resetFaceting(), ).rejects.toHaveProperty( 'cause.code', - ErrorStatusCode.MISSING_AUTHORIZATION_HEADER - ) - }) -}) + ErrorStatusCode.MISSING_AUTHORIZATION_HEADER, + ); + }); +}); describe.each([ { host: BAD_HOST, trailing: false }, @@ -162,36 +162,36 @@ describe.each([ { host: `${BAD_HOST}/trailing/`, trailing: true }, ])('Tests on url construction', ({ host, trailing }) => { test(`Test getFaceting route`, async () => { - const route = `indexes/${index.uid}/settings/faceting` - const client = new MeiliSearch({ host }) - const strippedHost = trailing ? host.slice(0, -1) : host + const route = `indexes/${index.uid}/settings/faceting`; + const client = new MeiliSearch({ host }); + const strippedHost = trailing ? host.slice(0, -1) : host; await expect(client.index(index.uid).getFaceting()).rejects.toHaveProperty( 'message', - `Request to ${strippedHost}/${route} has failed` - ) - }) + `Request to ${strippedHost}/${route} has failed`, + ); + }); test(`Test updateFaceting route`, async () => { - const route = `indexes/${index.uid}/settings/faceting` - const client = new MeiliSearch({ host }) - const strippedHost = trailing ? host.slice(0, -1) : host + const route = `indexes/${index.uid}/settings/faceting`; + const client = new MeiliSearch({ host }); + const strippedHost = trailing ? host.slice(0, -1) : host; await expect( - client.index(index.uid).updateFaceting({ maxValuesPerFacet: null }) + client.index(index.uid).updateFaceting({ maxValuesPerFacet: null }), ).rejects.toHaveProperty( 'message', - `Request to ${strippedHost}/${route} has failed` - ) - }) + `Request to ${strippedHost}/${route} has failed`, + ); + }); test(`Test resetFaceting route`, async () => { - const route = `indexes/${index.uid}/settings/faceting` - const client = new MeiliSearch({ host }) - const strippedHost = trailing ? host.slice(0, -1) : host + const route = `indexes/${index.uid}/settings/faceting`; + const client = new MeiliSearch({ host }); + const strippedHost = trailing ? host.slice(0, -1) : host; await expect( - client.index(index.uid).resetFaceting() + client.index(index.uid).resetFaceting(), ).rejects.toHaveProperty( 'message', - `Request to ${strippedHost}/${route} has failed` - ) - }) -}) + `Request to ${strippedHost}/${route} has failed`, + ); + }); +}); diff --git a/tests/filterable_attributes.test.ts b/tests/filterable_attributes.test.ts index ac5b17e73..03b9df931 100644 --- a/tests/filterable_attributes.test.ts +++ b/tests/filterable_attributes.test.ts @@ -1,4 +1,4 @@ -import { ErrorStatusCode } from '../src/types' +import { ErrorStatusCode } from '../src/types'; import { clearAllIndexes, config, @@ -6,150 +6,150 @@ import { MeiliSearch, getClient, dataset, -} from './utils/meilisearch-test-utils' +} from './utils/meilisearch-test-utils'; const index = { uid: 'movies_test', -} +}; -jest.setTimeout(100 * 1000) +jest.setTimeout(100 * 1000); afterAll(() => { - return clearAllIndexes(config) -}) + return clearAllIndexes(config); +}); describe.each([{ permission: 'Master' }, { permission: 'Admin' }])( 'Test on searchable attributes', ({ permission }) => { beforeEach(async () => { - const client = await getClient('Master') - const { taskUid } = await client.index(index.uid).addDocuments(dataset) - await client.waitForTask(taskUid) - }) + const client = await getClient('Master'); + const { taskUid } = await client.index(index.uid).addDocuments(dataset); + await client.waitForTask(taskUid); + }); test(`${permission} key: Get default attributes for filtering`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const response: string[] = await client .index(index.uid) - .getFilterableAttributes() + .getFilterableAttributes(); - expect(response.sort()).toEqual([]) - }) + expect(response.sort()).toEqual([]); + }); test(`${permission} key: Update attributes for filtering`, async () => { - const client = await getClient(permission) - const newFilterableAttributes = ['genre'] + const client = await getClient(permission); + const newFilterableAttributes = ['genre']; const task = await client .index(index.uid) - .updateFilterableAttributes(newFilterableAttributes) - await client.index(index.uid).waitForTask(task.taskUid) + .updateFilterableAttributes(newFilterableAttributes); + await client.index(index.uid).waitForTask(task.taskUid); const response: string[] = await client .index(index.uid) - .getFilterableAttributes() - expect(response).toEqual(newFilterableAttributes) - }) + .getFilterableAttributes(); + expect(response).toEqual(newFilterableAttributes); + }); test(`${permission} key: Update attributes for filtering at null`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const task = await client .index(index.uid) - .updateFilterableAttributes(null) - await client.index(index.uid).waitForTask(task.taskUid) + .updateFilterableAttributes(null); + await client.index(index.uid).waitForTask(task.taskUid); const response: string[] = await client .index(index.uid) - .getFilterableAttributes() + .getFilterableAttributes(); - expect(response.sort()).toEqual([]) - }) + expect(response.sort()).toEqual([]); + }); test(`${permission} key: Reset attributes for filtering`, async () => { - const client = await getClient(permission) - const task = await client.index(index.uid).resetFilterableAttributes() - await client.index(index.uid).waitForTask(task.taskUid) + const client = await getClient(permission); + const task = await client.index(index.uid).resetFilterableAttributes(); + await client.index(index.uid).waitForTask(task.taskUid); const response: string[] = await client .index(index.uid) - .getFilterableAttributes() + .getFilterableAttributes(); - expect(response.sort()).toEqual([]) - }) - } -) + expect(response.sort()).toEqual([]); + }); + }, +); describe.each([{ permission: 'Search' }])( 'Test on attributes for filtering', ({ permission }) => { beforeEach(async () => { - const client = await getClient('Master') - const { taskUid } = await client.createIndex(index.uid) - await client.waitForTask(taskUid) - }) + const client = await getClient('Master'); + const { taskUid } = await client.createIndex(index.uid); + await client.waitForTask(taskUid); + }); test(`${permission} key: try to get attributes for filtering and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect( - client.index(index.uid).getFilterableAttributes() - ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY) - }) + client.index(index.uid).getFilterableAttributes(), + ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY); + }); test(`${permission} key: try to update attributes for filtering and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect( - client.index(index.uid).updateFilterableAttributes([]) - ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY) - }) + client.index(index.uid).updateFilterableAttributes([]), + ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY); + }); test(`${permission} key: try to reset attributes for filtering and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect( - client.index(index.uid).resetFilterableAttributes() - ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY) - }) - } -) + client.index(index.uid).resetFilterableAttributes(), + ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY); + }); + }, +); describe.each([{ permission: 'No' }])( 'Test on attributes for filtering', ({ permission }) => { beforeEach(async () => { - const client = await getClient('Master') - const { taskUid } = await client.createIndex(index.uid) - await client.waitForTask(taskUid) - }) + const client = await getClient('Master'); + const { taskUid } = await client.createIndex(index.uid); + await client.waitForTask(taskUid); + }); test(`${permission} key: try to get attributes for filtering and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect( - client.index(index.uid).getFilterableAttributes() + client.index(index.uid).getFilterableAttributes(), ).rejects.toHaveProperty( 'cause.code', - ErrorStatusCode.MISSING_AUTHORIZATION_HEADER - ) - }) + ErrorStatusCode.MISSING_AUTHORIZATION_HEADER, + ); + }); test(`${permission} key: try to update attributes for filtering and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect( - client.index(index.uid).updateFilterableAttributes([]) + client.index(index.uid).updateFilterableAttributes([]), ).rejects.toHaveProperty( 'cause.code', - ErrorStatusCode.MISSING_AUTHORIZATION_HEADER - ) - }) + ErrorStatusCode.MISSING_AUTHORIZATION_HEADER, + ); + }); test(`${permission} key: try to reset attributes for filtering and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect( - client.index(index.uid).resetFilterableAttributes() + client.index(index.uid).resetFilterableAttributes(), ).rejects.toHaveProperty( 'cause.code', - ErrorStatusCode.MISSING_AUTHORIZATION_HEADER - ) - }) - } -) + ErrorStatusCode.MISSING_AUTHORIZATION_HEADER, + ); + }); + }, +); describe.each([ { host: BAD_HOST, trailing: false }, @@ -157,38 +157,38 @@ describe.each([ { host: `${BAD_HOST}/trailing/`, trailing: true }, ])('Tests on url construction', ({ host, trailing }) => { test(`Test getFilterableAttributes route`, async () => { - const route = `indexes/${index.uid}/settings/filterable-attributes` - const client = new MeiliSearch({ host }) - const strippedHost = trailing ? host.slice(0, -1) : host + const route = `indexes/${index.uid}/settings/filterable-attributes`; + const client = new MeiliSearch({ host }); + const strippedHost = trailing ? host.slice(0, -1) : host; await expect( - client.index(index.uid).getFilterableAttributes() + client.index(index.uid).getFilterableAttributes(), ).rejects.toHaveProperty( 'message', - `Request to ${strippedHost}/${route} has failed` - ) - }) + `Request to ${strippedHost}/${route} has failed`, + ); + }); test(`Test updateFilterableAttributes route`, async () => { - const route = `indexes/${index.uid}/settings/filterable-attributes` - const client = new MeiliSearch({ host }) - const strippedHost = trailing ? host.slice(0, -1) : host + const route = `indexes/${index.uid}/settings/filterable-attributes`; + const client = new MeiliSearch({ host }); + const strippedHost = trailing ? host.slice(0, -1) : host; await expect( - client.index(index.uid).updateFilterableAttributes([]) + client.index(index.uid).updateFilterableAttributes([]), ).rejects.toHaveProperty( 'message', - `Request to ${strippedHost}/${route} has failed` - ) - }) + `Request to ${strippedHost}/${route} has failed`, + ); + }); test(`Test resetFilterableAttributes route`, async () => { - const route = `indexes/${index.uid}/settings/filterable-attributes` - const client = new MeiliSearch({ host }) - const strippedHost = trailing ? host.slice(0, -1) : host + const route = `indexes/${index.uid}/settings/filterable-attributes`; + const client = new MeiliSearch({ host }); + const strippedHost = trailing ? host.slice(0, -1) : host; await expect( - client.index(index.uid).resetFilterableAttributes() + client.index(index.uid).resetFilterableAttributes(), ).rejects.toHaveProperty( 'message', - `Request to ${strippedHost}/${route} has failed` - ) - }) -}) + `Request to ${strippedHost}/${route} has failed`, + ); + }); +}); diff --git a/tests/get_search.test.ts b/tests/get_search.test.ts index 1504f06a5..e03b82de6 100644 --- a/tests/get_search.test.ts +++ b/tests/get_search.test.ts @@ -1,5 +1,5 @@ -import { ErrorStatusCode } from '../src/types' -import { EnqueuedTask } from '../src/enqueued-task' +import { ErrorStatusCode } from '../src/types'; +import { EnqueuedTask } from '../src/enqueued-task'; import { clearAllIndexes, config, @@ -8,14 +8,14 @@ import { getClient, HOST, getKey, -} from './utils/meilisearch-test-utils' +} from './utils/meilisearch-test-utils'; const index = { uid: 'movies_test', -} +}; const emptyIndex = { uid: 'empty_test', -} +}; const dataset = [ { @@ -55,13 +55,13 @@ const dataset = [ genre: 'fantasy', }, { id: 42, title: "The Hitchhiker's Guide to the Galaxy", genre: 'fantasy' }, -] +]; -jest.setTimeout(100 * 1000) +jest.setTimeout(100 * 1000); afterAll(() => { - return clearAllIndexes(config) -}) + return clearAllIndexes(config); +}); describe.each([ { permission: 'Master' }, @@ -69,122 +69,122 @@ describe.each([ { permission: 'Search' }, ])('Test on GET search', ({ permission }) => { beforeAll(async () => { - await clearAllIndexes(config) - const client = await getClient('Master') - const { taskUid: task1 } = await client.createIndex(index.uid) - await client.waitForTask(task1) - const { taskUid: task2 } = await client.createIndex(emptyIndex.uid) - await client.waitForTask(task2) - - const newFilterableAttributes = ['genre', 'title', 'id'] + await clearAllIndexes(config); + const client = await getClient('Master'); + const { taskUid: task1 } = await client.createIndex(index.uid); + await client.waitForTask(task1); + const { taskUid: task2 } = await client.createIndex(emptyIndex.uid); + await client.waitForTask(task2); + + const newFilterableAttributes = ['genre', 'title', 'id']; const { taskUid: task3 }: EnqueuedTask = await client .index(index.uid) .updateSettings({ filterableAttributes: newFilterableAttributes, sortableAttributes: ['id'], - }) - await client.waitForTask(task3) + }); + await client.waitForTask(task3); const { taskUid: task4 } = await client .index(index.uid) - .addDocuments(dataset) - await client.waitForTask(task4) - }) + .addDocuments(dataset); + await client.waitForTask(task4); + }); test(`${permission} key: Basic search`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); - const response = await client.index(index.uid).searchGet('prince', {}) + const response = await client.index(index.uid).searchGet('prince', {}); - expect(response).toHaveProperty('hits') - expect(Array.isArray(response.hits)).toBe(true) - expect(response).toHaveProperty('limit', 20) - expect(response).toHaveProperty('offset', 0) - expect(response).toHaveProperty('processingTimeMs', expect.any(Number)) - expect(response).toHaveProperty('query', 'prince') - expect(response.hits.length).toEqual(2) - }) + expect(response).toHaveProperty('hits'); + expect(Array.isArray(response.hits)).toBe(true); + expect(response).toHaveProperty('limit', 20); + expect(response).toHaveProperty('offset', 0); + expect(response).toHaveProperty('processingTimeMs', expect.any(Number)); + expect(response).toHaveProperty('query', 'prince'); + expect(response.hits.length).toEqual(2); + }); test(`${permission} key: search with options`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const response = await client .index(index.uid) - .searchGet('prince', { limit: 1 }) - expect(response).toHaveProperty('hits') - expect(Array.isArray(response.hits)).toBe(true) - expect(response).toHaveProperty('offset', 0) - expect(response).toHaveProperty('limit', 1) - expect(response).toHaveProperty('processingTimeMs', expect.any(Number)) - expect(response).toHaveProperty('query', 'prince') - expect(response.hits.length).toEqual(1) - }) + .searchGet('prince', { limit: 1 }); + expect(response).toHaveProperty('hits'); + expect(Array.isArray(response.hits)).toBe(true); + expect(response).toHaveProperty('offset', 0); + expect(response).toHaveProperty('limit', 1); + expect(response).toHaveProperty('processingTimeMs', expect.any(Number)); + expect(response).toHaveProperty('query', 'prince'); + expect(response.hits.length).toEqual(1); + }); test(`${permission} key: search with sortable`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const response = await client .index(index.uid) - .search('', { sort: ['id:asc'] }) - expect(response).toHaveProperty('hits') - expect(Array.isArray(response.hits)).toBe(true) - const hit = response.hits[0] - expect(hit.id).toEqual(1) - }) + .search('', { sort: ['id:asc'] }); + expect(response).toHaveProperty('hits'); + expect(Array.isArray(response.hits)).toBe(true); + const hit = response.hits[0]; + expect(hit.id).toEqual(1); + }); test(`${permission} key: search with array options`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const response = await client.index(index.uid).searchGet('prince', { attributesToRetrieve: ['*'], - }) - const hit = response.hits[0] + }); + const hit = response.hits[0]; - expect(response).toHaveProperty('hits') - expect(Array.isArray(response.hits)).toBe(true) - expect(response).toHaveProperty('query', 'prince') + expect(response).toHaveProperty('hits'); + expect(Array.isArray(response.hits)).toBe(true); + expect(response).toHaveProperty('query', 'prince'); expect(Object.keys(hit).join(',')).toEqual( - Object.keys(dataset[1]).join(',') - ) - }) + Object.keys(dataset[1]).join(','), + ); + }); test(`${permission} key: search on attributesToSearchOn`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const response = await client.index(index.uid).searchGet('prince', { attributesToSearchOn: ['id'], - }) + }); - expect(response.hits.length).toEqual(0) - }) + expect(response.hits.length).toEqual(0); + }); test(`${permission} key: search on attributesToSearchOn set to null`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const response = await client.index(index.uid).searchGet('prince', { attributesToSearchOn: null, - }) + }); - expect(response).toMatchSnapshot() - }) + expect(response).toMatchSnapshot(); + }); test(`${permission} key: search with options`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const response = await client .index(index.uid) - .searchGet('prince', { limit: 1 }) - expect(response).toHaveProperty('hits') - expect(Array.isArray(response.hits)).toBe(true) - expect(response).toHaveProperty('offset', 0) - expect(response).toHaveProperty('limit', 1) - expect(response).toHaveProperty('processingTimeMs', expect.any(Number)) - expect(response).toHaveProperty('query', 'prince') - expect(response.hits.length).toEqual(1) - }) + .searchGet('prince', { limit: 1 }); + expect(response).toHaveProperty('hits'); + expect(Array.isArray(response.hits)).toBe(true); + expect(response).toHaveProperty('offset', 0); + expect(response).toHaveProperty('limit', 1); + expect(response).toHaveProperty('processingTimeMs', expect.any(Number)); + expect(response).toHaveProperty('query', 'prince'); + expect(response.hits.length).toEqual(1); + }); test(`${permission} key: search with limit and offset`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const response = await client.index(index.uid).searchGet('prince', { limit: 1, offset: 1, - }) + }); expect(response).toHaveProperty('hits', [ { id: 4, @@ -192,32 +192,32 @@ describe.each([ comment: 'The best book', genre: 'fantasy', }, - ]) - expect(response).toHaveProperty('offset', 1) - expect(response).toHaveProperty('limit', 1) - expect(response).toHaveProperty('processingTimeMs', expect.any(Number)) - expect(response).toHaveProperty('query', 'prince') - expect(response.hits.length).toEqual(1) - }) + ]); + expect(response).toHaveProperty('offset', 1); + expect(response).toHaveProperty('limit', 1); + expect(response).toHaveProperty('processingTimeMs', expect.any(Number)); + expect(response).toHaveProperty('query', 'prince'); + expect(response.hits.length).toEqual(1); + }); test(`${permission} key: search with matches parameter and small croplength`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const response = await client.index(index.uid).searchGet('prince', { filter: 'title = "Le Petit Prince"', attributesToCrop: ['*'], cropLength: 5, showMatchesPosition: true, - }) - expect(response).toHaveProperty('hits') - expect(Array.isArray(response.hits)).toBe(true) + }); + expect(response).toHaveProperty('hits'); + expect(Array.isArray(response.hits)).toBe(true); expect(response.hits[0]).toHaveProperty('_matchesPosition', { comment: [{ start: 22, length: 6 }], title: [{ start: 9, length: 6 }], - }) - }) + }); + }); test(`${permission} key: search with all options but not all fields`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const response = await client.index(index.uid).searchGet('prince', { limit: 5, offset: 0, @@ -227,73 +227,73 @@ describe.each([ attributesToHighlight: ['*'], filter: 'title = "Le Petit Prince"', showMatchesPosition: true, - }) - - expect(response).toHaveProperty('hits') - expect(Array.isArray(response.hits)).toBe(true) - expect(response).toHaveProperty('offset', 0) - expect(response).toHaveProperty('limit', 5) - expect(response).toHaveProperty('processingTimeMs', expect.any(Number)) - expect(response).toHaveProperty('query', 'prince') - expect(response.hits[0]._formatted).toHaveProperty('title') - expect(response.hits[0]._formatted).toHaveProperty('id') - expect(response.hits[0]).not.toHaveProperty('comment') - expect(response.hits[0]).not.toHaveProperty('description') - expect(response.hits.length).toEqual(1) - expect(response.hits[0]).toHaveProperty('_formatted', expect.any(Object)) + }); + + expect(response).toHaveProperty('hits'); + expect(Array.isArray(response.hits)).toBe(true); + expect(response).toHaveProperty('offset', 0); + expect(response).toHaveProperty('limit', 5); + expect(response).toHaveProperty('processingTimeMs', expect.any(Number)); + expect(response).toHaveProperty('query', 'prince'); + expect(response.hits[0]._formatted).toHaveProperty('title'); + expect(response.hits[0]._formatted).toHaveProperty('id'); + expect(response.hits[0]).not.toHaveProperty('comment'); + expect(response.hits[0]).not.toHaveProperty('description'); + expect(response.hits.length).toEqual(1); + expect(response.hits[0]).toHaveProperty('_formatted', expect.any(Object)); expect(response.hits[0]._formatted).toHaveProperty( 'title', - 'Le Petit Prince' - ) + 'Le Petit Prince', + ); expect(response.hits[0]).toHaveProperty( '_matchesPosition', - expect.any(Object) - ) - }) + expect.any(Object), + ); + }); test(`${permission} key: search on default cropping parameters`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const response = await client.index(index.uid).searchGet('prince', { attributesToCrop: ['*'], cropLength: 6, - }) + }); expect(response.hits[0]._formatted).toHaveProperty( 'comment', - '…book about a prince that walks…' - ) - }) + '…book about a prince that walks…', + ); + }); test(`${permission} key: search on customized cropMarker`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const response = await client.index(index.uid).searchGet('prince', { attributesToCrop: ['*'], cropLength: 6, cropMarker: '(ꈍᴗꈍ)', - }) + }); expect(response.hits[0]._formatted).toHaveProperty( 'comment', - '(ꈍᴗꈍ)book about a prince that walks(ꈍᴗꈍ)' - ) - }) + '(ꈍᴗꈍ)book about a prince that walks(ꈍᴗꈍ)', + ); + }); test(`${permission} key: search on customized highlight tags`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const response = await client.index(index.uid).searchGet('prince', { attributesToHighlight: ['*'], highlightPreTag: '(⊃。•́‿•̀。)⊃ ', highlightPostTag: ' ⊂(´• ω •`⊂)', - }) + }); expect(response.hits[0]._formatted).toHaveProperty( 'comment', - 'A french book about a (⊃。•́‿•̀。)⊃ prince ⊂(´• ω •`⊂) that walks on little cute planets' - ) - }) + 'A french book about a (⊃。•́‿•̀。)⊃ prince ⊂(´• ω •`⊂) that walks on little cute planets', + ); + }); test(`${permission} key: search with all options and all fields`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const response = await client.index(index.uid).searchGet('prince', { limit: 5, offset: 0, @@ -303,27 +303,27 @@ describe.each([ attributesToHighlight: ['*'], filter: 'title = "Le Petit Prince"', showMatchesPosition: true, - }) - expect(response).toHaveProperty('hits') - expect(Array.isArray(response.hits)).toBe(true) - expect(response).toHaveProperty('offset', 0) - expect(response).toHaveProperty('limit', 5) - expect(response).toHaveProperty('processingTimeMs', expect.any(Number)) - expect(response).toHaveProperty('query', 'prince') - expect(response.hits.length).toEqual(1) - expect(response.hits[0]).toHaveProperty('_formatted', expect.any(Object)) + }); + expect(response).toHaveProperty('hits'); + expect(Array.isArray(response.hits)).toBe(true); + expect(response).toHaveProperty('offset', 0); + expect(response).toHaveProperty('limit', 5); + expect(response).toHaveProperty('processingTimeMs', expect.any(Number)); + expect(response).toHaveProperty('query', 'prince'); + expect(response.hits.length).toEqual(1); + expect(response.hits[0]).toHaveProperty('_formatted', expect.any(Object)); expect(response.hits[0]._formatted).toHaveProperty( 'title', - 'Le Petit Prince' - ) + 'Le Petit Prince', + ); expect(response.hits[0]).toHaveProperty( '_matchesPosition', - expect.any(Object) - ) - }) + expect.any(Object), + ); + }); test(`${permission} key: search with all options but specific fields`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const response = await client.index(index.uid).searchGet('prince', { limit: 5, offset: 0, @@ -333,135 +333,135 @@ describe.each([ attributesToHighlight: ['id', 'title'], filter: 'title = "Le Petit Prince"', showMatchesPosition: true, - }) - expect(response).toHaveProperty('hits') - expect(Array.isArray(response.hits)).toBe(true) - expect(response).toHaveProperty('offset', 0) - expect(response).toHaveProperty('limit', 5) - expect(response).toHaveProperty('processingTimeMs', expect.any(Number)) - expect(response).toHaveProperty('query', 'prince') - expect(response.hits.length).toEqual(1) - expect(response.hits[0]).toHaveProperty('id', 456) - expect(response.hits[0]).toHaveProperty('title', 'Le Petit Prince') - expect(response.hits[0]).not.toHaveProperty('comment') - expect(response.hits[0]).toHaveProperty('_formatted', expect.any(Object)) + }); + expect(response).toHaveProperty('hits'); + expect(Array.isArray(response.hits)).toBe(true); + expect(response).toHaveProperty('offset', 0); + expect(response).toHaveProperty('limit', 5); + expect(response).toHaveProperty('processingTimeMs', expect.any(Number)); + expect(response).toHaveProperty('query', 'prince'); + expect(response.hits.length).toEqual(1); + expect(response.hits[0]).toHaveProperty('id', 456); + expect(response.hits[0]).toHaveProperty('title', 'Le Petit Prince'); + expect(response.hits[0]).not.toHaveProperty('comment'); + expect(response.hits[0]).toHaveProperty('_formatted', expect.any(Object)); expect(response.hits[0]).not.toHaveProperty( 'description', - expect.any(Object) - ) + expect.any(Object), + ); expect(response.hits[0]._formatted).toHaveProperty( 'title', - 'Le Petit Prince' - ) - expect(response.hits[0]._formatted).not.toHaveProperty('comment') + 'Le Petit Prince', + ); + expect(response.hits[0]._formatted).not.toHaveProperty('comment'); expect(response.hits[0]).toHaveProperty( '_matchesPosition', - expect.any(Object) - ) - }) + expect.any(Object), + ); + }); test(`${permission} key: search with filter and facetDistribution`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const response = await client.index(index.uid).searchGet('a', { filter: 'genre = romance', facets: ['genre'], - }) + }); expect(response).toHaveProperty('facetDistribution', { genre: { romance: 2 }, - }) - expect(response).toHaveProperty('hits') - expect(Array.isArray(response.hits)).toBe(true) - expect(response.hits.length).toEqual(2) - }) + }); + expect(response).toHaveProperty('hits'); + expect(Array.isArray(response.hits)).toBe(true); + expect(response.hits.length).toEqual(2); + }); test(`${permission} key: search with filter on number`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const response = await client.index(index.uid).searchGet('a', { filter: 'id < 0', facets: ['genre'], - }) - expect(response).toHaveProperty('hits') - expect(Array.isArray(response.hits)).toBe(true) - expect(response.hits.length).toEqual(0) - }) + }); + expect(response).toHaveProperty('hits'); + expect(Array.isArray(response.hits)).toBe(true); + expect(response.hits.length).toEqual(0); + }); test(`${permission} key: search with filter with spaces`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const response = await client.index(index.uid).searchGet('h', { filter: 'genre = "sci fi"', - }) - expect(response).toHaveProperty('hits') - expect(Array.isArray(response.hits)).toBe(true) - expect(response.hits.length).toEqual(1) - }) + }); + expect(response).toHaveProperty('hits'); + expect(Array.isArray(response.hits)).toBe(true); + expect(response.hits.length).toEqual(1); + }); test(`${permission} key: search with multiple filter`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const response = await client.index(index.uid).searchGet('a', { filter: 'genre = romance AND (genre = romance OR genre = romance)', facets: ['genre'], - }) + }); expect(response).toHaveProperty('facetDistribution', { genre: { romance: 2 }, - }) - expect(response).toHaveProperty('hits') - expect(Array.isArray(response.hits)).toBe(true) - expect(response.hits.length).toEqual(2) - }) + }); + expect(response).toHaveProperty('hits'); + expect(Array.isArray(response.hits)).toBe(true); + expect(response.hits.length).toEqual(2); + }); test(`${permission} key: search with multiple filter and undefined query (placeholder)`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const response = await client.index(index.uid).searchGet(undefined, { filter: 'genre = fantasy', facets: ['genre'], - }) + }); expect(response).toHaveProperty('facetDistribution', { genre: { fantasy: 2 }, - }) - expect(response.hits.length).toEqual(2) - }) + }); + expect(response.hits.length).toEqual(2); + }); test(`${permission} key: search with multiple filter and null query (placeholder)`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const response = await client.index(index.uid).searchGet(null, { filter: 'genre = fantasy', facets: ['genre'], - }) + }); expect(response).toHaveProperty('facetDistribution', { genre: { fantasy: 2 }, - }) - expect(response.hits.length).toEqual(2) - expect(response.estimatedTotalHits).toEqual(2) - }) + }); + expect(response.hits.length).toEqual(2); + expect(response.estimatedTotalHits).toEqual(2); + }); test(`${permission} key: search with multiple filter and empty string query (placeholder)`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const response = await client.index(index.uid).searchGet('', { filter: 'genre = fantasy', facets: ['genre'], - }) + }); expect(response).toHaveProperty('facetDistribution', { genre: { fantasy: 2 }, - }) - expect(response.hits.length).toEqual(2) - }) + }); + expect(response.hits.length).toEqual(2); + }); test(`${permission} key: Try to search with wrong format filter`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect( client.index(index.uid).searchGet('prince', { filter: ['hello'], - }) + }), ).rejects.toHaveProperty( 'message', - 'The filter query parameter should be in string format when using searchGet' - ) - }) + 'The filter query parameter should be in string format when using searchGet', + ); + }); test(`${permission} key: search with vectors`, async () => { - const client = await getClient(permission) - const adminClient = await getClient('Admin') - const adminKey = await getKey('Admin') + const client = await getClient(permission); + const adminClient = await getClient('Admin'); + const adminKey = await getKey('Admin'); await fetch(`${HOST}/experimental-features`, { body: JSON.stringify({ vectorStore: true }), @@ -470,7 +470,7 @@ describe.each([ 'Content-Type': 'application/json', }, method: 'PATCH', - }) + }); const { taskUid } = await adminClient .index(emptyIndex.uid) @@ -479,38 +479,38 @@ describe.each([ source: 'userProvided', dimensions: 1, }, - }) - await adminClient.waitForTask(taskUid) + }); + await adminClient.waitForTask(taskUid); const response = await client .index(emptyIndex.uid) - .searchGet('', { vector: [1], hybridSemanticRatio: 1.0 }) + .searchGet('', { vector: [1], hybridSemanticRatio: 1.0 }); - expect(response).toHaveProperty('hits') - expect(response).toHaveProperty('semanticHitCount') + expect(response).toHaveProperty('hits'); + expect(response).toHaveProperty('semanticHitCount'); // Those fields are no longer returned by the search response // We want to ensure that they don't appear in it anymore - expect(response).not.toHaveProperty('vector') - expect(response).not.toHaveProperty('_semanticScore') - }) + expect(response).not.toHaveProperty('vector'); + expect(response).not.toHaveProperty('_semanticScore'); + }); test(`${permission} key: search without vectors`, async () => { - const client = await getClient(permission) - const response = await client.index(index.uid).search('prince', {}) + const client = await getClient(permission); + const response = await client.index(index.uid).search('prince', {}); - expect(response).not.toHaveProperty('semanticHitCount') - }) + expect(response).not.toHaveProperty('semanticHitCount'); + }); test(`${permission} key: Try to search on deleted index and fail`, async () => { - const client = await getClient(permission) - const masterClient = await getClient('Master') - const { taskUid } = await masterClient.index(index.uid).delete() - await masterClient.waitForTask(taskUid) + const client = await getClient(permission); + const masterClient = await getClient('Master'); + const { taskUid } = await masterClient.index(index.uid).delete(); + await masterClient.waitForTask(taskUid); await expect( - client.index(index.uid).searchGet('prince') - ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INDEX_NOT_FOUND) - }) -}) + client.index(index.uid).searchGet('prince'), + ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INDEX_NOT_FOUND); + }); +}); describe.each([ { host: BAD_HOST, trailing: false }, @@ -518,22 +518,22 @@ describe.each([ { host: `${BAD_HOST}/trailing/`, trailing: true }, ])('Tests on url construction', ({ host, trailing }) => { test(`Test get search route`, async () => { - const route = `indexes/${index.uid}/search` - const client = new MeiliSearch({ host }) - const strippedHost = trailing ? host.slice(0, -1) : host + const route = `indexes/${index.uid}/search`; + const client = new MeiliSearch({ host }); + const strippedHost = trailing ? host.slice(0, -1) : host; await expect(client.index(index.uid).searchGet()).rejects.toHaveProperty( 'message', - `Request to ${strippedHost}/${route} has failed` - ) - }) + `Request to ${strippedHost}/${route} has failed`, + ); + }); test(`Test post search route`, async () => { - const route = `indexes/${index.uid}/search` - const client = new MeiliSearch({ host }) - const strippedHost = trailing ? host.slice(0, -1) : host + const route = `indexes/${index.uid}/search`; + const client = new MeiliSearch({ host }); + const strippedHost = trailing ? host.slice(0, -1) : host; await expect(client.index(index.uid).searchGet()).rejects.toHaveProperty( 'message', - `Request to ${strippedHost}/${route} has failed` - ) - }) -}) + `Request to ${strippedHost}/${route} has failed`, + ); + }); +}); diff --git a/tests/index.test.ts b/tests/index.test.ts index 6ce76532f..954533d2b 100644 --- a/tests/index.test.ts +++ b/tests/index.test.ts @@ -1,497 +1,499 @@ -import { ErrorStatusCode } from '../src/types' +import { ErrorStatusCode } from '../src/types'; import { clearAllIndexes, config, BAD_HOST, MeiliSearch, getClient, -} from './utils/meilisearch-test-utils' +} from './utils/meilisearch-test-utils'; const indexNoPk = { uid: 'movies_test', -} +}; const indexPk = { uid: 'movies_test2', primaryKey: 'id', -} +}; afterAll(async () => { - return clearAllIndexes(config) -}) + return clearAllIndexes(config); +}); describe.each([{ permission: 'Master' }, { permission: 'Admin' }])( 'Test on indexes w/ master and admin key', ({ permission }) => { beforeEach(() => { - return clearAllIndexes(config) - }) + return clearAllIndexes(config); + }); test(`${permission} key: create index with NO primary key`, async () => { - const client = await getClient(permission) - const { taskUid } = await client.createIndex(indexNoPk.uid) - await client.waitForTask(taskUid) + const client = await getClient(permission); + const { taskUid } = await client.createIndex(indexNoPk.uid); + await client.waitForTask(taskUid); - const newIndex = await client.getIndex(indexNoPk.uid) + const newIndex = await client.getIndex(indexNoPk.uid); - expect(newIndex).toHaveProperty('uid', indexNoPk.uid) - expect(newIndex).toHaveProperty('primaryKey', null) + expect(newIndex).toHaveProperty('uid', indexNoPk.uid); + expect(newIndex).toHaveProperty('primaryKey', null); - const rawIndex = await client.index(indexNoPk.uid).getRawInfo() + 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)) - }) + 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) + const client = await getClient(permission); const { taskUid } = await client.createIndex(indexPk.uid, { primaryKey: indexPk.primaryKey, - }) - await client.waitForTask(taskUid) + }); + await client.waitForTask(taskUid); - const newIndex = await client.getIndex(indexPk.uid) + const newIndex = await client.getIndex(indexPk.uid); - expect(newIndex).toHaveProperty('uid', indexPk.uid) - expect(newIndex).toHaveProperty('primaryKey', indexPk.primaryKey) + expect(newIndex).toHaveProperty('uid', indexPk.uid); + expect(newIndex).toHaveProperty('primaryKey', indexPk.primaryKey); - const rawIndex = await client.index(indexPk.uid).getRawInfo() + 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)) - }) + 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) - const { taskUid } = await client.createIndex(indexPk.uid) - await client.waitForTask(taskUid) + const client = await getClient(permission); + const { taskUid } = await client.createIndex(indexPk.uid); + await client.waitForTask(taskUid); - const response = await client.getRawIndex(indexPk.uid) + const response = await client.getRawIndex(indexPk.uid); - expect(response).toHaveProperty('uid', indexPk.uid) - }) + expect(response).toHaveProperty('uid', indexPk.uid); + }); test(`${permission} key: Get all indexes in Index instances`, async () => { - const client = await getClient(permission) - const { taskUid } = await client.createIndex(indexPk.uid) - await client.waitForTask(taskUid) + const client = await getClient(permission); + const { taskUid } = await client.createIndex(indexPk.uid); + await client.waitForTask(taskUid); - const { results } = await client.getRawIndexes() + const { results } = await client.getRawIndexes(); - expect(results.length).toEqual(1) - expect(results[0].uid).toEqual(indexPk.uid) - }) + 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) + const client = await getClient(permission); await expect(client.getIndex('does_not_exist')).rejects.toHaveProperty( 'cause.code', - ErrorStatusCode.INDEX_NOT_FOUND - ) - }) + ErrorStatusCode.INDEX_NOT_FOUND, + ); + }); test(`${permission} key: Get raw index that does not exist`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect(client.getRawIndex('does_not_exist')).rejects.toHaveProperty( 'cause.code', - ErrorStatusCode.INDEX_NOT_FOUND - ) - }) + ErrorStatusCode.INDEX_NOT_FOUND, + ); + }); test(`${permission} key: Get raw index info through client with primary key`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const { taskUid } = await client.createIndex(indexPk.uid, { primaryKey: indexPk.primaryKey, - }) - await client.waitForTask(taskUid) + }); + await client.waitForTask(taskUid); - const response = await client.getRawIndex(indexPk.uid) + const response = await client.getRawIndex(indexPk.uid); - expect(response).toHaveProperty('uid', indexPk.uid) - expect(response).toHaveProperty('primaryKey', indexPk.primaryKey) - }) + 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) - const { taskUid } = await client.createIndex(indexNoPk.uid) - await client.waitForTask(taskUid) + const client = await getClient(permission); + const { taskUid } = await client.createIndex(indexNoPk.uid); + await client.waitForTask(taskUid); - const response = await client.getRawIndex(indexNoPk.uid) + const response = await client.getRawIndex(indexNoPk.uid); - expect(response).toHaveProperty('uid', indexNoPk.uid) - expect(response).toHaveProperty('primaryKey', null) - }) + 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) + const client = await getClient(permission); const { taskUid } = await client.createIndex(indexPk.uid, { primaryKey: indexPk.primaryKey, - }) - await client.waitForTask(taskUid) + }); + await client.waitForTask(taskUid); - const response = await client.index(indexPk.uid).getRawInfo() + const response = await client.index(indexPk.uid).getRawInfo(); - expect(response).toHaveProperty('uid', indexPk.uid) - expect(response).toHaveProperty('primaryKey', indexPk.primaryKey) - }) + 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) - const { taskUid } = await client.createIndex(indexNoPk.uid) - await client.waitForTask(taskUid) + const client = await getClient(permission); + const { taskUid } = await client.createIndex(indexNoPk.uid); + await client.waitForTask(taskUid); - const response = await client.index(indexNoPk.uid).getRawInfo() + const response = await client.index(indexNoPk.uid).getRawInfo(); - expect(response).toHaveProperty('uid', indexNoPk.uid) - expect(response).toHaveProperty('primaryKey', null) - }) + 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) + const client = await getClient(permission); const { taskUid } = await client.createIndex(indexPk.uid, { primaryKey: indexPk.primaryKey, - }) - await client.waitForTask(taskUid) + }); + await client.waitForTask(taskUid); - const index = client.index(indexPk.uid) - const response = await index.fetchInfo() + const index = client.index(indexPk.uid); + const response = await index.fetchInfo(); - expect(response).toHaveProperty('uid', indexPk.uid) - expect(response).toHaveProperty('primaryKey', indexPk.primaryKey) - }) + 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) + const client = await getClient(permission); const { taskUid } = await client.createIndex(indexPk.uid, { primaryKey: indexPk.primaryKey, - }) - await client.waitForTask(taskUid) + }); + await client.waitForTask(taskUid); - const index = client.index(indexPk.uid) - const response: string | undefined = await index.fetchPrimaryKey() + const index = client.index(indexPk.uid); + const response: string | undefined = await index.fetchPrimaryKey(); - expect(response).toBe(indexPk.primaryKey) - }) + expect(response).toBe(indexPk.primaryKey); + }); test(`${permission} key: fetch primary key on an index with NO primary key`, async () => { - const client = await getClient(permission) - const { taskUid } = await client.createIndex(indexNoPk.uid) - await client.waitForTask(taskUid) + const client = await getClient(permission); + const { taskUid } = await client.createIndex(indexNoPk.uid); + await client.waitForTask(taskUid); - const index = client.index(indexNoPk.uid) - const response: string | undefined = await index.fetchPrimaryKey() + const index = client.index(indexNoPk.uid); + const response: string | undefined = await index.fetchPrimaryKey(); - expect(response).toBe(null) - }) + expect(response).toBe(null); + }); test(`${permission} key: fetch index with primary key`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const { taskUid } = await client.createIndex(indexPk.uid, { primaryKey: indexPk.primaryKey, - }) - await client.waitForTask(taskUid) + }); + await client.waitForTask(taskUid); - const index = client.index(indexPk.uid) - const response = await index.fetchInfo() + const index = client.index(indexPk.uid); + const response = await index.fetchInfo(); - expect(response).toHaveProperty('uid', indexPk.uid) - expect(response).toHaveProperty('primaryKey', indexPk.primaryKey) - }) + 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) - const { taskUid } = await client.createIndex(indexNoPk.uid) - await client.waitForTask(taskUid) + const client = await getClient(permission); + const { taskUid } = await client.createIndex(indexNoPk.uid); + await client.waitForTask(taskUid); - const index = client.index(indexNoPk.uid) - const response = await index.fetchInfo() + const index = client.index(indexNoPk.uid); + const response = await index.fetchInfo(); - expect(response).toHaveProperty('uid', indexNoPk.uid) - expect(response).toHaveProperty('primaryKey', null) - }) + expect(response).toHaveProperty('uid', indexNoPk.uid); + expect(response).toHaveProperty('primaryKey', null); + }); test(`${permission} key: get all indexes`, async () => { - const client = await getClient(permission) - const task1 = await client.createIndex(indexNoPk.uid) - const task2 = await client.createIndex(indexPk.uid) - await client.waitForTask(task1.taskUid) - await client.waitForTask(task2.taskUid) + const client = await getClient(permission); + const task1 = await client.createIndex(indexNoPk.uid); + const task2 = await client.createIndex(indexPk.uid); + await client.waitForTask(task1.taskUid); + await client.waitForTask(task2.taskUid); - const indexes = await client.getIndexes() + const indexes = await client.getIndexes(); - expect(indexes.results.length).toEqual(2) - }) + expect(indexes.results.length).toEqual(2); + }); test(`${permission} key: get all indexes with filters`, async () => { - const client = await getClient(permission) - const task1 = await client.createIndex(indexNoPk.uid) - const task2 = await client.createIndex(indexPk.uid) - await client.waitForTask(task1.taskUid) - await client.waitForTask(task2.taskUid) + const client = await getClient(permission); + const task1 = await client.createIndex(indexNoPk.uid); + const task2 = await client.createIndex(indexPk.uid); + await client.waitForTask(task1.taskUid); + await client.waitForTask(task2.taskUid); - const indexes = await client.getIndexes({ limit: 1, offset: 1 }) + const indexes = await client.getIndexes({ limit: 1, offset: 1 }); - expect(indexes.results.length).toEqual(1) - expect(indexes.results[0].uid).toEqual(indexPk.uid) - }) + 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) - const { taskUid: createTask } = await client.createIndex(indexNoPk.uid) + const client = await getClient(permission); + const { taskUid: createTask } = await client.createIndex(indexNoPk.uid); const { taskUid: updateTask } = await client.index(indexNoPk.uid).update({ primaryKey: 'newPrimaryKey', - }) - await client.waitForTask(createTask) - await client.waitForTask(updateTask) + }); + await client.waitForTask(createTask); + await client.waitForTask(updateTask); - const index = await client.getIndex(indexNoPk.uid) + const index = await client.getIndex(indexNoPk.uid); - expect(index).toHaveProperty('uid', indexNoPk.uid) - expect(index).toHaveProperty('primaryKey', 'newPrimaryKey') - }) + 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) - const { taskUid: createTask } = await client.createIndex(indexNoPk.uid) + const client = await getClient(permission); + const { taskUid: createTask } = await client.createIndex(indexNoPk.uid); const { taskUid: updateTask } = await client.updateIndex(indexNoPk.uid, { primaryKey: indexPk.primaryKey, - }) - await client.waitForTask(createTask) - await client.waitForTask(updateTask) + }); + await client.waitForTask(createTask); + await client.waitForTask(updateTask); - const index = await client.getIndex(indexNoPk.uid) + const index = await client.getIndex(indexNoPk.uid); - expect(index).toHaveProperty('uid', indexNoPk.uid) - expect(index).toHaveProperty('primaryKey', indexPk.primaryKey) - }) + 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) + const client = await getClient(permission); const { taskUid: createTask } = await client.createIndex(indexPk.uid, { primaryKey: indexPk.primaryKey, - }) + }); const { taskUid: updateTask } = await client.updateIndex(indexPk.uid, { primaryKey: 'newPrimaryKey', - }) - await client.waitForTask(createTask) - await client.waitForTask(updateTask) + }); + await client.waitForTask(createTask); + await client.waitForTask(updateTask); - const index = await client.getIndex(indexPk.uid) + const index = await client.getIndex(indexPk.uid); - expect(index).toHaveProperty('uid', indexPk.uid) - expect(index).toHaveProperty('primaryKey', 'newPrimaryKey') - }) + 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) + const client = await getClient(permission); const { taskUid: createTask } = await client.createIndex(indexPk.uid, { primaryKey: indexPk.primaryKey, - }) + }); const { taskUid: updateTask } = await client.index(indexPk.uid).update({ primaryKey: 'newPrimaryKey', - }) - await client.waitForTask(createTask) - await client.waitForTask(updateTask) + }); + await client.waitForTask(createTask); + await client.waitForTask(updateTask); - const index = await client.getIndex(indexPk.uid) + const index = await client.getIndex(indexPk.uid); - expect(index).toHaveProperty('uid', indexPk.uid) - expect(index).toHaveProperty('primaryKey', 'newPrimaryKey') - }) + expect(index).toHaveProperty('uid', indexPk.uid); + expect(index).toHaveProperty('primaryKey', 'newPrimaryKey'); + }); test(`${permission} key: delete index`, async () => { - const client = await getClient(permission) - const { taskUid: createTask } = await client.createIndex(indexNoPk.uid) - const { taskUid: deleteTask } = await client.index(indexNoPk.uid).delete() - await client.waitForTask(createTask) - await client.waitForTask(deleteTask) + const client = await getClient(permission); + const { taskUid: createTask } = await client.createIndex(indexNoPk.uid); + const { taskUid: deleteTask } = await client + .index(indexNoPk.uid) + .delete(); + await client.waitForTask(createTask); + await client.waitForTask(deleteTask); - const { results } = await client.getIndexes() + const { results } = await client.getIndexes(); - expect(results).toHaveLength(0) - }) + expect(results).toHaveLength(0); + }); test(`${permission} key: delete index using client`, async () => { - const client = await getClient(permission) - await client.createIndex(indexPk.uid) - const { taskUid } = await client.deleteIndex(indexPk.uid) - await client.waitForTask(taskUid) + const client = await getClient(permission); + await client.createIndex(indexPk.uid); + const { taskUid } = await client.deleteIndex(indexPk.uid); + await client.waitForTask(taskUid); - const { results } = await client.getIndexes() + const { results } = await client.getIndexes(); - expect(results).toHaveLength(0) - }) + expect(results).toHaveLength(0); + }); test(`${permission} key: fetch deleted index should fail`, async () => { - const client = await getClient(permission) - const index = client.index(indexNoPk.uid) + const client = await getClient(permission); + const index = client.index(indexNoPk.uid); await expect(index.getRawInfo()).rejects.toHaveProperty( 'cause.code', - ErrorStatusCode.INDEX_NOT_FOUND - ) - }) + ErrorStatusCode.INDEX_NOT_FOUND, + ); + }); test(`${permission} key: get deleted raw index should fail through client`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect(client.getRawIndex(indexNoPk.uid)).rejects.toHaveProperty( 'cause.code', - ErrorStatusCode.INDEX_NOT_FOUND - ) - }) + 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 { taskUid } = await index.delete() + const client = await getClient(permission); + const index = client.index(indexNoPk.uid); + const { taskUid } = await index.delete(); - const task = await client.waitForTask(taskUid) + const task = await client.waitForTask(taskUid); - expect(task.status).toBe('failed') - }) + expect(task.status).toBe('failed'); + }); test(`${permission} key: get stats of an index`, async () => { - const client = await getClient(permission) - const { taskUid } = await client.createIndex(indexNoPk.uid) - await client.waitForTask(taskUid) + const client = await getClient(permission); + const { taskUid } = await client.createIndex(indexNoPk.uid); + await client.waitForTask(taskUid); - const response = await client.index(indexNoPk.uid).getStats() + 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('numberOfDocuments', 0); + expect(response).toHaveProperty('isIndexing', false); + expect(response).toHaveProperty('fieldDistribution', {}); + }); test(`${permission} key: Get updatedAt and createdAt through fetch info`, async () => { - const client = await getClient(permission) - const { taskUid } = await client.createIndex(indexPk.uid) - await client.waitForTask(taskUid) + const client = await getClient(permission); + const { taskUid } = await client.createIndex(indexPk.uid); + await client.waitForTask(taskUid); - const index = await client.index(indexPk.uid).fetchInfo() + const index = await client.index(indexPk.uid).fetchInfo(); - expect(index.createdAt).toBeInstanceOf(Date) - expect(index.updatedAt).toBeInstanceOf(Date) - }) + 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) - const { taskUid } = await client.createIndex(indexPk.uid) - await client.waitForTask(taskUid) + const client = await getClient(permission); + const { taskUid } = await client.createIndex(indexPk.uid); + await client.waitForTask(taskUid); - const index = client.index(indexPk.uid) + const index = client.index(indexPk.uid); - expect(index.createdAt).toBe(undefined) - expect(index.updatedAt).toBe(undefined) + expect(index.createdAt).toBe(undefined); + expect(index.updatedAt).toBe(undefined); - await index.getRawInfo() + await index.getRawInfo(); - expect(index.createdAt).toBeInstanceOf(Date) - expect(index.updatedAt).toBeInstanceOf(Date) - }) - } -) + expect(index.createdAt).toBeInstanceOf(Date); + expect(index.updatedAt).toBeInstanceOf(Date); + }); + }, +); describe.each([{ permission: 'Search' }])( 'Test on routes with search key', ({ permission }) => { beforeEach(() => { - return clearAllIndexes(config) - }) + return clearAllIndexes(config); + }); test(`${permission} key: try to get index info and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect( - client.index(indexNoPk.uid).getRawInfo() - ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY) - }) + client.index(indexNoPk.uid).getRawInfo(), + ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY); + }); test(`${permission} key: try to get raw index and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect(client.getRawIndex(indexNoPk.uid)).rejects.toHaveProperty( 'cause.code', - ErrorStatusCode.INVALID_API_KEY - ) - }) + ErrorStatusCode.INVALID_API_KEY, + ); + }); test(`${permission} key: try to delete index and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect(client.index(indexPk.uid).delete()).rejects.toHaveProperty( 'cause.code', - ErrorStatusCode.INVALID_API_KEY - ) - }) + ErrorStatusCode.INVALID_API_KEY, + ); + }); test(`${permission} key: try to update index and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect( - client.index(indexPk.uid).update({ primaryKey: indexPk.primaryKey }) - ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY) - }) + client.index(indexPk.uid).update({ primaryKey: indexPk.primaryKey }), + ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY); + }); test(`${permission} key: try to get stats and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect(client.index(indexPk.uid).getStats()).rejects.toHaveProperty( 'cause.code', - ErrorStatusCode.INVALID_API_KEY - ) - }) - } -) + ErrorStatusCode.INVALID_API_KEY, + ); + }); + }, +); describe.each([{ permission: 'No' }])( 'Test on routes without an API key', ({ permission }) => { beforeEach(() => { - return clearAllIndexes(config) - }) + return clearAllIndexes(config); + }); test(`${permission} key: try to get all indexes and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect(client.getIndexes()).rejects.toHaveProperty( 'cause.code', - ErrorStatusCode.MISSING_AUTHORIZATION_HEADER - ) - }) + ErrorStatusCode.MISSING_AUTHORIZATION_HEADER, + ); + }); test(`${permission} key: try to get index info and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect( - client.index(indexNoPk.uid).getRawInfo() + client.index(indexNoPk.uid).getRawInfo(), ).rejects.toHaveProperty( 'cause.code', - ErrorStatusCode.MISSING_AUTHORIZATION_HEADER - ) - }) + ErrorStatusCode.MISSING_AUTHORIZATION_HEADER, + ); + }); test(`${permission} key: try to get raw index and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect(client.getRawIndex(indexNoPk.uid)).rejects.toHaveProperty( 'cause.code', - ErrorStatusCode.MISSING_AUTHORIZATION_HEADER - ) - }) + ErrorStatusCode.MISSING_AUTHORIZATION_HEADER, + ); + }); test(`${permission} key: try to delete index and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect(client.index(indexPk.uid).delete()).rejects.toHaveProperty( 'cause.code', - ErrorStatusCode.MISSING_AUTHORIZATION_HEADER - ) - }) + ErrorStatusCode.MISSING_AUTHORIZATION_HEADER, + ); + }); test(`${permission} key: try to update index and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect( - client.index(indexPk.uid).update({ primaryKey: indexPk.primaryKey }) + client.index(indexPk.uid).update({ primaryKey: indexPk.primaryKey }), ).rejects.toHaveProperty( 'cause.code', - ErrorStatusCode.MISSING_AUTHORIZATION_HEADER - ) - }) - } -) + ErrorStatusCode.MISSING_AUTHORIZATION_HEADER, + ); + }); + }, +); describe.each([ { host: BAD_HOST, trailing: false }, @@ -499,60 +501,60 @@ describe.each([ { host: `${BAD_HOST}/trailing/`, trailing: true }, ])('Tests on url construction', ({ host, trailing }) => { test(`Test getStats route`, async () => { - const route = `indexes/${indexPk.uid}/stats` - const client = new MeiliSearch({ host }) - const strippedHost = trailing ? host.slice(0, -1) : host + 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` - ) - }) + `Request to ${strippedHost}/${route} has failed`, + ); + }); test(`Test getRawInfo route`, async () => { - const route = `indexes/${indexPk.uid}` - const client = new MeiliSearch({ host }) - const strippedHost = trailing ? host.slice(0, -1) : host + 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` - ) + `Request to ${strippedHost}/${route} has failed`, + ); await expect(client.index(indexPk.uid).getRawInfo()).rejects.toHaveProperty( 'name', - 'MeiliSearchRequestError' - ) - }) + 'MeiliSearchRequestError', + ); + }); test(`Test getRawIndex route`, async () => { - const route = `indexes/${indexPk.uid}` - const client = new MeiliSearch({ host }) - const strippedHost = trailing ? host.slice(0, -1) : host + 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` - ) + `Request to ${strippedHost}/${route} has failed`, + ); await expect(client.getRawIndex(indexPk.uid)).rejects.toHaveProperty( 'name', - 'MeiliSearchRequestError' - ) - }) + 'MeiliSearchRequestError', + ); + }); test(`Test updateIndex route`, async () => { - const route = `indexes/${indexPk.uid}` - const client = new MeiliSearch({ host }) - const strippedHost = trailing ? host.slice(0, -1) : host + 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` - ) - }) + `Request to ${strippedHost}/${route} has failed`, + ); + }); test(`Test delete index route`, async () => { - const route = `indexes/${indexPk.uid}` - const client = new MeiliSearch({ host }) - const strippedHost = trailing ? host.slice(0, -1) : host + 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` - ) - }) -}) + `Request to ${strippedHost}/${route} has failed`, + ); + }); +}); diff --git a/tests/keys.test.ts b/tests/keys.test.ts index 65fc22a9b..ff171698d 100644 --- a/tests/keys.test.ts +++ b/tests/keys.test.ts @@ -1,112 +1,112 @@ -import MeiliSearch from '../src/browser' -import { ErrorStatusCode } from '../src/types' +import MeiliSearch from '../src/browser'; +import { ErrorStatusCode } from '../src/types'; import { clearAllIndexes, config, getClient, getKey, HOST, -} from './utils/meilisearch-test-utils' +} from './utils/meilisearch-test-utils'; beforeEach(async () => { - await clearAllIndexes(config) -}) + await clearAllIndexes(config); +}); afterAll(() => { - return clearAllIndexes(config) -}) + return clearAllIndexes(config); +}); describe.each([{ permission: 'Master' }, { permission: 'Admin' }])( 'Test on keys', ({ permission }) => { beforeEach(async () => { - const client = await getClient('Master') - await clearAllIndexes(config) + const client = await getClient('Master'); + await clearAllIndexes(config); - const keys = await client.getKeys() + const keys = await client.getKeys(); const customKeys = keys.results.filter( (key) => key.name !== 'Default Search API Key' && - key.name !== 'Default Admin API Key' - ) + key.name !== 'Default Admin API Key', + ); // Delete all custom keys - await Promise.all(customKeys.map((key) => client.deleteKey(key.uid))) - }) + await Promise.all(customKeys.map((key) => client.deleteKey(key.uid))); + }); test(`${permission} key: get keys`, async () => { - const client = await getClient(permission) - const keys = await client.getKeys() + const client = await getClient(permission); + const keys = await client.getKeys(); const searchKey = keys.results.find( - (key: any) => key.name === 'Default Search API Key' - ) + (key: any) => key.name === 'Default Search API Key', + ); - expect(searchKey).toBeDefined() + expect(searchKey).toBeDefined(); expect(searchKey).toHaveProperty( 'description', - 'Use it to search from the frontend' - ) - expect(searchKey).toHaveProperty('key') - expect(searchKey).toHaveProperty('actions') - expect(searchKey).toHaveProperty('indexes') - expect(searchKey).toHaveProperty('expiresAt', null) - expect(searchKey).toHaveProperty('createdAt') - expect(searchKey?.createdAt).toBeInstanceOf(Date) - expect(searchKey).toHaveProperty('updatedAt') - expect(searchKey?.updatedAt).toBeInstanceOf(Date) + 'Use it to search from the frontend', + ); + expect(searchKey).toHaveProperty('key'); + expect(searchKey).toHaveProperty('actions'); + expect(searchKey).toHaveProperty('indexes'); + expect(searchKey).toHaveProperty('expiresAt', null); + expect(searchKey).toHaveProperty('createdAt'); + expect(searchKey?.createdAt).toBeInstanceOf(Date); + expect(searchKey).toHaveProperty('updatedAt'); + expect(searchKey?.updatedAt).toBeInstanceOf(Date); const adminKey = keys.results.find( - (key: any) => key.name === 'Default Admin API Key' - ) + (key: any) => key.name === 'Default Admin API Key', + ); - expect(adminKey).toBeDefined() + expect(adminKey).toBeDefined(); expect(adminKey).toHaveProperty( 'description', - 'Use it for anything that is not a search operation. Caution! Do not expose it on a public frontend' - ) - expect(adminKey).toHaveProperty('key') - expect(adminKey).toHaveProperty('actions') - expect(adminKey).toHaveProperty('indexes') - expect(adminKey).toHaveProperty('expiresAt', null) - expect(adminKey).toHaveProperty('createdAt') - expect(searchKey?.createdAt).toBeInstanceOf(Date) - expect(adminKey).toHaveProperty('updatedAt') - expect(searchKey?.updatedAt).toBeInstanceOf(Date) - }) + 'Use it for anything that is not a search operation. Caution! Do not expose it on a public frontend', + ); + expect(adminKey).toHaveProperty('key'); + expect(adminKey).toHaveProperty('actions'); + expect(adminKey).toHaveProperty('indexes'); + expect(adminKey).toHaveProperty('expiresAt', null); + expect(adminKey).toHaveProperty('createdAt'); + expect(searchKey?.createdAt).toBeInstanceOf(Date); + expect(adminKey).toHaveProperty('updatedAt'); + expect(searchKey?.updatedAt).toBeInstanceOf(Date); + }); test(`${permission} key: get keys with pagination`, async () => { - const client = await getClient(permission) - const keys = await client.getKeys({ limit: 1, offset: 2 }) + const client = await getClient(permission); + const keys = await client.getKeys({ limit: 1, offset: 2 }); - expect(keys.limit).toEqual(1) - expect(keys.offset).toEqual(2) - expect(keys.total).toEqual(2) - }) + expect(keys.limit).toEqual(1); + expect(keys.offset).toEqual(2); + expect(keys.total).toEqual(2); + }); test(`${permission} key: get on key`, async () => { - const client = await getClient(permission) - const apiKey = await getKey('Admin') + const client = await getClient(permission); + const apiKey = await getKey('Admin'); - const key = await client.getKey(apiKey) + const key = await client.getKey(apiKey); - expect(key).toBeDefined() + expect(key).toBeDefined(); expect(key).toHaveProperty( 'description', - 'Use it for anything that is not a search operation. Caution! Do not expose it on a public frontend' - ) - expect(key).toHaveProperty('key') - expect(key).toHaveProperty('actions') - expect(key).toHaveProperty('indexes') - expect(key).toHaveProperty('expiresAt', null) - expect(key).toHaveProperty('createdAt') - expect(key).toHaveProperty('updatedAt') - }) + 'Use it for anything that is not a search operation. Caution! Do not expose it on a public frontend', + ); + expect(key).toHaveProperty('key'); + expect(key).toHaveProperty('actions'); + expect(key).toHaveProperty('indexes'); + expect(key).toHaveProperty('expiresAt', null); + expect(key).toHaveProperty('createdAt'); + expect(key).toHaveProperty('updatedAt'); + }); test(`${permission} key: create key with no expiresAt`, async () => { - const client = await getClient(permission) - const uid = '3db051e0-423d-4b5c-a63a-f82a7043dce6' + const client = await getClient(permission); + const uid = '3db051e0-423d-4b5c-a63a-f82a7043dce6'; const key = await client.createKey({ uid, @@ -114,17 +114,17 @@ describe.each([{ permission: 'Master' }, { permission: 'Admin' }])( actions: ['documents.add'], indexes: ['products'], expiresAt: null, - }) + }); - expect(key).toBeDefined() - expect(key).toHaveProperty('description', 'Indexing Products API key') - expect(key).toHaveProperty('uid', uid) - expect(key).toHaveProperty('expiresAt', null) - }) + expect(key).toBeDefined(); + expect(key).toHaveProperty('description', 'Indexing Products API key'); + expect(key).toHaveProperty('uid', uid); + expect(key).toHaveProperty('expiresAt', null); + }); test(`${permission} key: create key with actions using wildcards to provide rights`, async () => { - const client = await getClient(permission) - const uid = '3db051e0-423d-4b5c-a63a-f82a7043dce6' + const client = await getClient(permission); + const uid = '3db051e0-423d-4b5c-a63a-f82a7043dce6'; const key = await client.createKey({ uid, @@ -132,126 +132,126 @@ describe.each([{ permission: 'Master' }, { permission: 'Admin' }])( actions: ['indexes.*', 'tasks.*', 'documents.*'], indexes: ['wildcard_keys_permission'], expiresAt: null, - }) + }); - const newClient = new MeiliSearch({ host: HOST, apiKey: key.key }) - await newClient.createIndex('wildcard_keys_permission') // test index creation + const newClient = new MeiliSearch({ host: HOST, apiKey: key.key }); + await newClient.createIndex('wildcard_keys_permission'); // test index creation const taskInfo = await newClient .index('wildcard_keys_permission') - .addDocuments([{ id: 1 }]) // test document addition - const task = await newClient.waitForTask(taskInfo.taskUid) // test fetching of tasks + .addDocuments([{ id: 1 }]); // test document addition + const task = await newClient.waitForTask(taskInfo.taskUid); // test fetching of tasks - expect(key).toBeDefined() - expect(task.status).toBe('succeeded') - expect(key).toHaveProperty('description', 'Indexing Products API key') - expect(key).toHaveProperty('uid', uid) - expect(key).toHaveProperty('expiresAt', null) - }) + expect(key).toBeDefined(); + expect(task.status).toBe('succeeded'); + expect(key).toHaveProperty('description', 'Indexing Products API key'); + expect(key).toHaveProperty('uid', uid); + expect(key).toHaveProperty('expiresAt', null); + }); test(`${permission} key: create key with an expiresAt`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const key = await client.createKey({ description: 'Indexing Products API key', actions: ['documents.add'], indexes: ['products'], expiresAt: new Date('2050-11-13T00:00:00Z'), // Test will fail in 2050 - }) + }); - expect(key).toBeDefined() - expect(key).toHaveProperty('description', 'Indexing Products API key') - expect(key).toHaveProperty('expiresAt', '2050-11-13T00:00:00Z') - }) + expect(key).toBeDefined(); + expect(key).toHaveProperty('description', 'Indexing Products API key'); + expect(key).toHaveProperty('expiresAt', '2050-11-13T00:00:00Z'); + }); test(`${permission} key: update a key`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const key = await client.createKey({ description: 'Indexing Products API key', actions: ['documents.add'], indexes: ['products'], expiresAt: new Date('2050-11-13T00:00:00Z'), // Test will fail in 2050 - }) + }); const updatedKey = await client.updateKey(key.key, { description: 'Indexing Products API key 2', name: 'Product admin', - }) + }); - expect(updatedKey).toBeDefined() + expect(updatedKey).toBeDefined(); expect(updatedKey).toHaveProperty( 'description', - 'Indexing Products API key 2' - ) - expect(updatedKey).toHaveProperty('name', 'Product admin') - }) + 'Indexing Products API key 2', + ); + expect(updatedKey).toHaveProperty('name', 'Product admin'); + }); test(`${permission} key: delete a key`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const key = await client.createKey({ description: 'Indexing Products API key', actions: ['documents.add'], indexes: ['products'], expiresAt: new Date('2050-11-13T00:00:00Z'), // Test will fail in 2050 - }) + }); - const deletedKey = await client.deleteKey(key.key) + const deletedKey = await client.deleteKey(key.key); - expect(deletedKey).toBeUndefined() - }) - } -) + expect(deletedKey).toBeUndefined(); + }); + }, +); describe.each([{ permission: 'Search' }])( 'Test on keys with search key', ({ permission }) => { test(`${permission} key: get keys denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect(client.getKeys()).rejects.toHaveProperty( 'cause.code', - ErrorStatusCode.INVALID_API_KEY - ) - }) + ErrorStatusCode.INVALID_API_KEY, + ); + }); test(`${permission} key: create key denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect( client.createKey({ description: 'Indexing Products API key', actions: ['documents.add'], indexes: ['products'], expiresAt: null, - }) - ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY) - }) - } -) + }), + ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY); + }); + }, +); describe.each([{ permission: 'No' }])( 'Test on keys with No key', ({ permission }) => { test(`${permission} key: get keys denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect(client.getKeys()).rejects.toHaveProperty( 'cause.code', - ErrorStatusCode.MISSING_AUTHORIZATION_HEADER - ) - }) + ErrorStatusCode.MISSING_AUTHORIZATION_HEADER, + ); + }); test(`${permission} key: create key denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect( client.createKey({ description: 'Indexing Products API key', actions: ['documents.add'], indexes: ['products'], expiresAt: null, - }) + }), ).rejects.toHaveProperty( 'cause.code', - ErrorStatusCode.MISSING_AUTHORIZATION_HEADER - ) - }) - } -) + ErrorStatusCode.MISSING_AUTHORIZATION_HEADER, + ); + }); + }, +); diff --git a/tests/non_separator_tokens.test.ts b/tests/non_separator_tokens.test.ts index 8feebd97f..6bf42ddb7 100644 --- a/tests/non_separator_tokens.test.ts +++ b/tests/non_separator_tokens.test.ts @@ -1,4 +1,4 @@ -import { EnqueuedTask } from '../src/enqueued-task' +import { EnqueuedTask } from '../src/enqueued-task'; import { clearAllIndexes, config, @@ -6,81 +6,81 @@ import { MeiliSearch, getClient, dataset, -} from './utils/meilisearch-test-utils' +} from './utils/meilisearch-test-utils'; const index = { uid: 'movies_test', -} +}; -jest.setTimeout(100 * 1000) +jest.setTimeout(100 * 1000); afterAll(() => { - return clearAllIndexes(config) -}) + return clearAllIndexes(config); +}); describe.each([{ permission: 'Master' }, { permission: 'Admin' }])( 'Test on non separator tokens', ({ permission }) => { beforeEach(async () => { - const client = await getClient('Master') - const { taskUid } = await client.index(index.uid).addDocuments(dataset) - await client.waitForTask(taskUid) - }) + const client = await getClient('Master'); + const { taskUid } = await client.index(index.uid).addDocuments(dataset); + await client.waitForTask(taskUid); + }); test(`${permission} key: Get default non separator tokens`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const response: string[] = await client .index(index.uid) - .getNonSeparatorTokens() + .getNonSeparatorTokens(); - expect(response).toEqual([]) - }) + expect(response).toEqual([]); + }); test(`${permission} key: Update non separator tokens`, async () => { - const client = await getClient(permission) - const newNonSeparatorTokens = ['&sep', '/', '|'] + const client = await getClient(permission); + const newNonSeparatorTokens = ['&sep', '/', '|']; const task: EnqueuedTask = await client .index(index.uid) - .updateNonSeparatorTokens(newNonSeparatorTokens) - await client.index(index.uid).waitForTask(task.taskUid) + .updateNonSeparatorTokens(newNonSeparatorTokens); + await client.index(index.uid).waitForTask(task.taskUid); const response: string[] = await client .index(index.uid) - .getNonSeparatorTokens() + .getNonSeparatorTokens(); - expect(response).toEqual(newNonSeparatorTokens) - }) + expect(response).toEqual(newNonSeparatorTokens); + }); test(`${permission} key: Update non separator tokens with null value`, async () => { - const client = await getClient(permission) - const newNonSeparatorTokens = null + const client = await getClient(permission); + const newNonSeparatorTokens = null; const task: EnqueuedTask = await client .index(index.uid) - .updateNonSeparatorTokens(newNonSeparatorTokens) - await client.index(index.uid).waitForTask(task.taskUid) + .updateNonSeparatorTokens(newNonSeparatorTokens); + await client.index(index.uid).waitForTask(task.taskUid); const response: string[] = await client .index(index.uid) - .getNonSeparatorTokens() + .getNonSeparatorTokens(); - expect(response).toEqual([]) - }) + expect(response).toEqual([]); + }); test(`${permission} key: Reset NonSeparator tokens`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const task: EnqueuedTask = await client .index(index.uid) - .resetNonSeparatorTokens() - await client.index(index.uid).waitForTask(task.taskUid) + .resetNonSeparatorTokens(); + await client.index(index.uid).waitForTask(task.taskUid); const response: string[] = await client .index(index.uid) - .getNonSeparatorTokens() + .getNonSeparatorTokens(); - expect(response).toEqual([]) - }) - } -) + expect(response).toEqual([]); + }); + }, +); describe.each([ { host: BAD_HOST, trailing: false }, @@ -88,38 +88,38 @@ describe.each([ { host: `${BAD_HOST}/trailing/`, trailing: true }, ])('Tests on url construction', ({ host, trailing }) => { test(`Test getNonSeparatorTokens route`, async () => { - const route = `indexes/${index.uid}/settings/non-separator-tokens` - const client = new MeiliSearch({ host }) - const strippedHost = trailing ? host.slice(0, -1) : host + const route = `indexes/${index.uid}/settings/non-separator-tokens`; + const client = new MeiliSearch({ host }); + const strippedHost = trailing ? host.slice(0, -1) : host; await expect( - client.index(index.uid).getNonSeparatorTokens() + client.index(index.uid).getNonSeparatorTokens(), ).rejects.toHaveProperty( 'message', - `Request to ${strippedHost}/${route} has failed` - ) - }) + `Request to ${strippedHost}/${route} has failed`, + ); + }); test(`Test updateNonSeparatorTokens route`, async () => { - const route = `indexes/${index.uid}/settings/non-separator-tokens` - const client = new MeiliSearch({ host }) - const strippedHost = trailing ? host.slice(0, -1) : host + const route = `indexes/${index.uid}/settings/non-separator-tokens`; + const client = new MeiliSearch({ host }); + const strippedHost = trailing ? host.slice(0, -1) : host; await expect( - client.index(index.uid).updateNonSeparatorTokens([]) + client.index(index.uid).updateNonSeparatorTokens([]), ).rejects.toHaveProperty( 'message', - `Request to ${strippedHost}/${route} has failed` - ) - }) + `Request to ${strippedHost}/${route} has failed`, + ); + }); test(`Test resetNonSeparatorTokens route`, async () => { - const route = `indexes/${index.uid}/settings/non-separator-tokens` - const client = new MeiliSearch({ host }) - const strippedHost = trailing ? host.slice(0, -1) : host + const route = `indexes/${index.uid}/settings/non-separator-tokens`; + const client = new MeiliSearch({ host }); + const strippedHost = trailing ? host.slice(0, -1) : host; await expect( - client.index(index.uid).resetNonSeparatorTokens() + client.index(index.uid).resetNonSeparatorTokens(), ).rejects.toHaveProperty( 'message', - `Request to ${strippedHost}/${route} has failed` - ) - }) -}) + `Request to ${strippedHost}/${route} has failed`, + ); + }); +}); diff --git a/tests/pagination.test.ts b/tests/pagination.test.ts index 160342835..1f325edbd 100644 --- a/tests/pagination.test.ts +++ b/tests/pagination.test.ts @@ -1,4 +1,4 @@ -import { ErrorStatusCode } from '../src/types' +import { ErrorStatusCode } from '../src/types'; import { clearAllIndexes, config, @@ -6,152 +6,156 @@ import { MeiliSearch, getClient, dataset, -} from './utils/meilisearch-test-utils' +} from './utils/meilisearch-test-utils'; const index = { uid: 'movies_test', -} +}; -jest.setTimeout(100 * 1000) +jest.setTimeout(100 * 1000); afterAll(() => { - return clearAllIndexes(config) -}) + return clearAllIndexes(config); +}); describe.each([{ permission: 'Master' }, { permission: 'Admin' }])( 'Test on pagination', ({ permission }) => { beforeEach(async () => { - await clearAllIndexes(config) - const client = await getClient('Master') - const { taskUid } = await client.index(index.uid).addDocuments(dataset) - await client.waitForTask(taskUid) - }) + await clearAllIndexes(config); + const client = await getClient('Master'); + const { taskUid } = await client.index(index.uid).addDocuments(dataset); + await client.waitForTask(taskUid); + }); test(`${permission} key: Get default pagination settings`, async () => { - const client = await getClient(permission) - const response = await client.index(index.uid).getPagination() + const client = await getClient(permission); + const response = await client.index(index.uid).getPagination(); - expect(response).toEqual({ maxTotalHits: 1000 }) - }) + expect(response).toEqual({ maxTotalHits: 1000 }); + }); test(`${permission} key: Update pagination`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const newPagination = { maxTotalHits: 100, - } - const task = await client.index(index.uid).updatePagination(newPagination) - await client.waitForTask(task.taskUid) + }; + const task = await client + .index(index.uid) + .updatePagination(newPagination); + await client.waitForTask(task.taskUid); - const response = await client.index(index.uid).getPagination() + const response = await client.index(index.uid).getPagination(); - expect(response).toEqual(newPagination) - }) + expect(response).toEqual(newPagination); + }); test(`${permission} key: Update pagination at null`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const newPagination = { maxTotalHits: null, - } - const task = await client.index(index.uid).updatePagination(newPagination) - await client.index(index.uid).waitForTask(task.taskUid) + }; + const task = await client + .index(index.uid) + .updatePagination(newPagination); + await client.index(index.uid).waitForTask(task.taskUid); - const response = await client.index(index.uid).getPagination() + const response = await client.index(index.uid).getPagination(); - expect(response).toEqual({ maxTotalHits: 1000 }) - }) + expect(response).toEqual({ maxTotalHits: 1000 }); + }); test(`${permission} key: Reset pagination`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const newPagination = { maxTotalHits: 100, - } + }; const updateTask = await client .index(index.uid) - .updatePagination(newPagination) - await client.waitForTask(updateTask.taskUid) - const task = await client.index(index.uid).resetPagination() - await client.waitForTask(task.taskUid) + .updatePagination(newPagination); + await client.waitForTask(updateTask.taskUid); + const task = await client.index(index.uid).resetPagination(); + await client.waitForTask(task.taskUid); - const response = await client.index(index.uid).getPagination() + const response = await client.index(index.uid).getPagination(); - expect(response).toEqual({ maxTotalHits: 1000 }) - }) - } -) + expect(response).toEqual({ maxTotalHits: 1000 }); + }); + }, +); describe.each([{ permission: 'Search' }])( 'Test on pagination', ({ permission }) => { beforeEach(async () => { - const client = await getClient('Master') - const { taskUid } = await client.createIndex(index.uid) - await client.waitForTask(taskUid) - }) + const client = await getClient('Master'); + const { taskUid } = await client.createIndex(index.uid); + await client.waitForTask(taskUid); + }); test(`${permission} key: try to get pagination and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect( - client.index(index.uid).getPagination() - ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY) - }) + client.index(index.uid).getPagination(), + ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY); + }); test(`${permission} key: try to update pagination and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect( - client.index(index.uid).updatePagination({ maxTotalHits: 10 }) - ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY) - }) + client.index(index.uid).updatePagination({ maxTotalHits: 10 }), + ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY); + }); test(`${permission} key: try to reset pagination and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect( - client.index(index.uid).resetPagination() - ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY) - }) - } -) + client.index(index.uid).resetPagination(), + ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY); + }); + }, +); describe.each([{ permission: 'No' }])( 'Test on pagination', ({ permission }) => { beforeAll(async () => { - const client = await getClient('Master') - const { taskUid } = await client.createIndex(index.uid) - await client.waitForTask(taskUid) - }) + const client = await getClient('Master'); + const { taskUid } = await client.createIndex(index.uid); + await client.waitForTask(taskUid); + }); test(`${permission} key: try to get pagination and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect( - client.index(index.uid).getPagination() + client.index(index.uid).getPagination(), ).rejects.toHaveProperty( 'cause.code', - ErrorStatusCode.MISSING_AUTHORIZATION_HEADER - ) - }) + ErrorStatusCode.MISSING_AUTHORIZATION_HEADER, + ); + }); test(`${permission} key: try to update pagination and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect( - client.index(index.uid).updatePagination({ maxTotalHits: 10 }) + client.index(index.uid).updatePagination({ maxTotalHits: 10 }), ).rejects.toHaveProperty( 'cause.code', - ErrorStatusCode.MISSING_AUTHORIZATION_HEADER - ) - }) + ErrorStatusCode.MISSING_AUTHORIZATION_HEADER, + ); + }); test(`${permission} key: try to reset pagination and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect( - client.index(index.uid).resetPagination() + client.index(index.uid).resetPagination(), ).rejects.toHaveProperty( 'cause.code', - ErrorStatusCode.MISSING_AUTHORIZATION_HEADER - ) - }) - } -) + ErrorStatusCode.MISSING_AUTHORIZATION_HEADER, + ); + }); + }, +); describe.each([ { host: BAD_HOST, trailing: false }, @@ -159,38 +163,38 @@ describe.each([ { host: `${BAD_HOST}/trailing/`, trailing: true }, ])('Tests on url construction', ({ host, trailing }) => { test(`Test getPagination route`, async () => { - const route = `indexes/${index.uid}/settings/pagination` - const client = new MeiliSearch({ host }) - const strippedHost = trailing ? host.slice(0, -1) : host + const route = `indexes/${index.uid}/settings/pagination`; + const client = new MeiliSearch({ host }); + const strippedHost = trailing ? host.slice(0, -1) : host; await expect( - client.index(index.uid).getPagination() + client.index(index.uid).getPagination(), ).rejects.toHaveProperty( 'message', - `Request to ${strippedHost}/${route} has failed` - ) - }) + `Request to ${strippedHost}/${route} has failed`, + ); + }); test(`Test updatePagination route`, async () => { - const route = `indexes/${index.uid}/settings/pagination` - const client = new MeiliSearch({ host }) - const strippedHost = trailing ? host.slice(0, -1) : host + const route = `indexes/${index.uid}/settings/pagination`; + const client = new MeiliSearch({ host }); + const strippedHost = trailing ? host.slice(0, -1) : host; await expect( - client.index(index.uid).updatePagination({ maxTotalHits: null }) + client.index(index.uid).updatePagination({ maxTotalHits: null }), ).rejects.toHaveProperty( 'message', - `Request to ${strippedHost}/${route} has failed` - ) - }) + `Request to ${strippedHost}/${route} has failed`, + ); + }); test(`Test resetPagination route`, async () => { - const route = `indexes/${index.uid}/settings/pagination` - const client = new MeiliSearch({ host }) - const strippedHost = trailing ? host.slice(0, -1) : host + const route = `indexes/${index.uid}/settings/pagination`; + const client = new MeiliSearch({ host }); + const strippedHost = trailing ? host.slice(0, -1) : host; await expect( - client.index(index.uid).resetPagination() + client.index(index.uid).resetPagination(), ).rejects.toHaveProperty( 'message', - `Request to ${strippedHost}/${route} has failed` - ) - }) -}) + `Request to ${strippedHost}/${route} has failed`, + ); + }); +}); diff --git a/tests/proximity_precision.test.ts b/tests/proximity_precision.test.ts index fe92844ce..1c885d4ba 100644 --- a/tests/proximity_precision.test.ts +++ b/tests/proximity_precision.test.ts @@ -1,4 +1,4 @@ -import { EnqueuedTask } from '../src/enqueued-task' +import { EnqueuedTask } from '../src/enqueued-task'; import { clearAllIndexes, config, @@ -6,81 +6,81 @@ import { MeiliSearch, getClient, dataset, -} from './utils/meilisearch-test-utils' +} from './utils/meilisearch-test-utils'; const index = { uid: 'movies_test', -} +}; -jest.setTimeout(100 * 1000) +jest.setTimeout(100 * 1000); afterAll(() => { - return clearAllIndexes(config) -}) + return clearAllIndexes(config); +}); describe.each([{ permission: 'Master' }, { permission: 'Admin' }])( 'Test on proximity precision', ({ permission }) => { beforeEach(async () => { - const client = await getClient('Master') - const { taskUid } = await client.index(index.uid).addDocuments(dataset) - await client.waitForTask(taskUid) - }) + const client = await getClient('Master'); + const { taskUid } = await client.index(index.uid).addDocuments(dataset); + await client.waitForTask(taskUid); + }); test(`${permission} key: Get default proximity precision`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const response: string = await client .index(index.uid) - .getProximityPrecision() + .getProximityPrecision(); - expect(response).toEqual('byWord') - }) + expect(response).toEqual('byWord'); + }); test(`${permission} key: Update proximity precision with 'byAttribute' value`, async () => { - const client = await getClient(permission) - const newProximityPrecision = 'byAttribute' + const client = await getClient(permission); + const newProximityPrecision = 'byAttribute'; const task: EnqueuedTask = await client .index(index.uid) - .updateProximityPrecision(newProximityPrecision) - await client.index(index.uid).waitForTask(task.taskUid) + .updateProximityPrecision(newProximityPrecision); + await client.index(index.uid).waitForTask(task.taskUid); const response: string = await client .index(index.uid) - .getProximityPrecision() + .getProximityPrecision(); - expect(response).toEqual(newProximityPrecision) - }) + expect(response).toEqual(newProximityPrecision); + }); test(`${permission} key: Update proximity precision with 'byWord' value`, async () => { - const client = await getClient(permission) - const newProximityPrecision = 'byWord' + const client = await getClient(permission); + const newProximityPrecision = 'byWord'; const task: EnqueuedTask = await client .index(index.uid) - .updateProximityPrecision(newProximityPrecision) - await client.index(index.uid).waitForTask(task.taskUid) + .updateProximityPrecision(newProximityPrecision); + await client.index(index.uid).waitForTask(task.taskUid); const response: string = await client .index(index.uid) - .getProximityPrecision() + .getProximityPrecision(); - expect(response).toEqual(newProximityPrecision) - }) + expect(response).toEqual(newProximityPrecision); + }); test(`${permission} key: Reset proximity precision`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const task: EnqueuedTask = await client .index(index.uid) - .resetProximityPrecision() - await client.index(index.uid).waitForTask(task.taskUid) + .resetProximityPrecision(); + await client.index(index.uid).waitForTask(task.taskUid); const response: string = await client .index(index.uid) - .getProximityPrecision() + .getProximityPrecision(); - expect(response).toEqual('byWord') - }) - } -) + expect(response).toEqual('byWord'); + }); + }, +); describe.each([ { host: BAD_HOST, trailing: false }, @@ -88,38 +88,38 @@ describe.each([ { host: `${BAD_HOST}/trailing/`, trailing: true }, ])('Tests on url construction', ({ host, trailing }) => { test(`Test getProximityPrecision route`, async () => { - const route = `indexes/${index.uid}/settings/proximity-precision` - const client = new MeiliSearch({ host }) - const strippedHost = trailing ? host.slice(0, -1) : host + const route = `indexes/${index.uid}/settings/proximity-precision`; + const client = new MeiliSearch({ host }); + const strippedHost = trailing ? host.slice(0, -1) : host; await expect( - client.index(index.uid).getProximityPrecision() + client.index(index.uid).getProximityPrecision(), ).rejects.toHaveProperty( 'message', - `Request to ${strippedHost}/${route} has failed` - ) - }) + `Request to ${strippedHost}/${route} has failed`, + ); + }); test(`Test updateProximityPrecision route`, async () => { - const route = `indexes/${index.uid}/settings/proximity-precision` - const client = new MeiliSearch({ host }) - const strippedHost = trailing ? host.slice(0, -1) : host + const route = `indexes/${index.uid}/settings/proximity-precision`; + const client = new MeiliSearch({ host }); + const strippedHost = trailing ? host.slice(0, -1) : host; await expect( - client.index(index.uid).updateProximityPrecision('byAttribute') + client.index(index.uid).updateProximityPrecision('byAttribute'), ).rejects.toHaveProperty( 'message', - `Request to ${strippedHost}/${route} has failed` - ) - }) + `Request to ${strippedHost}/${route} has failed`, + ); + }); test(`Test resetProximityPrecision route`, async () => { - const route = `indexes/${index.uid}/settings/proximity-precision` - const client = new MeiliSearch({ host }) - const strippedHost = trailing ? host.slice(0, -1) : host + const route = `indexes/${index.uid}/settings/proximity-precision`; + const client = new MeiliSearch({ host }); + const strippedHost = trailing ? host.slice(0, -1) : host; await expect( - client.index(index.uid).resetProximityPrecision() + client.index(index.uid).resetProximityPrecision(), ).rejects.toHaveProperty( 'message', - `Request to ${strippedHost}/${route} has failed` - ) - }) -}) + `Request to ${strippedHost}/${route} has failed`, + ); + }); +}); diff --git a/tests/ranking_rules.test.ts b/tests/ranking_rules.test.ts index 6cdb24126..4cca63554 100644 --- a/tests/ranking_rules.test.ts +++ b/tests/ranking_rules.test.ts @@ -1,5 +1,5 @@ -import { ErrorStatusCode } from '../src/types' -import { EnqueuedTask } from '../src/enqueued-task' +import { ErrorStatusCode } from '../src/types'; +import { EnqueuedTask } from '../src/enqueued-task'; import { clearAllIndexes, config, @@ -7,11 +7,11 @@ import { MeiliSearch, getClient, dataset, -} from './utils/meilisearch-test-utils' +} from './utils/meilisearch-test-utils'; const index = { uid: 'movies_test', -} +}; const defaultRankingRules = [ 'words', @@ -20,137 +20,145 @@ const defaultRankingRules = [ 'attribute', 'sort', 'exactness', -] +]; -jest.setTimeout(100 * 1000) +jest.setTimeout(100 * 1000); afterAll(() => { - return clearAllIndexes(config) -}) + return clearAllIndexes(config); +}); describe.each([{ permission: 'Master' }, { permission: 'Admin' }])( 'Test on ranking rules', ({ permission }) => { beforeEach(async () => { - await clearAllIndexes(config) - const client = await getClient('master') - const { taskUid } = await client.index(index.uid).addDocuments(dataset) - await client.waitForTask(taskUid) - }) + await clearAllIndexes(config); + const client = await getClient('master'); + const { taskUid } = await client.index(index.uid).addDocuments(dataset); + await client.waitForTask(taskUid); + }); test(`${permission} key: Get default ranking rules`, async () => { - const client = await getClient(permission) - const response: string[] = await client.index(index.uid).getRankingRules() - expect(response).toEqual(defaultRankingRules) - }) + const client = await getClient(permission); + const response: string[] = await client + .index(index.uid) + .getRankingRules(); + expect(response).toEqual(defaultRankingRules); + }); test(`${permission} key: Update ranking rules`, async () => { - const client = await getClient(permission) - const newRankingRules = ['title:asc', 'typo', 'description:desc'] + const client = await getClient(permission); + const newRankingRules = ['title:asc', 'typo', 'description:desc']; const task: EnqueuedTask = await client .index(index.uid) - .updateRankingRules(newRankingRules) - await client.index(index.uid).waitForTask(task.taskUid) + .updateRankingRules(newRankingRules); + await client.index(index.uid).waitForTask(task.taskUid); - const response: string[] = await client.index(index.uid).getRankingRules() + const response: string[] = await client + .index(index.uid) + .getRankingRules(); - expect(response).toEqual(newRankingRules) - }) + expect(response).toEqual(newRankingRules); + }); test(`${permission} key: Update ranking rules at null`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const task: EnqueuedTask = await client .index(index.uid) - .updateRankingRules(null) - await client.index(index.uid).waitForTask(task.taskUid) + .updateRankingRules(null); + await client.index(index.uid).waitForTask(task.taskUid); - const response: string[] = await client.index(index.uid).getRankingRules() + const response: string[] = await client + .index(index.uid) + .getRankingRules(); - expect(response).toEqual(defaultRankingRules) - }) + expect(response).toEqual(defaultRankingRules); + }); test(`${permission} key: Reset ranking rules`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const task: EnqueuedTask = await client .index(index.uid) - .resetRankingRules() - await client.index(index.uid).waitForTask(task.taskUid) + .resetRankingRules(); + await client.index(index.uid).waitForTask(task.taskUid); - const response: string[] = await client.index(index.uid).getRankingRules() + const response: string[] = await client + .index(index.uid) + .getRankingRules(); - expect(response).toEqual(defaultRankingRules) - }) - } -) + expect(response).toEqual(defaultRankingRules); + }); + }, +); describe.each([{ permission: 'Search' }])( 'Test on ranking rules', ({ permission }) => { beforeEach(async () => { - await clearAllIndexes(config) - }) + await clearAllIndexes(config); + }); test(`${permission} key: try to get ranking rules and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect( - client.index(index.uid).getRankingRules() - ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY) - }) + client.index(index.uid).getRankingRules(), + ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY); + }); test(`${permission} key: try to update ranking rules and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect( - client.index(index.uid).updateRankingRules([]) - ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY) - }) + client.index(index.uid).updateRankingRules([]), + ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY); + }); test(`${permission} key: try to reset ranking rules and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect( - client.index(index.uid).resetRankingRules() - ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY) - }) - } -) + client.index(index.uid).resetRankingRules(), + ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY); + }); + }, +); describe.each([{ permission: 'No' }])( 'Test on ranking rules', ({ permission }) => { beforeEach(async () => { - await clearAllIndexes(config) - }) + await clearAllIndexes(config); + }); test(`${permission} key: try to get ranking rules and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect( - client.index(index.uid).getRankingRules() + client.index(index.uid).getRankingRules(), ).rejects.toHaveProperty( 'cause.code', - ErrorStatusCode.MISSING_AUTHORIZATION_HEADER - ) - }) + ErrorStatusCode.MISSING_AUTHORIZATION_HEADER, + ); + }); test(`${permission} key: try to update ranking rules and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect( - client.index(index.uid).updateRankingRules([]) + client.index(index.uid).updateRankingRules([]), ).rejects.toHaveProperty( 'cause.code', - ErrorStatusCode.MISSING_AUTHORIZATION_HEADER - ) - }) + ErrorStatusCode.MISSING_AUTHORIZATION_HEADER, + ); + }); test(`${permission} key: try to reset ranking rules and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect( - client.index(index.uid).resetRankingRules() + client.index(index.uid).resetRankingRules(), ).rejects.toHaveProperty( 'cause.code', - ErrorStatusCode.MISSING_AUTHORIZATION_HEADER - ) - }) - } -) + ErrorStatusCode.MISSING_AUTHORIZATION_HEADER, + ); + }); + }, +); describe.each([ { host: BAD_HOST, trailing: false }, @@ -158,38 +166,38 @@ describe.each([ { host: `${BAD_HOST}/trailing/`, trailing: true }, ])('Tests on url construction', ({ host, trailing }) => { test(`Test getRankingRules route`, async () => { - const route = `indexes/${index.uid}/settings/ranking-rules` - const client = new MeiliSearch({ host }) - const strippedHost = trailing ? host.slice(0, -1) : host + const route = `indexes/${index.uid}/settings/ranking-rules`; + const client = new MeiliSearch({ host }); + const strippedHost = trailing ? host.slice(0, -1) : host; await expect( - client.index(index.uid).getRankingRules() + client.index(index.uid).getRankingRules(), ).rejects.toHaveProperty( 'message', - `Request to ${strippedHost}/${route} has failed` - ) - }) + `Request to ${strippedHost}/${route} has failed`, + ); + }); test(`Test updateRankingRules route`, async () => { - const route = `indexes/${index.uid}/settings/ranking-rules` - const client = new MeiliSearch({ host }) - const strippedHost = trailing ? host.slice(0, -1) : host + const route = `indexes/${index.uid}/settings/ranking-rules`; + const client = new MeiliSearch({ host }); + const strippedHost = trailing ? host.slice(0, -1) : host; await expect( - client.index(index.uid).updateRankingRules([]) + client.index(index.uid).updateRankingRules([]), ).rejects.toHaveProperty( 'message', - `Request to ${strippedHost}/${route} has failed` - ) - }) + `Request to ${strippedHost}/${route} has failed`, + ); + }); test(`Test resetRankingRules route`, async () => { - const route = `indexes/${index.uid}/settings/ranking-rules` - const client = new MeiliSearch({ host }) - const strippedHost = trailing ? host.slice(0, -1) : host + const route = `indexes/${index.uid}/settings/ranking-rules`; + const client = new MeiliSearch({ host }); + const strippedHost = trailing ? host.slice(0, -1) : host; await expect( - client.index(index.uid).resetRankingRules() + client.index(index.uid).resetRankingRules(), ).rejects.toHaveProperty( 'message', - `Request to ${strippedHost}/${route} has failed` - ) - }) -}) + `Request to ${strippedHost}/${route} has failed`, + ); + }); +}); diff --git a/tests/raw_document.test.ts b/tests/raw_document.test.ts index 0df31ec65..e2393c520 100644 --- a/tests/raw_document.test.ts +++ b/tests/raw_document.test.ts @@ -2,239 +2,239 @@ import { clearAllIndexes, config, getClient, -} from './utils/meilisearch-test-utils' -import { TaskStatus, ContentTypeEnum } from '../src/types' +} from './utils/meilisearch-test-utils'; +import { TaskStatus, ContentTypeEnum } from '../src/types'; beforeEach(async () => { - await clearAllIndexes(config) -}) + await clearAllIndexes(config); +}); describe.each([{ permission: 'Master' }, { permission: 'Admin' }])( 'Test on raw documents addition using `addDocumentsFromString`', ({ permission }) => { test(`${permission} key: Add documents in CSV format`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const data = `id,title,comment 123,Pride and Prejudice, A great book -546,Le Petit Prince,a french book` +546,Le Petit Prince,a french book`; const { taskUid } = await client .index('csv_index') - .addDocumentsFromString(data, ContentTypeEnum.CSV) - const task = await client.waitForTask(taskUid) + .addDocumentsFromString(data, ContentTypeEnum.CSV); + const task = await client.waitForTask(taskUid); - expect(task.details.receivedDocuments).toBe(2) - expect(task.status).toBe(TaskStatus.TASK_SUCCEEDED) - }) + expect(task.details.receivedDocuments).toBe(2); + expect(task.status).toBe(TaskStatus.TASK_SUCCEEDED); + }); test(`${permission} key: Add documents in CSV format with custom primary key`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const data = `name,title,comment 123,Pride and Prejudice, A great book -546,Le Petit Prince,a french book` +546,Le Petit Prince,a french book`; const { taskUid } = await client .index('csv_index') .addDocumentsFromString(data, ContentTypeEnum.CSV, { primaryKey: 'name', - }) - const task = await client.waitForTask(taskUid) + }); + const task = await client.waitForTask(taskUid); - expect(task.details.receivedDocuments).toBe(2) - expect(task.status).toBe(TaskStatus.TASK_SUCCEEDED) - }) + expect(task.details.receivedDocuments).toBe(2); + expect(task.status).toBe(TaskStatus.TASK_SUCCEEDED); + }); test(`${permission} key: Add documents in CSV format with custom delimiter`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const data = `name;title;comment 123;Pride and Prejudice; A great book -546;Le Petit Prince;a french book` +546;Le Petit Prince;a french book`; const { taskUid } = await client .index('csv_index') .addDocumentsFromString(data, ContentTypeEnum.CSV, { primaryKey: 'name', csvDelimiter: ';', - }) - const task = await client.waitForTask(taskUid) + }); + const task = await client.waitForTask(taskUid); - expect(task.details.receivedDocuments).toBe(2) - expect(task.status).toBe(TaskStatus.TASK_SUCCEEDED) - }) + expect(task.details.receivedDocuments).toBe(2); + expect(task.status).toBe(TaskStatus.TASK_SUCCEEDED); + }); test(`${permission} key: Add documents in JSON lines format`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const data = `{ "id": 123, "title": "Pride and Prejudice", "comment": "A great book" } -{ "id": 456, "title": "Le Petit Prince", "comment": "A french book" }` +{ "id": 456, "title": "Le Petit Prince", "comment": "A french book" }`; const { taskUid } = await client .index('jsonl_index') - .addDocumentsFromString(data, ContentTypeEnum.NDJSON, {}) - const task = await client.waitForTask(taskUid) + .addDocumentsFromString(data, ContentTypeEnum.NDJSON, {}); + const task = await client.waitForTask(taskUid); - expect(task.details.receivedDocuments).toBe(2) - expect(task.status).toBe(TaskStatus.TASK_SUCCEEDED) - }) + expect(task.details.receivedDocuments).toBe(2); + expect(task.status).toBe(TaskStatus.TASK_SUCCEEDED); + }); test(`${permission} key: Add documents in JSON lines with custom primary key`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const data = `{ "name": 123, "title": "Pride and Prejudice", "comment": "A great book" } -{ "name": 456, "title": "Le Petit Prince", "comment": "A french book" }` +{ "name": 456, "title": "Le Petit Prince", "comment": "A french book" }`; const { taskUid } = await client .index('jsonl_index') .addDocumentsFromString(data, ContentTypeEnum.NDJSON, { primaryKey: 'name', - }) - const task = await client.waitForTask(taskUid) + }); + const task = await client.waitForTask(taskUid); - expect(task.details.receivedDocuments).toBe(2) - expect(task.status).toBe(TaskStatus.TASK_SUCCEEDED) - }) + expect(task.details.receivedDocuments).toBe(2); + expect(task.status).toBe(TaskStatus.TASK_SUCCEEDED); + }); test(`${permission} key: Add documents in JSON format`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const data = `[{ "id": 123, "title": "Pride and Prejudice", "comment": "A great book" }, -{ "id": 456, "title": "Le Petit Prince", "comment": "A french book" }]` +{ "id": 456, "title": "Le Petit Prince", "comment": "A french book" }]`; const { taskUid } = await client .index('json_index') - .addDocumentsFromString(data, ContentTypeEnum.JSON) - const task = await client.waitForTask(taskUid) + .addDocumentsFromString(data, ContentTypeEnum.JSON); + const task = await client.waitForTask(taskUid); - expect(task.details.receivedDocuments).toBe(2) - expect(task.status).toBe(TaskStatus.TASK_SUCCEEDED) - }) + expect(task.details.receivedDocuments).toBe(2); + expect(task.status).toBe(TaskStatus.TASK_SUCCEEDED); + }); test(`${permission} key: Add documents in JSON format with custom primary key`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const data = `[{ "name": 123, "title": "Pride and Prejudice", "comment": "A great book" }, -{ "name": 456, "title": "Le Petit Prince", "comment": "A french book" }]` +{ "name": 456, "title": "Le Petit Prince", "comment": "A french book" }]`; const { taskUid } = await client .index('json_index') .addDocumentsFromString(data, ContentTypeEnum.JSON, { primaryKey: 'name', - }) - const task = await client.waitForTask(taskUid) + }); + const task = await client.waitForTask(taskUid); - expect(task.details.receivedDocuments).toBe(2) - expect(task.status).toBe(TaskStatus.TASK_SUCCEEDED) - }) - } -) + expect(task.details.receivedDocuments).toBe(2); + expect(task.status).toBe(TaskStatus.TASK_SUCCEEDED); + }); + }, +); describe.each([{ permission: 'Master' }, { permission: 'Admin' }])( 'Test on raw documents update using `updateDocumentsFromString`', ({ permission }) => { test(`${permission} key: Update documents in CSV format`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const data = `id,title,comment 123,Pride and Prejudice, A great book -546,Le Petit Prince,a french book` +546,Le Petit Prince,a french book`; const { taskUid } = await client .index('csv_index') - .updateDocumentsFromString(data, ContentTypeEnum.CSV) - const task = await client.waitForTask(taskUid) + .updateDocumentsFromString(data, ContentTypeEnum.CSV); + const task = await client.waitForTask(taskUid); - expect(task.details.receivedDocuments).toBe(2) - expect(task.status).toBe(TaskStatus.TASK_SUCCEEDED) - }) + expect(task.details.receivedDocuments).toBe(2); + expect(task.status).toBe(TaskStatus.TASK_SUCCEEDED); + }); test(`${permission} key: Update documents in CSV format with custom primary key`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const data = `name,title,comment 123,Pride and Prejudice, A great book -546,Le Petit Prince,a french book` +546,Le Petit Prince,a french book`; const { taskUid } = await client .index('csv_index') .updateDocumentsFromString(data, ContentTypeEnum.CSV, { primaryKey: 'name', - }) - const task = await client.waitForTask(taskUid) + }); + const task = await client.waitForTask(taskUid); - expect(task.details.receivedDocuments).toBe(2) - expect(task.status).toBe(TaskStatus.TASK_SUCCEEDED) - }) + expect(task.details.receivedDocuments).toBe(2); + expect(task.status).toBe(TaskStatus.TASK_SUCCEEDED); + }); test(`${permission} key: Update documents in CSV format with custom delimiter`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const data = `name;title;comment 123;Pride and Prejudice; A great book -546;Le Petit Prince;a french book` +546;Le Petit Prince;a french book`; const { taskUid } = await client .index('csv_index') .updateDocumentsFromString(data, ContentTypeEnum.CSV, { primaryKey: 'name', csvDelimiter: ';', - }) - const task = await client.waitForTask(taskUid) + }); + const task = await client.waitForTask(taskUid); - expect(task.details.receivedDocuments).toBe(2) - expect(task.status).toBe(TaskStatus.TASK_SUCCEEDED) - }) + expect(task.details.receivedDocuments).toBe(2); + expect(task.status).toBe(TaskStatus.TASK_SUCCEEDED); + }); test(`${permission} key: Update documents in JSON lines format`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const data = `{ "id": 123, "title": "Pride and Prejudice", "comment": "A great book" } -{ "id": 456, "title": "Le Petit Prince", "comment": "A french book" }` +{ "id": 456, "title": "Le Petit Prince", "comment": "A french book" }`; const { taskUid } = await client .index('jsonl_index') - .updateDocumentsFromString(data, ContentTypeEnum.NDJSON) - const task = await client.waitForTask(taskUid) + .updateDocumentsFromString(data, ContentTypeEnum.NDJSON); + const task = await client.waitForTask(taskUid); - expect(task.details.receivedDocuments).toBe(2) - expect(task.status).toBe(TaskStatus.TASK_SUCCEEDED) - }) + expect(task.details.receivedDocuments).toBe(2); + expect(task.status).toBe(TaskStatus.TASK_SUCCEEDED); + }); test(`${permission} key: Update documents in JSON lines with custom primary key`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const data = `{ "name": 123, "title": "Pride and Prejudice", "comment": "A great book" } -{ "name": 456, "title": "Le Petit Prince", "comment": "A french book" }` +{ "name": 456, "title": "Le Petit Prince", "comment": "A french book" }`; const { taskUid } = await client .index('jsonl_index') .updateDocumentsFromString(data, ContentTypeEnum.NDJSON, { primaryKey: 'name', - }) - const task = await client.waitForTask(taskUid) + }); + const task = await client.waitForTask(taskUid); - expect(task.details.receivedDocuments).toBe(2) - expect(task.status).toBe(TaskStatus.TASK_SUCCEEDED) - }) + expect(task.details.receivedDocuments).toBe(2); + expect(task.status).toBe(TaskStatus.TASK_SUCCEEDED); + }); test(`${permission} key: Update documents in JSON format`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const data = `[{ "id": 123, "title": "Pride and Prejudice", "comment": "A great book" }, -{ "id": 456, "title": "Le Petit Prince", "comment": "A french book" }]` +{ "id": 456, "title": "Le Petit Prince", "comment": "A french book" }]`; const { taskUid } = await client .index('json_index') - .updateDocumentsFromString(data, ContentTypeEnum.JSON, {}) - const task = await client.waitForTask(taskUid) + .updateDocumentsFromString(data, ContentTypeEnum.JSON, {}); + const task = await client.waitForTask(taskUid); - expect(task.details.receivedDocuments).toBe(2) - expect(task.status).toBe(TaskStatus.TASK_SUCCEEDED) - }) + expect(task.details.receivedDocuments).toBe(2); + expect(task.status).toBe(TaskStatus.TASK_SUCCEEDED); + }); test(`${permission} key: Update documents in JSON format with custom primary key`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const data = `[{ "name": 123, "title": "Pride and Prejudice", "comment": "A great book" }, -{ "name": 456, "title": "Le Petit Prince", "comment": "A french book" }]` +{ "name": 456, "title": "Le Petit Prince", "comment": "A french book" }]`; const { taskUid } = await client .index('json_index') .updateDocumentsFromString(data, ContentTypeEnum.JSON, { primaryKey: 'name', - }) - const task = await client.waitForTask(taskUid) - - expect(task.details.receivedDocuments).toBe(2) - expect(task.status).toBe(TaskStatus.TASK_SUCCEEDED) - }) - } -) + }); + const task = await client.waitForTask(taskUid); + + expect(task.details.receivedDocuments).toBe(2); + expect(task.status).toBe(TaskStatus.TASK_SUCCEEDED); + }); + }, +); diff --git a/tests/search.test.ts b/tests/search.test.ts index e1dd65a41..0f6bafeb7 100644 --- a/tests/search.test.ts +++ b/tests/search.test.ts @@ -1,5 +1,5 @@ -import { ErrorStatusCode, MatchingStrategies } from '../src/types' -import { EnqueuedTask } from '../src/enqueued-task' +import { ErrorStatusCode, MatchingStrategies } from '../src/types'; +import { EnqueuedTask } from '../src/enqueued-task'; import { clearAllIndexes, config, @@ -9,25 +9,25 @@ import { datasetWithNests, HOST, getKey, -} from './utils/meilisearch-test-utils' +} from './utils/meilisearch-test-utils'; if (typeof fetch === 'undefined') { - require('cross-fetch/polyfill') + require('cross-fetch/polyfill'); } const index = { uid: 'movies_test', -} +}; const emptyIndex = { uid: 'empty_test', -} +}; type Books = { - id: number - title: string - comment: string - genre: string -} + id: number; + title: string; + comment: string; + genre: string; +}; const dataset = [ { @@ -69,7 +69,7 @@ const dataset = [ genre: 'fantasy', }, { id: 42, title: "The Hitchhiker's Guide to the Galaxy", genre: 'fantasy' }, -] +]; describe.each([ { permission: 'Master' }, @@ -77,304 +77,306 @@ describe.each([ { permission: 'Search' }, ])('Test on POST search', ({ permission }) => { beforeAll(async () => { - await clearAllIndexes(config) - const client = await getClient('Master') - await client.createIndex(index.uid) - await client.createIndex(emptyIndex.uid) + await clearAllIndexes(config); + const client = await getClient('Master'); + await client.createIndex(index.uid); + await client.createIndex(emptyIndex.uid); - const newFilterableAttributes = ['genre', 'title', 'id'] + const newFilterableAttributes = ['genre', 'title', 'id']; const { taskUid: task1 }: EnqueuedTask = await client .index(index.uid) .updateSettings({ filterableAttributes: newFilterableAttributes, sortableAttributes: ['id'], - }) - await client.waitForTask(task1) + }); + await client.waitForTask(task1); const { taskUid: task2 } = await client .index(index.uid) - .addDocuments(dataset) - await client.waitForTask(task2) - }) + .addDocuments(dataset); + await client.waitForTask(task2); + }); test(`${permission} key: Multi index search no queries`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const response = await client.multiSearch({ queries: [], - }) + }); - expect(response.results.length).toEqual(0) - }) + expect(response.results.length).toEqual(0); + }); test(`${permission} key: Multi index search with one query`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const response = await client.multiSearch({ queries: [{ indexUid: index.uid, q: 'prince' }], - }) + }); - expect(response.results[0].hits.length).toEqual(2) - }) + expect(response.results[0].hits.length).toEqual(2); + }); test(`${permission} key: Multi index search with multiple queries`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const response = await client.multiSearch({ queries: [ { indexUid: index.uid, q: 'something' }, { indexUid: emptyIndex.uid, q: 'something' }, ], - }) + }); - expect(response.results.length).toEqual(2) - }) + expect(response.results.length).toEqual(2); + }); test(`${permission} key: Multi index search with one query`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); type MyIndex = { - id: 1 - } + id: 1; + }; const response = await client.multiSearch({ queries: [{ indexUid: index.uid, q: 'prince' }], - }) + }); - expect(response.results[0].hits.length).toEqual(2) - expect(response.results[0].hits[0].id).toEqual(456) - expect(response.results[0].hits[0].title).toEqual('Le Petit Prince') - }) + expect(response.results[0].hits.length).toEqual(2); + expect(response.results[0].hits[0].id).toEqual(456); + expect(response.results[0].hits[0].title).toEqual('Le Petit Prince'); + }); test(`${permission} key: Basic search`, async () => { - const client = await getClient(permission) - const response = await client.index(index.uid).search('prince', {}) - - expect(response).toHaveProperty('hits') - expect(Array.isArray(response.hits)).toBe(true) - expect(response).toHaveProperty('limit', 20) - expect(response).toHaveProperty('offset', 0) - expect(response).toHaveProperty('processingTimeMs', expect.any(Number)) - expect(response).toHaveProperty('query', 'prince') - expect(response.facetStats).toBeUndefined() - expect(response.hits.length).toEqual(2) + const client = await getClient(permission); + const response = await client.index(index.uid).search('prince', {}); + + expect(response).toHaveProperty('hits'); + expect(Array.isArray(response.hits)).toBe(true); + expect(response).toHaveProperty('limit', 20); + expect(response).toHaveProperty('offset', 0); + expect(response).toHaveProperty('processingTimeMs', expect.any(Number)); + expect(response).toHaveProperty('query', 'prince'); + expect(response.facetStats).toBeUndefined(); + expect(response.hits.length).toEqual(2); // @ts-expect-error Not present in the SearchResponse type because neither `page` or `hitsPerPage` is provided in the search params. - expect(response.hitsPerPage).toBeUndefined() + expect(response.hitsPerPage).toBeUndefined(); // @ts-expect-error Not present in the SearchResponse type because neither `page` or `hitsPerPage` is provided in the search params. - expect(response.page).toBeUndefined() + expect(response.page).toBeUndefined(); // @ts-expect-error Not present in the SearchResponse type because neither `page` or `hitsPerPage` is provided in the search params. - expect(response.totalPages).toBeUndefined() + expect(response.totalPages).toBeUndefined(); // @ts-expect-error Not present in the SearchResponse type because neither `page` or `hitsPerPage` is provided in the search params. - expect(response.totalHits).toBeUndefined() - }) + expect(response.totalHits).toBeUndefined(); + }); test(`${permission} key: Basic phrase search with matchingStrategy at ALL`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const response = await client .index(index.uid) .search('"french book" about', { matchingStrategy: MatchingStrategies.ALL, - }) + }); - expect(response).toHaveProperty('hits') - expect(Array.isArray(response.hits)).toBe(true) - expect(response).toHaveProperty('offset', 0) - expect(response).toHaveProperty('limit', 20) - expect(response.hits.length).toEqual(1) - }) + expect(response).toHaveProperty('hits'); + expect(Array.isArray(response.hits)).toBe(true); + expect(response).toHaveProperty('offset', 0); + expect(response).toHaveProperty('limit', 20); + expect(response.hits.length).toEqual(1); + }); test(`${permission} key: Basic phrase search with matchingStrategy at LAST`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const response = await client .index(index.uid) - .search('french book', { matchingStrategy: MatchingStrategies.LAST }) + .search('french book', { matchingStrategy: MatchingStrategies.LAST }); - expect(response).toHaveProperty('hits') - expect(Array.isArray(response.hits)).toBe(true) - expect(response).toHaveProperty('offset', 0) - expect(response).toHaveProperty('limit', 20) - expect(response.hits.length).toEqual(2) - }) + expect(response).toHaveProperty('hits'); + expect(Array.isArray(response.hits)).toBe(true); + expect(response).toHaveProperty('offset', 0); + expect(response).toHaveProperty('limit', 20); + expect(response.hits.length).toEqual(2); + }); test(`${permission} key: Search with query in searchParams overwriting query`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const response = await client .index(index.uid) - .search('other', { q: 'prince' }) - - expect(response).toHaveProperty('hits') - expect(Array.isArray(response.hits)).toBe(true) - expect(response).toHaveProperty('limit', 20) - expect(response).toHaveProperty('offset', 0) - expect(response.estimatedTotalHits).toBeDefined() - expect(response).toHaveProperty('processingTimeMs', expect.any(Number)) - expect(response).toHaveProperty('query', 'prince') - expect(response.hits.length).toEqual(2) - }) + .search('other', { q: 'prince' }); + + expect(response).toHaveProperty('hits'); + expect(Array.isArray(response.hits)).toBe(true); + expect(response).toHaveProperty('limit', 20); + expect(response).toHaveProperty('offset', 0); + expect(response.estimatedTotalHits).toBeDefined(); + expect(response).toHaveProperty('processingTimeMs', expect.any(Number)); + expect(response).toHaveProperty('query', 'prince'); + expect(response.hits.length).toEqual(2); + }); test(`${permission} key: Search with query in searchParams overwriting null query`, async () => { - const client = await getClient(permission) - const response = await client.index(index.uid).search(null, { q: 'prince' }) - - expect(response).toHaveProperty('hits') - expect(Array.isArray(response.hits)).toBe(true) - expect(response).toHaveProperty('limit', 20) - expect(response).toHaveProperty('offset', 0) - expect(response.estimatedTotalHits).toBeDefined() - expect(response).toHaveProperty('processingTimeMs', expect.any(Number)) - expect(response).toHaveProperty('query', 'prince') - expect(response.hits.length).toEqual(2) - }) + const client = await getClient(permission); + const response = await client + .index(index.uid) + .search(null, { q: 'prince' }); + + expect(response).toHaveProperty('hits'); + expect(Array.isArray(response.hits)).toBe(true); + expect(response).toHaveProperty('limit', 20); + expect(response).toHaveProperty('offset', 0); + expect(response.estimatedTotalHits).toBeDefined(); + expect(response).toHaveProperty('processingTimeMs', expect.any(Number)); + expect(response).toHaveProperty('query', 'prince'); + expect(response.hits.length).toEqual(2); + }); test(`${permission} key: Basic phrase search`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const response = await client .index(index.uid) - .search('"french book" about', {}) - expect(response).toHaveProperty('hits') - expect(Array.isArray(response.hits)).toBe(true) - expect(response).toHaveProperty('limit', 20) - expect(response).toHaveProperty('offset', 0) - expect(response).toHaveProperty('processingTimeMs', expect.any(Number)) - expect(response).toHaveProperty('query', '"french book" about') + .search('"french book" about', {}); + expect(response).toHaveProperty('hits'); + expect(Array.isArray(response.hits)).toBe(true); + expect(response).toHaveProperty('limit', 20); + expect(response).toHaveProperty('offset', 0); + expect(response).toHaveProperty('processingTimeMs', expect.any(Number)); + expect(response).toHaveProperty('query', '"french book" about'); - expect(response.hits.length).toEqual(2) - }) + expect(response.hits.length).toEqual(2); + }); test(`${permission} key: search with options`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const response = await client .index(index.uid) - .search('prince', { limit: 1 }) - expect(response).toHaveProperty('hits') - expect(Array.isArray(response.hits)).toBe(true) - expect(response).toHaveProperty('offset', 0) - expect(response).toHaveProperty('limit', 1) - expect(response.estimatedTotalHits).toEqual(2) - expect(response).toHaveProperty('processingTimeMs', expect.any(Number)) - expect(response).toHaveProperty('query', 'prince') - expect(response.hits.length).toEqual(1) - }) + .search('prince', { limit: 1 }); + expect(response).toHaveProperty('hits'); + expect(Array.isArray(response.hits)).toBe(true); + expect(response).toHaveProperty('offset', 0); + expect(response).toHaveProperty('limit', 1); + expect(response.estimatedTotalHits).toEqual(2); + expect(response).toHaveProperty('processingTimeMs', expect.any(Number)); + expect(response).toHaveProperty('query', 'prince'); + expect(response.hits.length).toEqual(1); + }); test(`${permission} key: search with sortable`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const response = await client .index(index.uid) - .search('', { sort: ['id:asc'] }) - expect(response).toHaveProperty('hits') - expect(Array.isArray(response.hits)).toBe(true) - const hit = response.hits[0] - expect(hit.id).toEqual(1) - }) + .search('', { sort: ['id:asc'] }); + expect(response).toHaveProperty('hits'); + expect(Array.isArray(response.hits)).toBe(true); + const hit = response.hits[0]; + expect(hit.id).toEqual(1); + }); test(`${permission} key: search with _showRankingScore enabled`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const response = await client.index(index.uid).search('prince', { showRankingScore: true, - }) + }); - const hit = response.hits[0] + const hit = response.hits[0]; - expect(response).toHaveProperty('hits') - expect(Array.isArray(response.hits)).toBe(true) - expect(response).toHaveProperty('query', 'prince') - expect(hit).toHaveProperty('_rankingScore') - }) + expect(response).toHaveProperty('hits'); + expect(Array.isArray(response.hits)).toBe(true); + expect(response).toHaveProperty('query', 'prince'); + expect(hit).toHaveProperty('_rankingScore'); + }); test(`${permission} key: search with showRankingScoreDetails`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const response = await client.index(index.uid).search('prince', { showRankingScoreDetails: true, - }) + }); - const hit = response.hits[0] + const hit = response.hits[0]; - expect(response).toHaveProperty('hits') - expect(Array.isArray(response.hits)).toBe(true) - expect(response).toHaveProperty('query', 'prince') - expect(hit).toHaveProperty('_rankingScoreDetails') + expect(response).toHaveProperty('hits'); + expect(Array.isArray(response.hits)).toBe(true); + expect(response).toHaveProperty('query', 'prince'); + expect(hit).toHaveProperty('_rankingScoreDetails'); expect(Object.keys(hit._rankingScoreDetails || {})).toEqual([ 'words', 'typo', 'proximity', 'attribute', 'exactness', - ]) - }) + ]); + }); test(`${permission} key: search with array options`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const response = await client.index(index.uid).search('prince', { attributesToRetrieve: ['*'], - }) - const hit = response.hits[0] + }); + const hit = response.hits[0]; - expect(response).toHaveProperty('hits') - expect(Array.isArray(response.hits)).toBe(true) - expect(response).toHaveProperty('query', 'prince') + expect(response).toHaveProperty('hits'); + expect(Array.isArray(response.hits)).toBe(true); + expect(response).toHaveProperty('query', 'prince'); expect(Object.keys(hit).join(',')).toEqual( - Object.keys(dataset[1]).join(',') - ) - }) + Object.keys(dataset[1]).join(','), + ); + }); test(`${permission} key: search on attributesToSearchOn`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const response = await client.index(index.uid).search('prince', { attributesToSearchOn: ['id'], - }) + }); - expect(response.hits.length).toEqual(0) - }) + expect(response.hits.length).toEqual(0); + }); test(`${permission} key: search on attributesToSearchOn set to null`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const response = await client.index(index.uid).search('prince', { attributesToSearchOn: null, - }) + }); - expect(response).toMatchSnapshot() - }) + expect(response).toMatchSnapshot(); + }); test(`${permission} key: search with array options`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const response = await client.index(index.uid).search('prince', { attributesToRetrieve: ['*'], - }) - const hit = response.hits[0] + }); + const hit = response.hits[0]; - expect(response).toHaveProperty('hits') - expect(Array.isArray(response.hits)).toBe(true) - expect(response).toHaveProperty('query', 'prince') + expect(response).toHaveProperty('hits'); + expect(Array.isArray(response.hits)).toBe(true); + expect(response).toHaveProperty('query', 'prince'); expect(Object.keys(hit).join(',')).toEqual( - Object.keys(dataset[1]).join(',') - ) - }) + Object.keys(dataset[1]).join(','), + ); + }); test(`${permission} key: search with options`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const response = await client .index(index.uid) - .search('prince', { limit: 1 }) - expect(response).toHaveProperty('hits') - expect(Array.isArray(response.hits)).toBe(true) - expect(response).toHaveProperty('offset', 0) - expect(response).toHaveProperty('limit', 1) - expect(response.estimatedTotalHits).toEqual(2) - expect(response).toHaveProperty('processingTimeMs', expect.any(Number)) - expect(response).toHaveProperty('query', 'prince') - expect(response.hits.length).toEqual(1) - }) + .search('prince', { limit: 1 }); + expect(response).toHaveProperty('hits'); + expect(Array.isArray(response.hits)).toBe(true); + expect(response).toHaveProperty('offset', 0); + expect(response).toHaveProperty('limit', 1); + expect(response.estimatedTotalHits).toEqual(2); + expect(response).toHaveProperty('processingTimeMs', expect.any(Number)); + expect(response).toHaveProperty('query', 'prince'); + expect(response.hits.length).toEqual(1); + }); test(`${permission} key: search with limit and offset`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const response = await client.index(index.uid).search('prince', { limit: 1, offset: 1, - }) + }); expect(response).toHaveProperty('hits', [ { @@ -383,41 +385,41 @@ describe.each([ comment: 'The best book', genre: 'fantasy', }, - ]) - expect(response).toHaveProperty('offset', 1) - expect(response).toHaveProperty('limit', 1) - expect(response.estimatedTotalHits).toEqual(2) - expect(response).toHaveProperty('processingTimeMs', expect.any(Number)) - expect(response).toHaveProperty('query', 'prince') - expect(response.hits.length).toEqual(1) + ]); + expect(response).toHaveProperty('offset', 1); + expect(response).toHaveProperty('limit', 1); + expect(response.estimatedTotalHits).toEqual(2); + expect(response).toHaveProperty('processingTimeMs', expect.any(Number)); + expect(response).toHaveProperty('query', 'prince'); + expect(response.hits.length).toEqual(1); // @ts-expect-error Not present in the SearchResponse type because neither `page` or `hitsPerPage` is provided in the search params. - expect(response.hitsPerPage).toBeUndefined() + expect(response.hitsPerPage).toBeUndefined(); // @ts-expect-error Not present in the SearchResponse type because neither `page` or `hitsPerPage` is provided in the search params. - expect(response.page).toBeUndefined() + expect(response.page).toBeUndefined(); // @ts-expect-error Not present in the SearchResponse type because neither `page` or `hitsPerPage` is provided in the search params. - expect(response.totalPages).toBeUndefined() + expect(response.totalPages).toBeUndefined(); // @ts-expect-error Not present in the SearchResponse type because neither `page` or `hitsPerPage` is provided in the search params. - expect(response.totalHits).toBeUndefined() - }) + expect(response.totalHits).toBeUndefined(); + }); test(`${permission} key: search with matches parameter and small croplength`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const response = await client.index(index.uid).search('prince', { filter: 'title = "Le Petit Prince"', attributesToCrop: ['*'], cropLength: 5, showMatchesPosition: true, - }) - expect(response).toHaveProperty('hits') - expect(Array.isArray(response.hits)).toBe(true) + }); + expect(response).toHaveProperty('hits'); + expect(Array.isArray(response.hits)).toBe(true); expect(response.hits[0]).toHaveProperty('_matchesPosition', { comment: [{ start: 22, length: 6 }], title: [{ start: 9, length: 6 }], - }) - }) + }); + }); test(`${permission} key: search with all options but not all fields`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const response = await client.index(index.uid).search('prince', { limit: 5, offset: 0, @@ -427,73 +429,73 @@ describe.each([ attributesToHighlight: ['*'], filter: 'title = "Le Petit Prince"', showMatchesPosition: true, - }) - expect(response).toHaveProperty('hits') - expect(Array.isArray(response.hits)).toBe(true) - expect(response).toHaveProperty('offset', 0) - expect(response).toHaveProperty('limit', 5) - expect(response.estimatedTotalHits).toEqual(1) - expect(response).toHaveProperty('processingTimeMs', expect.any(Number)) - expect(response).toHaveProperty('query', 'prince') - expect(response.hits[0]._formatted).toHaveProperty('title') - expect(response.hits[0]._formatted).toHaveProperty('id') - expect(response.hits[0]).not.toHaveProperty('comment') - expect(response.hits[0]).not.toHaveProperty('description') - expect(response.hits.length).toEqual(1) - expect(response.hits[0]).toHaveProperty('_formatted', expect.any(Object)) + }); + expect(response).toHaveProperty('hits'); + expect(Array.isArray(response.hits)).toBe(true); + expect(response).toHaveProperty('offset', 0); + expect(response).toHaveProperty('limit', 5); + expect(response.estimatedTotalHits).toEqual(1); + expect(response).toHaveProperty('processingTimeMs', expect.any(Number)); + expect(response).toHaveProperty('query', 'prince'); + expect(response.hits[0]._formatted).toHaveProperty('title'); + expect(response.hits[0]._formatted).toHaveProperty('id'); + expect(response.hits[0]).not.toHaveProperty('comment'); + expect(response.hits[0]).not.toHaveProperty('description'); + expect(response.hits.length).toEqual(1); + expect(response.hits[0]).toHaveProperty('_formatted', expect.any(Object)); expect(response.hits[0]._formatted).toHaveProperty( 'title', - 'Le Petit Prince' - ) + 'Le Petit Prince', + ); expect(response.hits[0]).toHaveProperty( '_matchesPosition', - expect.any(Object) - ) - }) + expect.any(Object), + ); + }); test(`${permission} key: search on default cropping parameters`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const response = await client.index(index.uid).search('prince', { attributesToCrop: ['*'], cropLength: 6, - }) + }); expect(response.hits[0]._formatted).toHaveProperty( 'comment', - '…book about a prince that walks…' - ) - }) + '…book about a prince that walks…', + ); + }); test(`${permission} key: search on customized cropMarker`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const response = await client.index(index.uid).search('prince', { attributesToCrop: ['*'], cropLength: 6, cropMarker: '(ꈍᴗꈍ)', - }) + }); expect(response.hits[0]._formatted).toHaveProperty( 'comment', - '(ꈍᴗꈍ)book about a prince that walks(ꈍᴗꈍ)' - ) - }) + '(ꈍᴗꈍ)book about a prince that walks(ꈍᴗꈍ)', + ); + }); test(`${permission} key: search on customized highlight tags`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const response = await client.index(index.uid).search('prince', { attributesToHighlight: ['*'], highlightPreTag: '(⊃。•́‿•̀。)⊃ ', highlightPostTag: ' ⊂(´• ω •`⊂)', - }) + }); expect(response.hits[0]._formatted).toHaveProperty( 'comment', - 'A french book about a (⊃。•́‿•̀。)⊃ prince ⊂(´• ω •`⊂) that walks on little cute planets' - ) - }) + 'A french book about a (⊃。•́‿•̀。)⊃ prince ⊂(´• ω •`⊂) that walks on little cute planets', + ); + }); test(`${permission} key: search with all options and all fields`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const response = await client.index(index.uid).search('prince', { limit: 5, offset: 0, @@ -503,27 +505,27 @@ describe.each([ attributesToHighlight: ['*'], filter: 'title = "Le Petit Prince"', showMatchesPosition: true, - }) - expect(response).toHaveProperty('hits') - expect(Array.isArray(response.hits)).toBe(true) - expect(response).toHaveProperty('offset', 0) - expect(response).toHaveProperty('limit', 5) - expect(response).toHaveProperty('processingTimeMs', expect.any(Number)) - expect(response).toHaveProperty('query', 'prince') - expect(response.hits.length).toEqual(1) - expect(response.hits[0]).toHaveProperty('_formatted', expect.any(Object)) + }); + expect(response).toHaveProperty('hits'); + expect(Array.isArray(response.hits)).toBe(true); + expect(response).toHaveProperty('offset', 0); + expect(response).toHaveProperty('limit', 5); + expect(response).toHaveProperty('processingTimeMs', expect.any(Number)); + expect(response).toHaveProperty('query', 'prince'); + expect(response.hits.length).toEqual(1); + expect(response.hits[0]).toHaveProperty('_formatted', expect.any(Object)); expect(response.hits[0]._formatted).toHaveProperty( 'title', - 'Le Petit Prince' - ) + 'Le Petit Prince', + ); expect(response.hits[0]).toHaveProperty( '_matchesPosition', - expect.any(Object) - ) - }) + expect.any(Object), + ); + }); test(`${permission} key: search with all options but specific fields`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const response = await client.index(index.uid).search('prince', { limit: 5, offset: 0, @@ -533,325 +535,325 @@ describe.each([ attributesToHighlight: ['id', 'title'], filter: 'title = "Le Petit Prince"', showMatchesPosition: true, - }) - expect(response).toHaveProperty('hits') - expect(Array.isArray(response.hits)).toBe(true) - expect(response).toHaveProperty('offset', 0) - expect(response).toHaveProperty('limit', 5) - expect(response).toHaveProperty('processingTimeMs', expect.any(Number)) - expect(response).toHaveProperty('query', 'prince') - expect(response.hits.length).toEqual(1) - expect(response.hits[0]._formatted?.id).toEqual('456') - expect(response.hits[0]).toHaveProperty('title', 'Le Petit Prince') - expect(response.hits[0]).not.toHaveProperty('comment') - expect(response.hits[0]).toHaveProperty('_formatted', expect.any(Object)) + }); + expect(response).toHaveProperty('hits'); + expect(Array.isArray(response.hits)).toBe(true); + expect(response).toHaveProperty('offset', 0); + expect(response).toHaveProperty('limit', 5); + expect(response).toHaveProperty('processingTimeMs', expect.any(Number)); + expect(response).toHaveProperty('query', 'prince'); + expect(response.hits.length).toEqual(1); + expect(response.hits[0]._formatted?.id).toEqual('456'); + expect(response.hits[0]).toHaveProperty('title', 'Le Petit Prince'); + expect(response.hits[0]).not.toHaveProperty('comment'); + expect(response.hits[0]).toHaveProperty('_formatted', expect.any(Object)); expect(response.hits[0]).not.toHaveProperty( 'description', - expect.any(Object) - ) + expect.any(Object), + ); expect(response.hits[0]._formatted).toHaveProperty( 'title', - 'Le Petit Prince' - ) - expect(response.hits[0]._formatted).not.toHaveProperty('comment') + 'Le Petit Prince', + ); + expect(response.hits[0]._formatted).not.toHaveProperty('comment'); expect(response.hits[0]).toHaveProperty( '_matchesPosition', - expect.any(Object) - ) - }) + expect.any(Object), + ); + }); test(`${permission} key: Search with specific fields in attributesToHighlight and check for types of number fields`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const response = await client.index(index.uid).search('prince', { attributesToHighlight: ['title'], - }) - expect(response.hits[0]._formatted?.id).toEqual('456') - expect(response.hits[0]._formatted?.isNull).toEqual(null) - expect(response.hits[0]._formatted?.isTrue).toEqual(true) - }) + }); + expect(response.hits[0]._formatted?.id).toEqual('456'); + expect(response.hits[0]._formatted?.isNull).toEqual(null); + expect(response.hits[0]._formatted?.isTrue).toEqual(true); + }); test(`${permission} key: Search with specific fields in attributesToHighlight and check for types of number fields`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const response = await client.index(index.uid).search('prince', { attributesToHighlight: ['title', 'id'], - }) - expect(response.hits[0]._formatted?.id).toEqual('456') - expect(response.hits[0]._formatted?.isNull).toEqual(null) - expect(response.hits[0]._formatted?.isTrue).toEqual(true) - }) + }); + expect(response.hits[0]._formatted?.id).toEqual('456'); + expect(response.hits[0]._formatted?.isNull).toEqual(null); + expect(response.hits[0]._formatted?.isTrue).toEqual(true); + }); test(`${permission} key: search with filter and facetDistribution`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const response = await client.index(index.uid).search('a', { filter: ['genre = romance'], facets: ['genre', 'id'], - }) + }); expect(response).toHaveProperty('facetDistribution', { genre: { romance: 2 }, id: { '123': 1, '2': 1 }, - }) + }); - expect(response.facetStats).toEqual({ id: { min: 2, max: 123 } }) - expect(response.facetStats?.['id']?.max).toBe(123) - expect(response).toHaveProperty('hits') - expect(Array.isArray(response.hits)).toBe(true) - expect(response.hits.length).toEqual(2) - }) + expect(response.facetStats).toEqual({ id: { min: 2, max: 123 } }); + expect(response.facetStats?.['id']?.max).toBe(123); + expect(response).toHaveProperty('hits'); + expect(Array.isArray(response.hits)).toBe(true); + expect(response.hits.length).toEqual(2); + }); test(`${permission} key: search with filter on number`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const response = await client.index(index.uid).search('a', { filter: 'id < 0', - }) - expect(response).toHaveProperty('hits') - expect(Array.isArray(response.hits)).toBe(true) - expect(response.hits.length).toEqual(0) - }) + }); + expect(response).toHaveProperty('hits'); + expect(Array.isArray(response.hits)).toBe(true); + expect(response.hits.length).toEqual(0); + }); test(`${permission} key: search with filter with spaces`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const response = await client.index(index.uid).search('h', { filter: ['genre = "sci fi"'], - }) + }); - expect(response).toHaveProperty('hits') - expect(Array.isArray(response.hits)).toBe(true) - expect(response.hits.length).toEqual(1) - }) + expect(response).toHaveProperty('hits'); + expect(Array.isArray(response.hits)).toBe(true); + expect(response.hits.length).toEqual(1); + }); test(`${permission} key: search with multiple filter`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const response = await client.index(index.uid).search('a', { filter: ['genre = romance', ['genre = romance', 'genre = romance']], facets: ['genre'], - }) + }); expect(response).toHaveProperty('facetDistribution', { genre: { romance: 2 }, - }) - expect(response).toHaveProperty('hits') - expect(Array.isArray(response.hits)).toBe(true) - expect(response.hits.length).toEqual(2) - }) + }); + expect(response).toHaveProperty('hits'); + expect(Array.isArray(response.hits)).toBe(true); + expect(response.hits.length).toEqual(2); + }); test(`${permission} key: search with multiple filter and undefined query (placeholder)`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const response = await client.index(index.uid).search(undefined, { filter: ['genre = fantasy'], facets: ['genre'], - }) + }); expect(response).toHaveProperty('facetDistribution', { genre: { fantasy: 2 }, - }) - expect(response.hits.length).toEqual(2) - }) + }); + expect(response.hits.length).toEqual(2); + }); test(`${permission} key: search with multiple filter and null query (placeholder)`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const response = await client.index(index.uid).search(null, { filter: ['genre = fantasy'], facets: ['genre'], - }) + }); expect(response).toHaveProperty('facetDistribution', { genre: { fantasy: 2 }, - }) - expect(response.hits.length).toEqual(2) - }) + }); + expect(response.hits.length).toEqual(2); + }); test(`${permission} key: search with multiple filter and empty string query (placeholder)`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const response = await client.index(index.uid).search('', { filter: ['genre = fantasy'], facets: ['genre'], - }) + }); expect(response).toHaveProperty('facetDistribution', { genre: { fantasy: 2 }, - }) - expect(response.hits.length).toEqual(2) - }) + }); + expect(response.hits.length).toEqual(2); + }); test(`${permission} key: search with pagination parameters: hitsPerPage and page`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const response = await client.index(index.uid).search('', { hitsPerPage: 1, page: 1, - }) + }); - expect(response.hits.length).toEqual(1) - expect(response.totalPages).toEqual(7) - expect(response.hitsPerPage).toEqual(1) - expect(response.page).toEqual(1) - expect(response.totalHits).toEqual(7) - }) + expect(response.hits.length).toEqual(1); + expect(response.totalPages).toEqual(7); + expect(response.hitsPerPage).toEqual(1); + expect(response.page).toEqual(1); + expect(response.totalHits).toEqual(7); + }); test(`${permission} key: search with pagination parameters: hitsPerPage at 0 and page at 1`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const response = await client.index(index.uid).search('', { hitsPerPage: 0, page: 1, - }) + }); - expect(response.hits.length).toEqual(0) - expect(response.hitsPerPage).toEqual(0) - expect(response.page).toEqual(1) - expect(response.totalPages).toEqual(0) - expect(response.totalHits).toEqual(7) - }) + expect(response.hits.length).toEqual(0); + expect(response.hitsPerPage).toEqual(0); + expect(response.page).toEqual(1); + expect(response.totalPages).toEqual(0); + expect(response.totalHits).toEqual(7); + }); test(`${permission} key: search with pagination parameters: hitsPerPage at 0`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const response = await client.index(index.uid).search('', { hitsPerPage: 0, - }) + }); - expect(response.hits.length).toEqual(0) - expect(response.hitsPerPage).toEqual(0) - expect(response.page).toEqual(1) - expect(response.totalPages).toEqual(0) - expect(response.totalHits).toEqual(7) + expect(response.hits.length).toEqual(0); + expect(response.hitsPerPage).toEqual(0); + expect(response.page).toEqual(1); + expect(response.totalPages).toEqual(0); + expect(response.totalHits).toEqual(7); // @ts-expect-error Not present in the SearchResponse type because `page` and/or `hitsPerPage` is provided in the search params. - expect(response.limit).toBeUndefined() + expect(response.limit).toBeUndefined(); // @ts-expect-error Not present in the SearchResponse type because `page` and/or `hitsPerPage` is provided in the search params. - expect(response.offset).toBeUndefined() + expect(response.offset).toBeUndefined(); // @ts-expect-error Not present in the SearchResponse type because `page` and/or `hitsPerPage` is provided in the search params. - expect(response.estimatedTotalHits).toBeUndefined() - }) + expect(response.estimatedTotalHits).toBeUndefined(); + }); test(`${permission} key: search with pagination parameters: hitsPerPage at 1 and page at 0`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const response = await client.index(index.uid).search('', { hitsPerPage: 1, page: 0, - }) + }); - expect(response.hits.length).toEqual(0) - expect(response.hitsPerPage).toEqual(1) - expect(response.page).toEqual(0) - expect(response.totalPages).toEqual(7) - expect(response.totalHits).toEqual(7) - }) + expect(response.hits.length).toEqual(0); + expect(response.hitsPerPage).toEqual(1); + expect(response.page).toEqual(0); + expect(response.totalPages).toEqual(7); + expect(response.totalHits).toEqual(7); + }); test(`${permission} key: search with pagination parameters: page at 0`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const response = await client.index(index.uid).search('', { page: 0, - }) + }); - expect(response.hits.length).toEqual(0) - expect(response.hitsPerPage).toEqual(20) - expect(response.page).toEqual(0) - expect(response.totalPages).toEqual(1) - expect(response.totalHits).toEqual(7) - }) + expect(response.hits.length).toEqual(0); + expect(response.hitsPerPage).toEqual(20); + expect(response.page).toEqual(0); + expect(response.totalPages).toEqual(1); + expect(response.totalHits).toEqual(7); + }); test(`${permission} key: search with pagination parameters: hitsPerPage at 0 and page at 0`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const response = await client.index(index.uid).search('', { hitsPerPage: 0, page: 0, - }) + }); - expect(response.hits.length).toEqual(0) + expect(response.hits.length).toEqual(0); // @ts-expect-error Property not existing on type - expect(response.limit).toBeUndefined() + expect(response.limit).toBeUndefined(); // @ts-expect-error Property not existing on type - expect(response.offset).toBeUndefined() + expect(response.offset).toBeUndefined(); // @ts-expect-error Property not existing on type - expect(response.estimatedTotalHits).toBeUndefined() + expect(response.estimatedTotalHits).toBeUndefined(); - expect(response.hitsPerPage).toEqual(0) - expect(response.page).toEqual(0) - expect(response.totalPages).toEqual(0) - expect(response.totalHits).toEqual(7) - }) + expect(response.hitsPerPage).toEqual(0); + expect(response.page).toEqual(0); + expect(response.totalPages).toEqual(0); + expect(response.totalHits).toEqual(7); + }); test(`${permission} key: search with pagination parameters hitsPerPage/page and offset/limit`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const response = await client.index(index.uid).search('', { hitsPerPage: 1, page: 1, offset: 1, limit: 1, - }) + }); - expect(response.hits.length).toEqual(1) + expect(response.hits.length).toEqual(1); // @ts-expect-error Property not existing on type - expect(response.limit).toBeUndefined() + expect(response.limit).toBeUndefined(); // @ts-expect-error Property not existing on type - expect(response.offset).toBeUndefined() + expect(response.offset).toBeUndefined(); // @ts-expect-error Property not existing on type - expect(response.estimatedTotalHits).toBeUndefined() - expect(response.hitsPerPage).toEqual(1) - expect(response.page).toEqual(1) - expect(response.totalPages).toEqual(7) - expect(response.totalHits).toEqual(7) - }) + expect(response.estimatedTotalHits).toBeUndefined(); + expect(response.hitsPerPage).toEqual(1); + expect(response.page).toEqual(1); + expect(response.totalPages).toEqual(7); + expect(response.totalHits).toEqual(7); + }); test(`${permission} key: search with pagination parameters hitsPerPage/page and offset`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const response = await client.index(index.uid).search('', { hitsPerPage: 1, page: 1, offset: 1, - }) + }); - expect(response.hits.length).toEqual(1) + expect(response.hits.length).toEqual(1); // @ts-expect-error Property not existing on type - expect(response.limit).toBeUndefined() + expect(response.limit).toBeUndefined(); // @ts-expect-error Property not existing on type - expect(response.offset).toBeUndefined() + expect(response.offset).toBeUndefined(); // @ts-expect-error Property not existing on type - expect(response.estimatedTotalHits).toBeUndefined() - expect(response.hitsPerPage).toEqual(1) - expect(response.page).toEqual(1) - expect(response.totalHits).toEqual(7) - expect(response.totalPages).toEqual(7) - }) + expect(response.estimatedTotalHits).toBeUndefined(); + expect(response.hitsPerPage).toEqual(1); + expect(response.page).toEqual(1); + expect(response.totalHits).toEqual(7); + expect(response.totalPages).toEqual(7); + }); test(`${permission} key: search with pagination parameters hitsPerPage/page and limit`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const response = await client.index(index.uid).search('', { hitsPerPage: 1, page: 1, limit: 1, - }) + }); - expect(response.hits.length).toEqual(1) + expect(response.hits.length).toEqual(1); // @ts-expect-error Property not existing on type - expect(response.limit).toBeUndefined() + expect(response.limit).toBeUndefined(); // @ts-expect-error Property not existing on type - expect(response.offset).toBeUndefined() + expect(response.offset).toBeUndefined(); // @ts-expect-error Property not existing on type - expect(response.estimatedTotalHits).toBeUndefined() - expect(response.page).toEqual(1) - expect(response.hitsPerPage).toEqual(1) - expect(response.totalPages).toEqual(7) - expect(response.totalHits).toEqual(7) - }) + expect(response.estimatedTotalHits).toBeUndefined(); + expect(response.page).toEqual(1); + expect(response.hitsPerPage).toEqual(1); + expect(response.totalPages).toEqual(7); + expect(response.totalHits).toEqual(7); + }); test(`${permission} key: search on index with no documents and no primary key`, async () => { - const client = await getClient(permission) - const response = await client.index(emptyIndex.uid).search('prince', {}) + const client = await getClient(permission); + const response = await client.index(emptyIndex.uid).search('prince', {}); - expect(response).toHaveProperty('hits', []) - expect(response).toHaveProperty('query', 'prince') - expect(response.hits.length).toEqual(0) - }) + expect(response).toHaveProperty('hits', []); + expect(response).toHaveProperty('query', 'prince'); + expect(response.hits.length).toEqual(0); + }); test(`${permission} key: search with vectors`, async () => { - const client = await getClient(permission) - const adminClient = await getClient('Admin') - const adminKey = await getKey('Admin') + const client = await getClient(permission); + const adminClient = await getClient('Admin'); + const adminKey = await getKey('Admin'); await fetch(`${HOST}/experimental-features`, { body: JSON.stringify({ vectorStore: true }), @@ -860,7 +862,7 @@ describe.each([ 'Content-Type': 'application/json', }, method: 'PATCH', - }) + }); const { taskUid } = await adminClient .index(emptyIndex.uid) @@ -869,89 +871,89 @@ describe.each([ source: 'userProvided', dimensions: 1, }, - }) - await adminClient.waitForTask(taskUid) + }); + await adminClient.waitForTask(taskUid); const response = await client.index(emptyIndex.uid).search('', { vector: [1], hybrid: { semanticRatio: 1.0, }, - }) + }); - expect(response).toHaveProperty('hits') - expect(response).toHaveProperty('semanticHitCount') + expect(response).toHaveProperty('hits'); + expect(response).toHaveProperty('semanticHitCount'); // Those fields are no longer returned by the search response // We want to ensure that they don't appear in it anymore - expect(response).not.toHaveProperty('vector') - expect(response).not.toHaveProperty('_semanticScore') - }) + expect(response).not.toHaveProperty('vector'); + expect(response).not.toHaveProperty('_semanticScore'); + }); test(`${permission} key: search without vectors`, async () => { - const client = await getClient(permission) - const response = await client.index(index.uid).search('prince', {}) + const client = await getClient(permission); + const response = await client.index(index.uid).search('prince', {}); - expect(response).not.toHaveProperty('semanticHitCount') - }) + expect(response).not.toHaveProperty('semanticHitCount'); + }); test(`${permission} key: Try to search on deleted index and fail`, async () => { - const client = await getClient(permission) - const masterClient = await getClient('Master') - const { taskUid } = await masterClient.index(index.uid).delete() - await masterClient.waitForTask(taskUid) + const client = await getClient(permission); + const masterClient = await getClient('Master'); + const { taskUid } = await masterClient.index(index.uid).delete(); + await masterClient.waitForTask(taskUid); await expect( - client.index(index.uid).search('prince', {}) - ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INDEX_NOT_FOUND) - }) -}) + client.index(index.uid).search('prince', {}), + ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INDEX_NOT_FOUND); + }); +}); describe.each([{ permission: 'No' }])( 'Test failing test on search', ({ permission }) => { beforeAll(async () => { - const client = await getClient('Master') - const { taskUid } = await client.createIndex(index.uid) - await client.waitForTask(taskUid) - }) + const client = await getClient('Master'); + const { taskUid } = await client.createIndex(index.uid); + await client.waitForTask(taskUid); + }); test(`${permission} key: Try Basic search and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect( - client.index(index.uid).search('prince') + client.index(index.uid).search('prince'), ).rejects.toHaveProperty( 'cause.code', - ErrorStatusCode.MISSING_AUTHORIZATION_HEADER - ) - }) + ErrorStatusCode.MISSING_AUTHORIZATION_HEADER, + ); + }); test(`${permission} key: Try multi search and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect(client.multiSearch({ queries: [] })).rejects.toHaveProperty( 'cause.code', - ErrorStatusCode.MISSING_AUTHORIZATION_HEADER - ) - }) - } -) + ErrorStatusCode.MISSING_AUTHORIZATION_HEADER, + ); + }); + }, +); describe.each([{ permission: 'Master' }])( 'Tests on documents with nested objects', ({ permission }) => { beforeEach(async () => { - await clearAllIndexes(config) - const client = await getClient('Master') - await client.createIndex(index.uid) + await clearAllIndexes(config); + const client = await getClient('Master'); + await client.createIndex(index.uid); const { taskUid: documentAdditionTask } = await client .index(index.uid) - .addDocuments(datasetWithNests) - await client.waitForTask(documentAdditionTask) - }) + .addDocuments(datasetWithNests); + await client.waitForTask(documentAdditionTask); + }); test(`${permission} key: search on nested content with no parameters`, async () => { - const client = await getClient(permission) - const response = await client.index(index.uid).search('An awesome', {}) + const client = await getClient(permission); + const response = await client.index(index.uid).search('An awesome', {}); expect(response.hits[0]).toEqual({ id: 5, @@ -960,19 +962,19 @@ describe.each([{ permission: 'Master' }])( comment: 'An awesome book', reviewNb: 900, }, - }) - }) + }); + }); test(`${permission} key: search on nested content with searchable on specific nested field`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const { taskUid: settingsUpdateTask }: EnqueuedTask = await client .index(index.uid) .updateSettings({ searchableAttributes: ['title', 'info.comment'], - }) - await client.waitForTask(settingsUpdateTask) + }); + await client.waitForTask(settingsUpdateTask); - const response = await client.index(index.uid).search('An awesome', {}) + const response = await client.index(index.uid).search('An awesome', {}); expect(response.hits[0]).toEqual({ id: 5, @@ -981,22 +983,22 @@ describe.each([{ permission: 'Master' }])( comment: 'An awesome book', reviewNb: 900, }, - }) - }) + }); + }); test(`${permission} key: search on nested content with sort`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const { taskUid: settingsUpdateTask }: EnqueuedTask = await client .index(index.uid) .updateSettings({ searchableAttributes: ['title', 'info.comment'], sortableAttributes: ['info.reviewNb'], - }) - await client.waitForTask(settingsUpdateTask) + }); + await client.waitForTask(settingsUpdateTask); const response = await client.index(index.uid).search('', { sort: ['info.reviewNb:desc'], - }) + }); expect(response.hits[0]).toEqual({ id: 6, @@ -1005,10 +1007,10 @@ describe.each([{ permission: 'Master' }])( comment: 'The best book', reviewNb: 1000, }, - }) - }) - } -) + }); + }); + }, +); describe.each([ { permission: 'Master' }, @@ -1016,40 +1018,40 @@ describe.each([ { permission: 'Search' }, ])('Test on abortable search', ({ permission }) => { beforeAll(async () => { - const client = await getClient('Master') - await clearAllIndexes(config) - const { taskUid } = await client.createIndex(index.uid) - await client.waitForTask(taskUid) - }) + const client = await getClient('Master'); + await clearAllIndexes(config); + const { taskUid } = await client.createIndex(index.uid); + await client.waitForTask(taskUid); + }); test(`${permission} key: search on index and abort`, async () => { - const controller = new AbortController() - const client = await getClient(permission) + const controller = new AbortController(); + const client = await getClient(permission); const searchPromise = client.index(index.uid).search( 'unreachable', {}, { // @ts-ignore qwe signal: controller.signal, - } - ) + }, + ); - controller.abort() + controller.abort(); searchPromise.catch((error: any) => { expect(error).toHaveProperty( 'cause.message', - 'This operation was aborted' - ) - }) - }) + 'This operation was aborted', + ); + }); + }); test(`${permission} key: search on index multiple times, and abort only one request`, async () => { - const client = await getClient(permission) - const controllerA = new AbortController() - const controllerB = new AbortController() - const controllerC = new AbortController() - const searchQuery = 'prince' + const client = await getClient(permission); + const controllerA = new AbortController(); + const controllerB = new AbortController(); + const controllerC = new AbortController(); + const searchQuery = 'prince'; const searchAPromise = client.index(index.uid).search( searchQuery, @@ -1057,8 +1059,8 @@ describe.each([ { // @ts-ignore signal: controllerA.signal, - } - ) + }, + ); const searchBPromise = client.index(index.uid).search( searchQuery, @@ -1066,8 +1068,8 @@ describe.each([ { // @ts-ignore signal: controllerB.signal, - } - ) + }, + ); const searchCPromise = client.index(index.uid).search( searchQuery, @@ -1075,48 +1077,48 @@ describe.each([ { // @ts-ignore signal: controllerC.signal, - } - ) + }, + ); - const searchDPromise = client.index(index.uid).search(searchQuery, {}) + const searchDPromise = client.index(index.uid).search(searchQuery, {}); - controllerB.abort() + controllerB.abort(); searchDPromise.then((response) => { - expect(response).toHaveProperty('query', searchQuery) - }) + expect(response).toHaveProperty('query', searchQuery); + }); searchCPromise.then((response) => { - expect(response).toHaveProperty('query', searchQuery) - }) + expect(response).toHaveProperty('query', searchQuery); + }); searchAPromise.then((response) => { - expect(response).toHaveProperty('query', searchQuery) - }) + expect(response).toHaveProperty('query', searchQuery); + }); searchBPromise.catch((error: any) => { expect(error).toHaveProperty( 'cause.message', - 'This operation was aborted' - ) - }) - }) + 'This operation was aborted', + ); + }); + }); test(`${permission} key: search should be aborted when reaching timeout`, async () => { - const key = await getKey(permission) + const key = await getKey(permission); const client = new MeiliSearch({ ...config, apiKey: key, timeout: 1, - }) + }); try { - await client.health() + await client.health(); } catch (e: any) { - expect(e.cause.message).toEqual('Error: Request Timed Out') - expect(e.name).toEqual('MeiliSearchRequestError') + expect(e.cause.message).toEqual('Error: Request Timed Out'); + expect(e.name).toEqual('MeiliSearchRequestError'); } - }) -}) + }); +}); describe.each([ { host: BAD_HOST, trailing: false }, @@ -1124,28 +1126,28 @@ describe.each([ { host: `${BAD_HOST}/trailing/`, trailing: true }, ])('Tests on url construction', ({ host, trailing }) => { test(`Test get search route`, async () => { - const route = `indexes/${index.uid}/search` - const client = new MeiliSearch({ host }) - const strippedHost = trailing ? host.slice(0, -1) : host + const route = `indexes/${index.uid}/search`; + const client = new MeiliSearch({ host }); + const strippedHost = trailing ? host.slice(0, -1) : host; await expect(client.index(index.uid).search()).rejects.toHaveProperty( 'message', - `Request to ${strippedHost}/${route} has failed` - ) - }) + `Request to ${strippedHost}/${route} has failed`, + ); + }); test(`Test post search route`, async () => { - const route = `indexes/${index.uid}/search` - const client = new MeiliSearch({ host }) - const strippedHost = trailing ? host.slice(0, -1) : host + const route = `indexes/${index.uid}/search`; + const client = new MeiliSearch({ host }); + const strippedHost = trailing ? host.slice(0, -1) : host; await expect(client.index(index.uid).search()).rejects.toHaveProperty( 'message', - `Request to ${strippedHost}/${route} has failed` - ) - }) -}) + `Request to ${strippedHost}/${route} has failed`, + ); + }); +}); -jest.setTimeout(100 * 1000) +jest.setTimeout(100 * 1000); afterAll(() => { - return clearAllIndexes(config) -}) + return clearAllIndexes(config); +}); diff --git a/tests/searchCutoffMs.ts b/tests/searchCutoffMs.ts index ec4206f3c..a96a07085 100644 --- a/tests/searchCutoffMs.ts +++ b/tests/searchCutoffMs.ts @@ -1,4 +1,4 @@ -import { ErrorStatusCode } from '../src/types' +import { ErrorStatusCode } from '../src/types'; import { clearAllIndexes, config, @@ -6,164 +6,164 @@ import { MeiliSearch, getClient, dataset, -} from './utils/meilisearch-test-utils' +} from './utils/meilisearch-test-utils'; const index = { uid: 'movies_test', -} +}; -const DEFAULT_SEARCHCUTOFFMS = null +const DEFAULT_SEARCHCUTOFFMS = null; -jest.setTimeout(100 * 1000) +jest.setTimeout(100 * 1000); afterAll(() => { - return clearAllIndexes(config) -}) + return clearAllIndexes(config); +}); describe.each([{ permission: 'Master' }, { permission: 'Admin' }])( 'Test on searchCutoffMs', ({ permission }) => { beforeEach(async () => { - await clearAllIndexes(config) - const client = await getClient('Master') - const { taskUid } = await client.index(index.uid).addDocuments(dataset) - await client.waitForTask(taskUid) - }) + await clearAllIndexes(config); + const client = await getClient('Master'); + const { taskUid } = await client.index(index.uid).addDocuments(dataset); + await client.waitForTask(taskUid); + }); test(`${permission} key: Get default searchCutoffMs settings`, async () => { - const client = await getClient(permission) - const response = await client.index(index.uid).getSearchCutoffMs() + const client = await getClient(permission); + const response = await client.index(index.uid).getSearchCutoffMs(); - expect(response).toEqual(DEFAULT_SEARCHCUTOFFMS) - }) + expect(response).toEqual(DEFAULT_SEARCHCUTOFFMS); + }); test(`${permission} key: Update searchCutoffMs to valid value`, async () => { - const client = await getClient(permission) - const newSearchCutoffMs = 100 + const client = await getClient(permission); + const newSearchCutoffMs = 100; const task = await client .index(index.uid) - .updateSearchCutoffMs(newSearchCutoffMs) - await client.waitForTask(task.taskUid) + .updateSearchCutoffMs(newSearchCutoffMs); + await client.waitForTask(task.taskUid); - const response = await client.index(index.uid).getSearchCutoffMs() + const response = await client.index(index.uid).getSearchCutoffMs(); - expect(response).toEqual(newSearchCutoffMs) - }) + expect(response).toEqual(newSearchCutoffMs); + }); test(`${permission} key: Update searchCutoffMs to null`, async () => { - const client = await getClient(permission) - const newSearchCutoffMs = null + const client = await getClient(permission); + const newSearchCutoffMs = null; const task = await client .index(index.uid) - .updateSearchCutoffMs(newSearchCutoffMs) - await client.index(index.uid).waitForTask(task.taskUid) + .updateSearchCutoffMs(newSearchCutoffMs); + await client.index(index.uid).waitForTask(task.taskUid); - const response = await client.index(index.uid).getSearchCutoffMs() + const response = await client.index(index.uid).getSearchCutoffMs(); - expect(response).toEqual(DEFAULT_SEARCHCUTOFFMS) - }) + expect(response).toEqual(DEFAULT_SEARCHCUTOFFMS); + }); test(`${permission} key: Update searchCutoffMs with invalid value`, async () => { - const client = await getClient(permission) - const newSearchCutoffMs = 'hello' as any // bad searchCutoffMs value + const client = await getClient(permission); + const newSearchCutoffMs = 'hello' as any; // bad searchCutoffMs value await expect( - client.index(index.uid).updateSearchCutoffMs(newSearchCutoffMs) + client.index(index.uid).updateSearchCutoffMs(newSearchCutoffMs), ).rejects.toHaveProperty( 'cause.code', - ErrorStatusCode.INVALID_SETTINGS_SEARCH_CUTOFF_MS - ) - }) + ErrorStatusCode.INVALID_SETTINGS_SEARCH_CUTOFF_MS, + ); + }); test(`${permission} key: Reset searchCutoffMs`, async () => { - const client = await getClient(permission) - const newSearchCutoffMs = 100 + const client = await getClient(permission); + const newSearchCutoffMs = 100; const updateTask = await client .index(index.uid) - .updateSearchCutoffMs(newSearchCutoffMs) - await client.waitForTask(updateTask.taskUid) - const task = await client.index(index.uid).resetSearchCutoffMs() - await client.waitForTask(task.taskUid) + .updateSearchCutoffMs(newSearchCutoffMs); + await client.waitForTask(updateTask.taskUid); + const task = await client.index(index.uid).resetSearchCutoffMs(); + await client.waitForTask(task.taskUid); - const response = await client.index(index.uid).getSearchCutoffMs() + const response = await client.index(index.uid).getSearchCutoffMs(); - expect(response).toEqual(DEFAULT_SEARCHCUTOFFMS) - }) - } -) + expect(response).toEqual(DEFAULT_SEARCHCUTOFFMS); + }); + }, +); describe.each([{ permission: 'Search' }])( 'Test on searchCutoffMs', ({ permission }) => { beforeEach(async () => { - const client = await getClient('Master') - const { taskUid } = await client.createIndex(index.uid) - await client.waitForTask(taskUid) - }) + const client = await getClient('Master'); + const { taskUid } = await client.createIndex(index.uid); + await client.waitForTask(taskUid); + }); test(`${permission} key: try to get searchCutoffMs and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect( - client.index(index.uid).getSearchCutoffMs() - ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY) - }) + client.index(index.uid).getSearchCutoffMs(), + ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY); + }); test(`${permission} key: try to update searchCutoffMs and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect( - client.index(index.uid).updateSearchCutoffMs(100) - ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY) - }) + client.index(index.uid).updateSearchCutoffMs(100), + ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY); + }); test(`${permission} key: try to reset searchCutoffMs and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect( - client.index(index.uid).resetSearchCutoffMs() - ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY) - }) - } -) + client.index(index.uid).resetSearchCutoffMs(), + ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY); + }); + }, +); describe.each([{ permission: 'No' }])( 'Test on searchCutoffMs', ({ permission }) => { beforeAll(async () => { - const client = await getClient('Master') - const { taskUid } = await client.createIndex(index.uid) - await client.waitForTask(taskUid) - }) + const client = await getClient('Master'); + const { taskUid } = await client.createIndex(index.uid); + await client.waitForTask(taskUid); + }); test(`${permission} key: try to get searchCutoffMs and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect( - client.index(index.uid).getSearchCutoffMs() + client.index(index.uid).getSearchCutoffMs(), ).rejects.toHaveProperty( 'cause.code', - ErrorStatusCode.MISSING_AUTHORIZATION_HEADER - ) - }) + ErrorStatusCode.MISSING_AUTHORIZATION_HEADER, + ); + }); test(`${permission} key: try to update searchCutoffMs and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect( - client.index(index.uid).updateSearchCutoffMs(100) + client.index(index.uid).updateSearchCutoffMs(100), ).rejects.toHaveProperty( 'cause.code', - ErrorStatusCode.MISSING_AUTHORIZATION_HEADER - ) - }) + ErrorStatusCode.MISSING_AUTHORIZATION_HEADER, + ); + }); test(`${permission} key: try to reset searchCutoffMs and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect( - client.index(index.uid).resetSearchCutoffMs() + client.index(index.uid).resetSearchCutoffMs(), ).rejects.toHaveProperty( 'cause.code', - ErrorStatusCode.MISSING_AUTHORIZATION_HEADER - ) - }) - } -) + ErrorStatusCode.MISSING_AUTHORIZATION_HEADER, + ); + }); + }, +); describe.each([ { host: BAD_HOST, trailing: false }, @@ -171,38 +171,38 @@ describe.each([ { host: `${BAD_HOST}/trailing/`, trailing: true }, ])('Tests on url construction', ({ host, trailing }) => { test(`Test getSearchCutoffMs route`, async () => { - const route = `indexes/${index.uid}/settings/search-cutoff-ms` - const client = new MeiliSearch({ host }) - const strippedHost = trailing ? host.slice(0, -1) : host + const route = `indexes/${index.uid}/settings/search-cutoff-ms`; + const client = new MeiliSearch({ host }); + const strippedHost = trailing ? host.slice(0, -1) : host; await expect( - client.index(index.uid).getSearchCutoffMs() + client.index(index.uid).getSearchCutoffMs(), ).rejects.toHaveProperty( 'message', - `Request to ${strippedHost}/${route} has failed` - ) - }) + `Request to ${strippedHost}/${route} has failed`, + ); + }); test(`Test updateSearchCutoffMs route`, async () => { - const route = `indexes/${index.uid}/settings/search-cutoff-ms` - const client = new MeiliSearch({ host }) - const strippedHost = trailing ? host.slice(0, -1) : host + const route = `indexes/${index.uid}/settings/search-cutoff-ms`; + const client = new MeiliSearch({ host }); + const strippedHost = trailing ? host.slice(0, -1) : host; await expect( - client.index(index.uid).updateSearchCutoffMs(null) + client.index(index.uid).updateSearchCutoffMs(null), ).rejects.toHaveProperty( 'message', - `Request to ${strippedHost}/${route} has failed` - ) - }) + `Request to ${strippedHost}/${route} has failed`, + ); + }); test(`Test resetSearchCutoffMs route`, async () => { - const route = `indexes/${index.uid}/settings/search-cutoff-ms` - const client = new MeiliSearch({ host }) - const strippedHost = trailing ? host.slice(0, -1) : host + const route = `indexes/${index.uid}/settings/search-cutoff-ms`; + const client = new MeiliSearch({ host }); + const strippedHost = trailing ? host.slice(0, -1) : host; await expect( - client.index(index.uid).resetSearchCutoffMs() + client.index(index.uid).resetSearchCutoffMs(), ).rejects.toHaveProperty( 'message', - `Request to ${strippedHost}/${route} has failed` - ) - }) -}) + `Request to ${strippedHost}/${route} has failed`, + ); + }); +}); diff --git a/tests/searchable_attributes.test.ts b/tests/searchable_attributes.test.ts index e546b9996..82132d721 100644 --- a/tests/searchable_attributes.test.ts +++ b/tests/searchable_attributes.test.ts @@ -1,4 +1,4 @@ -import { ErrorStatusCode } from '../src/types' +import { ErrorStatusCode } from '../src/types'; import { clearAllIndexes, config, @@ -6,152 +6,152 @@ import { MeiliSearch, getClient, dataset, -} from './utils/meilisearch-test-utils' +} from './utils/meilisearch-test-utils'; const index = { uid: 'movies_test', -} +}; -jest.setTimeout(100 * 1000) +jest.setTimeout(100 * 1000); afterAll(() => { - return clearAllIndexes(config) -}) + return clearAllIndexes(config); +}); describe.each([{ permission: 'Master' }, { permission: 'Admin' }])( 'Test on searchable attributes', ({ permission }) => { beforeEach(async () => { - const client = await getClient('Master') - const { taskUid } = await client.index(index.uid).addDocuments(dataset) - await client.waitForTask(taskUid) - }) + const client = await getClient('Master'); + const { taskUid } = await client.index(index.uid).addDocuments(dataset); + await client.waitForTask(taskUid); + }); test(`${permission} key: Get default searchable attributes`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const response: string[] = await client .index(index.uid) - .getSearchableAttributes() + .getSearchableAttributes(); - expect(response).toEqual(['*']) - }) + expect(response).toEqual(['*']); + }); test(`${permission} key: Update searchable attributes`, async () => { - const client = await getClient(permission) - const newSearchableAttributes = ['title'] + const client = await getClient(permission); + const newSearchableAttributes = ['title']; const task = await client .index(index.uid) - .updateSearchableAttributes(newSearchableAttributes) - await client.index(index.uid).waitForTask(task.taskUid) + .updateSearchableAttributes(newSearchableAttributes); + await client.index(index.uid).waitForTask(task.taskUid); const response: string[] = await client .index(index.uid) - .getSearchableAttributes() + .getSearchableAttributes(); - expect(response).toEqual(newSearchableAttributes) - }) + expect(response).toEqual(newSearchableAttributes); + }); test(`${permission} key: Update searchable attributes at null`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const task = await client .index(index.uid) - .updateSearchableAttributes(null) - await client.index(index.uid).waitForTask(task.taskUid) + .updateSearchableAttributes(null); + await client.index(index.uid).waitForTask(task.taskUid); const response: string[] = await client .index(index.uid) - .getSearchableAttributes() + .getSearchableAttributes(); - expect(response).toEqual(['*']) - }) + expect(response).toEqual(['*']); + }); test(`${permission} key: Reset searchable attributes`, async () => { - const client = await getClient(permission) - const task = await client.index(index.uid).resetSearchableAttributes() - await client.index(index.uid).waitForTask(task.taskUid) + const client = await getClient(permission); + const task = await client.index(index.uid).resetSearchableAttributes(); + await client.index(index.uid).waitForTask(task.taskUid); const response: string[] = await client .index(index.uid) - .getSearchableAttributes() + .getSearchableAttributes(); - expect(response).toEqual(['*']) - }) - } -) + expect(response).toEqual(['*']); + }); + }, +); describe.each([{ permission: 'Search' }])( 'Test on searchable attributes', ({ permission }) => { beforeEach(async () => { - const client = await getClient('Master') - const { taskUid } = await client.createIndex(index.uid) - await client.waitForTask(taskUid) - }) + const client = await getClient('Master'); + const { taskUid } = await client.createIndex(index.uid); + await client.waitForTask(taskUid); + }); test(`${permission} key: try to get searchable attributes and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect( - client.index(index.uid).getSearchableAttributes() - ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY) - }) + client.index(index.uid).getSearchableAttributes(), + ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY); + }); test(`${permission} key: try to update searchable attributes and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect( - client.index(index.uid).updateSearchableAttributes([]) - ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY) - }) + client.index(index.uid).updateSearchableAttributes([]), + ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY); + }); test(`${permission} key: try to reset searchable attributes and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect( - client.index(index.uid).resetSearchableAttributes() - ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY) - }) - } -) + client.index(index.uid).resetSearchableAttributes(), + ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY); + }); + }, +); describe.each([{ permission: 'No' }])( 'Test on searchable attributes', ({ permission }) => { beforeAll(async () => { - const client = await getClient('Master') - const { taskUid } = await client.createIndex(index.uid) - await client.waitForTask(taskUid) - }) + const client = await getClient('Master'); + const { taskUid } = await client.createIndex(index.uid); + await client.waitForTask(taskUid); + }); test(`${permission} key: try to get searchable attributes and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect( - client.index(index.uid).getSearchableAttributes() + client.index(index.uid).getSearchableAttributes(), ).rejects.toHaveProperty( 'cause.code', - ErrorStatusCode.MISSING_AUTHORIZATION_HEADER - ) - }) + ErrorStatusCode.MISSING_AUTHORIZATION_HEADER, + ); + }); test(`${permission} key: try to update searchable attributes and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect( - client.index(index.uid).updateSearchableAttributes([]) + client.index(index.uid).updateSearchableAttributes([]), ).rejects.toHaveProperty( 'cause.code', - ErrorStatusCode.MISSING_AUTHORIZATION_HEADER - ) - }) + ErrorStatusCode.MISSING_AUTHORIZATION_HEADER, + ); + }); test(`${permission} key: try to reset searchable attributes and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect( - client.index(index.uid).resetSearchableAttributes() + client.index(index.uid).resetSearchableAttributes(), ).rejects.toHaveProperty( 'cause.code', - ErrorStatusCode.MISSING_AUTHORIZATION_HEADER - ) - }) - } -) + ErrorStatusCode.MISSING_AUTHORIZATION_HEADER, + ); + }); + }, +); describe.each([ { host: BAD_HOST, trailing: false }, @@ -159,38 +159,38 @@ describe.each([ { host: `${BAD_HOST}/trailing/`, trailing: true }, ])('Tests on url construction', ({ host, trailing }) => { test(`Test getSearchableAttributes route`, async () => { - const route = `indexes/${index.uid}/settings/searchable-attributes` - const client = new MeiliSearch({ host }) - const strippedHost = trailing ? host.slice(0, -1) : host + const route = `indexes/${index.uid}/settings/searchable-attributes`; + const client = new MeiliSearch({ host }); + const strippedHost = trailing ? host.slice(0, -1) : host; await expect( - client.index(index.uid).getSearchableAttributes() + client.index(index.uid).getSearchableAttributes(), ).rejects.toHaveProperty( 'message', - `Request to ${strippedHost}/${route} has failed` - ) - }) + `Request to ${strippedHost}/${route} has failed`, + ); + }); test(`Test updateSearchableAttributes route`, async () => { - const route = `indexes/${index.uid}/settings/searchable-attributes` - const client = new MeiliSearch({ host }) - const strippedHost = trailing ? host.slice(0, -1) : host + const route = `indexes/${index.uid}/settings/searchable-attributes`; + const client = new MeiliSearch({ host }); + const strippedHost = trailing ? host.slice(0, -1) : host; await expect( - client.index(index.uid).updateSearchableAttributes([]) + client.index(index.uid).updateSearchableAttributes([]), ).rejects.toHaveProperty( 'message', - `Request to ${strippedHost}/${route} has failed` - ) - }) + `Request to ${strippedHost}/${route} has failed`, + ); + }); test(`Test resetSearchableAttributes route`, async () => { - const route = `indexes/${index.uid}/settings/searchable-attributes` - const client = new MeiliSearch({ host }) - const strippedHost = trailing ? host.slice(0, -1) : host + const route = `indexes/${index.uid}/settings/searchable-attributes`; + const client = new MeiliSearch({ host }); + const strippedHost = trailing ? host.slice(0, -1) : host; await expect( - client.index(index.uid).resetSearchableAttributes() + client.index(index.uid).resetSearchableAttributes(), ).rejects.toHaveProperty( 'message', - `Request to ${strippedHost}/${route} has failed` - ) - }) -}) + `Request to ${strippedHost}/${route} has failed`, + ); + }); +}); diff --git a/tests/separator_tokens.test.ts b/tests/separator_tokens.test.ts index c23f88c64..e571b7012 100644 --- a/tests/separator_tokens.test.ts +++ b/tests/separator_tokens.test.ts @@ -1,4 +1,4 @@ -import { EnqueuedTask } from '../src/enqueued-task' +import { EnqueuedTask } from '../src/enqueued-task'; import { clearAllIndexes, config, @@ -6,81 +6,81 @@ import { MeiliSearch, getClient, dataset, -} from './utils/meilisearch-test-utils' +} from './utils/meilisearch-test-utils'; const index = { uid: 'movies_test', -} +}; -jest.setTimeout(100 * 1000) +jest.setTimeout(100 * 1000); afterAll(() => { - return clearAllIndexes(config) -}) + return clearAllIndexes(config); +}); describe.each([{ permission: 'Master' }, { permission: 'Admin' }])( 'Test on separator tokens', ({ permission }) => { beforeEach(async () => { - const client = await getClient('Master') - const { taskUid } = await client.index(index.uid).addDocuments(dataset) - await client.waitForTask(taskUid) - }) + const client = await getClient('Master'); + const { taskUid } = await client.index(index.uid).addDocuments(dataset); + await client.waitForTask(taskUid); + }); test(`${permission} key: Get default separator tokens`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const response: string[] = await client .index(index.uid) - .getSeparatorTokens() + .getSeparatorTokens(); - expect(response).toEqual([]) - }) + expect(response).toEqual([]); + }); test(`${permission} key: Update separator tokens`, async () => { - const client = await getClient(permission) - const newSeparatorTokens = ['&sep', '/', '|'] + const client = await getClient(permission); + const newSeparatorTokens = ['&sep', '/', '|']; const task: EnqueuedTask = await client .index(index.uid) - .updateSeparatorTokens(newSeparatorTokens) - await client.index(index.uid).waitForTask(task.taskUid) + .updateSeparatorTokens(newSeparatorTokens); + await client.index(index.uid).waitForTask(task.taskUid); const response: string[] = await client .index(index.uid) - .getSeparatorTokens() + .getSeparatorTokens(); - expect(response).toEqual(newSeparatorTokens) - }) + expect(response).toEqual(newSeparatorTokens); + }); test(`${permission} key: Update separator tokens with null value`, async () => { - const client = await getClient(permission) - const newSeparatorTokens = null + const client = await getClient(permission); + const newSeparatorTokens = null; const task: EnqueuedTask = await client .index(index.uid) - .updateSeparatorTokens(newSeparatorTokens) - await client.index(index.uid).waitForTask(task.taskUid) + .updateSeparatorTokens(newSeparatorTokens); + await client.index(index.uid).waitForTask(task.taskUid); const response: string[] = await client .index(index.uid) - .getSeparatorTokens() + .getSeparatorTokens(); - expect(response).toEqual([]) - }) + expect(response).toEqual([]); + }); test(`${permission} key: Reset separator tokens`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const task: EnqueuedTask = await client .index(index.uid) - .resetSeparatorTokens() - await client.index(index.uid).waitForTask(task.taskUid) + .resetSeparatorTokens(); + await client.index(index.uid).waitForTask(task.taskUid); const response: string[] = await client .index(index.uid) - .getSeparatorTokens() + .getSeparatorTokens(); - expect(response).toEqual([]) - }) - } -) + expect(response).toEqual([]); + }); + }, +); describe.each([ { host: BAD_HOST, trailing: false }, @@ -88,38 +88,38 @@ describe.each([ { host: `${BAD_HOST}/trailing/`, trailing: true }, ])('Tests on url construction', ({ host, trailing }) => { test(`Test getSeparatorTokens route`, async () => { - const route = `indexes/${index.uid}/settings/separator-tokens` - const client = new MeiliSearch({ host }) - const strippedHost = trailing ? host.slice(0, -1) : host + const route = `indexes/${index.uid}/settings/separator-tokens`; + const client = new MeiliSearch({ host }); + const strippedHost = trailing ? host.slice(0, -1) : host; await expect( - client.index(index.uid).getSeparatorTokens() + client.index(index.uid).getSeparatorTokens(), ).rejects.toHaveProperty( 'message', - `Request to ${strippedHost}/${route} has failed` - ) - }) + `Request to ${strippedHost}/${route} has failed`, + ); + }); test(`Test updateSeparatorTokens route`, async () => { - const route = `indexes/${index.uid}/settings/separator-tokens` - const client = new MeiliSearch({ host }) - const strippedHost = trailing ? host.slice(0, -1) : host + const route = `indexes/${index.uid}/settings/separator-tokens`; + const client = new MeiliSearch({ host }); + const strippedHost = trailing ? host.slice(0, -1) : host; await expect( - client.index(index.uid).updateSeparatorTokens([]) + client.index(index.uid).updateSeparatorTokens([]), ).rejects.toHaveProperty( 'message', - `Request to ${strippedHost}/${route} has failed` - ) - }) + `Request to ${strippedHost}/${route} has failed`, + ); + }); test(`Test resetSeparatorTokens route`, async () => { - const route = `indexes/${index.uid}/settings/separator-tokens` - const client = new MeiliSearch({ host }) - const strippedHost = trailing ? host.slice(0, -1) : host + const route = `indexes/${index.uid}/settings/separator-tokens`; + const client = new MeiliSearch({ host }); + const strippedHost = trailing ? host.slice(0, -1) : host; await expect( - client.index(index.uid).resetSeparatorTokens() + client.index(index.uid).resetSeparatorTokens(), ).rejects.toHaveProperty( 'message', - `Request to ${strippedHost}/${route} has failed` - ) - }) -}) + `Request to ${strippedHost}/${route} has failed`, + ); + }); +}); diff --git a/tests/settings.test.ts b/tests/settings.test.ts index 9834bd5be..9c77d74de 100644 --- a/tests/settings.test.ts +++ b/tests/settings.test.ts @@ -1,4 +1,4 @@ -import { ErrorStatusCode, Settings } from '../src/types' +import { ErrorStatusCode, Settings } from '../src/types'; import { clearAllIndexes, config, @@ -8,59 +8,59 @@ import { dataset, getKey, HOST, -} from './utils/meilisearch-test-utils' +} from './utils/meilisearch-test-utils'; const index = { uid: 'movies_test', -} +}; const indexAndPK = { uid: 'movies_test_with_pk', primaryKey: 'id', -} +}; -jest.setTimeout(100 * 1000) +jest.setTimeout(100 * 1000); afterAll(() => { - return clearAllIndexes(config) -}) + return clearAllIndexes(config); +}); describe.each([{ permission: 'Master' }, { permission: 'Admin' }])( 'Test on settings', ({ permission }) => { beforeEach(async () => { - await clearAllIndexes(config) - const client = await getClient('Master') + await clearAllIndexes(config); + const client = await getClient('Master'); const { taskUid: AddDocPkTask } = await client .index(indexAndPK.uid) .addDocuments(dataset, { primaryKey: indexAndPK.primaryKey, - }) - await client.waitForTask(AddDocPkTask) + }); + await client.waitForTask(AddDocPkTask); const { taskUid: AddDocTask } = await client .index(index.uid) - .addDocuments(dataset, {}) - await client.waitForTask(AddDocTask) - }) + .addDocuments(dataset, {}); + await client.waitForTask(AddDocTask); + }); test(`${permission} key: Get default settings of an index`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); - const response = await client.index(index.uid).getSettings() + const response = await client.index(index.uid).getSettings(); - expect(response).toMatchSnapshot() - }) + expect(response).toMatchSnapshot(); + }); test(`${permission} key: Get default settings of empty index with primary key`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); - const response = await client.index(indexAndPK.uid).getSettings() + const response = await client.index(indexAndPK.uid).getSettings(); - expect(response).toMatchSnapshot() - }) + expect(response).toMatchSnapshot(); + }); test(`${permission} key: Update settings`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const newSettings: Settings = { filterableAttributes: ['title'], sortableAttributes: ['title'], @@ -93,20 +93,20 @@ describe.each([{ permission: 'Master' }, { permission: 'Admin' }])( nonSeparatorTokens: ['&sep', '/', '|'], dictionary: ['J. K.', 'J. R. R.'], searchCutoffMs: 1000, - } + }; // Add the settings - const task = await client.index(index.uid).updateSettings(newSettings) - await client.index(index.uid).waitForTask(task.taskUid) + const task = await client.index(index.uid).updateSettings(newSettings); + await client.index(index.uid).waitForTask(task.taskUid); // Fetch the settings - const response = await client.index(index.uid).getSettings() + const response = await client.index(index.uid).getSettings(); // tests - expect(response).toMatchSnapshot() - }) + expect(response).toMatchSnapshot(); + }); test(`${permission} key: Update settings with all null values`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const newSettings: Settings = { filterableAttributes: null, sortableAttributes: null, @@ -136,21 +136,21 @@ describe.each([{ permission: 'Master' }, { permission: 'Admin' }])( nonSeparatorTokens: null, dictionary: null, searchCutoffMs: null, - } + }; // Add the settings - const task = await client.index(index.uid).updateSettings(newSettings) - await client.index(index.uid).waitForTask(task.taskUid) + const task = await client.index(index.uid).updateSettings(newSettings); + await client.index(index.uid).waitForTask(task.taskUid); // Fetch the settings - const response = await client.index(index.uid).getSettings() + const response = await client.index(index.uid).getSettings(); // tests - expect(response).toMatchSnapshot() - }) + expect(response).toMatchSnapshot(); + }); test(`${permission} key: Update embedders settings `, async () => { - const client = await getClient(permission) - const key = await getKey(permission) + const client = await getClient(permission); + const key = await getKey(permission); await fetch(`${HOST}/experimental-features`, { body: JSON.stringify({ vectorStore: true }), @@ -159,7 +159,7 @@ describe.each([{ permission: 'Master' }, { permission: 'Admin' }])( 'Content-Type': 'application/json', }, method: 'PATCH', - }) + }); const newSettings: Settings = { embedders: { @@ -169,54 +169,54 @@ describe.each([{ permission: 'Master' }, { permission: 'Admin' }])( 'sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2', }, }, - } - const task = await client.index(index.uid).updateSettings(newSettings) - await client.index(index.uid).waitForTask(task.taskUid) - const response = await client.index(index.uid).getSettings() + }; + const task = await client.index(index.uid).updateSettings(newSettings); + await client.index(index.uid).waitForTask(task.taskUid); + const response = await client.index(index.uid).getSettings(); - expect(response).toMatchSnapshot() - }) + expect(response).toMatchSnapshot(); + }); test(`${permission} key: Update settings on empty index with primary key`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const newSettings = { distinctAttribute: 'title', rankingRules: ['title:asc', 'typo'], stopWords: ['the'], - } + }; const task = await client .index(indexAndPK.uid) - .updateSettings(newSettings) - await client.index(indexAndPK.uid).waitForTask(task.taskUid) + .updateSettings(newSettings); + await client.index(indexAndPK.uid).waitForTask(task.taskUid); - const response = await client.index(indexAndPK.uid).getSettings() + const response = await client.index(indexAndPK.uid).getSettings(); - expect(response).toMatchSnapshot() - }) + expect(response).toMatchSnapshot(); + }); test(`${permission} key: Reset settings`, async () => { - const client = await getClient(permission) - const task = await client.index(index.uid).resetSettings() - await client.index(index.uid).waitForTask(task.taskUid) + const client = await getClient(permission); + const task = await client.index(index.uid).resetSettings(); + await client.index(index.uid).waitForTask(task.taskUid); - const response = await client.index(index.uid).getSettings() + const response = await client.index(index.uid).getSettings(); - expect(response).toMatchSnapshot() - }) + expect(response).toMatchSnapshot(); + }); test(`${permission} key: Reset settings of empty index`, async () => { - const client = await getClient(permission) - const task = await client.index(indexAndPK.uid).resetSettings() - await client.index(index.uid).waitForTask(task.taskUid) + const client = await getClient(permission); + const task = await client.index(indexAndPK.uid).resetSettings(); + await client.index(index.uid).waitForTask(task.taskUid); - const response = await client.index(indexAndPK.uid).getSettings() + const response = await client.index(indexAndPK.uid).getSettings(); - expect(response).toMatchSnapshot() - }) + expect(response).toMatchSnapshot(); + }); test(`${permission} key: Reset embedders settings `, async () => { - const client = await getClient(permission) - const key = await getKey(permission) + const client = await getClient(permission); + const key = await getKey(permission); await fetch(`${HOST}/experimental-features`, { body: JSON.stringify({ vectorStore: true }), @@ -225,108 +225,108 @@ describe.each([{ permission: 'Master' }, { permission: 'Admin' }])( 'Content-Type': 'application/json', }, method: 'PATCH', - }) + }); const newSettings: Settings = { embedders: null, - } - const task = await client.index(index.uid).updateSettings(newSettings) - await client.index(index.uid).waitForTask(task.taskUid) - const response = await client.index(index.uid).getSettings() + }; + const task = await client.index(index.uid).updateSettings(newSettings); + await client.index(index.uid).waitForTask(task.taskUid); + const response = await client.index(index.uid).getSettings(); - expect(response).toMatchSnapshot() - }) + expect(response).toMatchSnapshot(); + }); test(`${permission} key: Update searchableAttributes settings on empty index`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const newSettings = { searchableAttributes: ['title'], - } - const task = await client.index(index.uid).updateSettings(newSettings) - await client.index(index.uid).waitForTask(task.taskUid) + }; + const task = await client.index(index.uid).updateSettings(newSettings); + await client.index(index.uid).waitForTask(task.taskUid); - const response = await client.index(index.uid).getSettings() + const response = await client.index(index.uid).getSettings(); - expect(response).toMatchSnapshot() - }) + expect(response).toMatchSnapshot(); + }); test(`${permission} key: Update searchableAttributes settings on empty index with a primary key`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const newSettings = { searchableAttributes: ['title'], - } + }; // Update settings const task = await client .index(indexAndPK.uid) - .updateSettings(newSettings) + .updateSettings(newSettings); // Wait for setting addition to be done - await client.index(index.uid).waitForTask(task.taskUid) + await client.index(index.uid).waitForTask(task.taskUid); // Fetch settings - const response = await client.index(indexAndPK.uid).getSettings() + const response = await client.index(indexAndPK.uid).getSettings(); - expect(response).toMatchSnapshot() - }) - } -) + expect(response).toMatchSnapshot(); + }); + }, +); describe.each([{ permission: 'Search' }])( 'Test on settings', ({ permission }) => { beforeEach(async () => { - await clearAllIndexes(config) - }) + await clearAllIndexes(config); + }); test(`${permission} key: try to get settings and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect( - client.index(index.uid).getSettings() - ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY) - }) + client.index(index.uid).getSettings(), + ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY); + }); test(`${permission} key: try to update settings and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect( - client.index(index.uid).updateSettings({}) - ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY) - }) + client.index(index.uid).updateSettings({}), + ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY); + }); test(`${permission} key: try to reset settings and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect( - client.index(index.uid).resetSettings() - ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY) - }) - } -) + client.index(index.uid).resetSettings(), + ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY); + }); + }, +); describe.each([{ permission: 'No' }])('Test on settings', ({ permission }) => { beforeEach(async () => { - await clearAllIndexes(config) - }) + await clearAllIndexes(config); + }); test(`${permission} key: try to get settings and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect(client.index(index.uid).getSettings()).rejects.toHaveProperty( 'cause.code', - ErrorStatusCode.MISSING_AUTHORIZATION_HEADER - ) - }) + ErrorStatusCode.MISSING_AUTHORIZATION_HEADER, + ); + }); test(`${permission} key: try to update settings and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect( - client.index(index.uid).updateSettings({}) + client.index(index.uid).updateSettings({}), ).rejects.toHaveProperty( 'cause.code', - ErrorStatusCode.MISSING_AUTHORIZATION_HEADER - ) - }) + ErrorStatusCode.MISSING_AUTHORIZATION_HEADER, + ); + }); test(`${permission} key: try to reset settings and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect( - client.index(index.uid).resetSettings() + client.index(index.uid).resetSettings(), ).rejects.toHaveProperty( 'cause.code', - ErrorStatusCode.MISSING_AUTHORIZATION_HEADER - ) - }) -}) + ErrorStatusCode.MISSING_AUTHORIZATION_HEADER, + ); + }); +}); describe.each([ { host: BAD_HOST, trailing: false }, @@ -334,36 +334,36 @@ describe.each([ { host: `${BAD_HOST}/trailing/`, trailing: true }, ])('Tests on url construction', ({ host, trailing }) => { test(`Test getSettings route`, async () => { - const route = `indexes/${index.uid}/settings` - const client = new MeiliSearch({ host }) - const strippedHost = trailing ? host.slice(0, -1) : host + const route = `indexes/${index.uid}/settings`; + const client = new MeiliSearch({ host }); + const strippedHost = trailing ? host.slice(0, -1) : host; await expect(client.index(index.uid).getSettings()).rejects.toHaveProperty( 'message', - `Request to ${strippedHost}/${route} has failed` - ) - }) + `Request to ${strippedHost}/${route} has failed`, + ); + }); test(`Test updateSettings route`, async () => { - const route = `indexes/${index.uid}/settings` - const client = new MeiliSearch({ host }) - const strippedHost = trailing ? host.slice(0, -1) : host + const route = `indexes/${index.uid}/settings`; + const client = new MeiliSearch({ host }); + const strippedHost = trailing ? host.slice(0, -1) : host; await expect( - client.index(index.uid).updateSettings({}) + client.index(index.uid).updateSettings({}), ).rejects.toHaveProperty( 'message', - `Request to ${strippedHost}/${route} has failed` - ) - }) + `Request to ${strippedHost}/${route} has failed`, + ); + }); test(`Test resetSettings route`, async () => { - const route = `indexes/${index.uid}/settings` - const client = new MeiliSearch({ host }) - const strippedHost = trailing ? host.slice(0, -1) : host + const route = `indexes/${index.uid}/settings`; + const client = new MeiliSearch({ host }); + const strippedHost = trailing ? host.slice(0, -1) : host; await expect( - client.index(index.uid).resetSettings() + client.index(index.uid).resetSettings(), ).rejects.toHaveProperty( 'message', - `Request to ${strippedHost}/${route} has failed` - ) - }) -}) + `Request to ${strippedHost}/${route} has failed`, + ); + }); +}); diff --git a/tests/snapshots.test.ts b/tests/snapshots.test.ts index 8ed7d8aac..bf78c87d4 100644 --- a/tests/snapshots.test.ts +++ b/tests/snapshots.test.ts @@ -1,53 +1,53 @@ -import { ErrorStatusCode } from '../src/types' +import { ErrorStatusCode } from '../src/types'; import { clearAllIndexes, config, MeiliSearch, BAD_HOST, getClient, -} from './utils/meilisearch-test-utils' +} from './utils/meilisearch-test-utils'; beforeEach(async () => { - await clearAllIndexes(config) -}) + await clearAllIndexes(config); +}); describe.each([{ permission: 'Master' }, { permission: 'Admin' }])( 'Test on snapshot', ({ permission }) => { test(`${permission} key: create a new snapshot`, async () => { - const client = await getClient(permission) - const { taskUid } = await client.createSnapshot() + const client = await getClient(permission); + const { taskUid } = await client.createSnapshot(); - await client.waitForTask(taskUid) - }) - } -) + await client.waitForTask(taskUid); + }); + }, +); describe.each([{ permission: 'Search' }])( 'Test on snapshot with search api key should not have access', ({ permission }) => { test(`${permission} key: try to create snapshot with search key and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect(client.createSnapshot()).rejects.toHaveProperty( 'cause.code', - ErrorStatusCode.INVALID_API_KEY - ) - }) - } -) + ErrorStatusCode.INVALID_API_KEY, + ); + }); + }, +); describe.each([{ permission: 'No' }])( 'Test on snapshot without api key should not have access', ({ permission }) => { test(`${permission} key: try to create snapshot with no key and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect(client.createSnapshot()).rejects.toHaveProperty( 'cause.code', - ErrorStatusCode.MISSING_AUTHORIZATION_HEADER - ) - }) - } -) + ErrorStatusCode.MISSING_AUTHORIZATION_HEADER, + ); + }); + }, +); describe.each([ { host: BAD_HOST, trailing: false }, @@ -55,13 +55,13 @@ describe.each([ { host: `${BAD_HOST}/trailing/`, trailing: true }, ])('Tests on url construction', ({ host, trailing }) => { test(`Test createSnapshot route`, async () => { - const route = `snapshots` - const client = new MeiliSearch({ host }) - const strippedHost = trailing ? host.slice(0, -1) : host + const route = `snapshots`; + const client = new MeiliSearch({ host }); + const strippedHost = trailing ? host.slice(0, -1) : host; await expect(client.createSnapshot()).rejects.toHaveProperty( 'message', - `Request to ${strippedHost}/${route} has failed` - ) - }) -}) + `Request to ${strippedHost}/${route} has failed`, + ); + }); +}); diff --git a/tests/sortable_attributes.test.ts b/tests/sortable_attributes.test.ts index 13cb2f5b5..a03069696 100644 --- a/tests/sortable_attributes.test.ts +++ b/tests/sortable_attributes.test.ts @@ -1,4 +1,4 @@ -import { ErrorStatusCode } from '../src/types' +import { ErrorStatusCode } from '../src/types'; import { clearAllIndexes, config, @@ -6,147 +6,147 @@ import { MeiliSearch, getClient, dataset, -} from './utils/meilisearch-test-utils' +} from './utils/meilisearch-test-utils'; const index = { uid: 'movies_test', -} +}; -jest.setTimeout(100 * 1000) +jest.setTimeout(100 * 1000); afterAll(() => { - return clearAllIndexes(config) -}) + return clearAllIndexes(config); +}); describe.each([{ permission: 'Master' }, { permission: 'Admin' }])( 'Test on sortable attributes', ({ permission }) => { beforeEach(async () => { - const client = await getClient('Master') - const { taskUid } = await client.createIndex(index.uid) - await client.waitForTask(taskUid) + const client = await getClient('Master'); + const { taskUid } = await client.createIndex(index.uid); + await client.waitForTask(taskUid); const { taskUid: docTask } = await client .index(index.uid) - .addDocuments(dataset) - await client.waitForTask(docTask) - }) + .addDocuments(dataset); + await client.waitForTask(docTask); + }); test(`${permission} key: Get default sortable attributes`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); - const response = await client.index(index.uid).getSortableAttributes() + const response = await client.index(index.uid).getSortableAttributes(); - expect(response).toEqual([]) - }) + expect(response).toEqual([]); + }); test(`${permission} key: Update sortable attributes`, async () => { - const client = await getClient(permission) - const newSortableAttributes = ['title'] + const client = await getClient(permission); + const newSortableAttributes = ['title']; const task = await client .index(index.uid) - .updateSortableAttributes(newSortableAttributes) - await client.index(index.uid).waitForTask(task.taskUid) + .updateSortableAttributes(newSortableAttributes); + await client.index(index.uid).waitForTask(task.taskUid); - const response = await client.index(index.uid).getSortableAttributes() - expect(response).toEqual(newSortableAttributes) - }) + const response = await client.index(index.uid).getSortableAttributes(); + expect(response).toEqual(newSortableAttributes); + }); test(`${permission} key: Update sortable attributes at null`, async () => { - const client = await getClient(permission) - const task = await client.index(index.uid).updateSortableAttributes(null) - await client.index(index.uid).waitForTask(task.taskUid) + const client = await getClient(permission); + const task = await client.index(index.uid).updateSortableAttributes(null); + await client.index(index.uid).waitForTask(task.taskUid); - const response = await client.index(index.uid).getSortableAttributes() + const response = await client.index(index.uid).getSortableAttributes(); - expect(response).toEqual([]) - }) + expect(response).toEqual([]); + }); test(`${permission} key: Reset sortable attributes`, async () => { - const client = await getClient(permission) - const task = await client.index(index.uid).resetSortableAttributes() - await client.index(index.uid).waitForTask(task.taskUid) + const client = await getClient(permission); + const task = await client.index(index.uid).resetSortableAttributes(); + await client.index(index.uid).waitForTask(task.taskUid); - const response = await client.index(index.uid).getSortableAttributes() + const response = await client.index(index.uid).getSortableAttributes(); - expect(response).toEqual([]) - }) - } -) + expect(response).toEqual([]); + }); + }, +); describe.each([{ permission: 'Search' }])( 'Test on sortable attributes', ({ permission }) => { beforeEach(async () => { - const client = await getClient('Master') - const { taskUid } = await client.createIndex(index.uid) - await client.waitForTask(taskUid) - }) + const client = await getClient('Master'); + const { taskUid } = await client.createIndex(index.uid); + await client.waitForTask(taskUid); + }); test(`${permission} key: try to get sortable attributes and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect( - client.index(index.uid).getSortableAttributes() - ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY) - }) + client.index(index.uid).getSortableAttributes(), + ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY); + }); test(`${permission} key: try to update sortable attributes and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect( - client.index(index.uid).updateSortableAttributes([]) - ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY) - }) + client.index(index.uid).updateSortableAttributes([]), + ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY); + }); test(`${permission} key: try to reset sortable attributes and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect( - client.index(index.uid).resetSortableAttributes() - ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY) - }) - } -) + client.index(index.uid).resetSortableAttributes(), + ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY); + }); + }, +); describe.each([{ permission: 'No' }])( 'Test on sortable attributes', ({ permission }) => { beforeAll(async () => { - const client = await getClient('Master') - const { taskUid } = await client.createIndex(index.uid) - await client.waitForTask(taskUid) - }) + const client = await getClient('Master'); + const { taskUid } = await client.createIndex(index.uid); + await client.waitForTask(taskUid); + }); test(`${permission} key: try to get sortable attributes and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect( - client.index(index.uid).getSortableAttributes() + client.index(index.uid).getSortableAttributes(), ).rejects.toHaveProperty( 'cause.code', - ErrorStatusCode.MISSING_AUTHORIZATION_HEADER - ) - }) + ErrorStatusCode.MISSING_AUTHORIZATION_HEADER, + ); + }); test(`${permission} key: try to update sortable attributes and be denied`, async () => { - const client = await getClient(permission) - const resetSortable: string[] = [] + const client = await getClient(permission); + const resetSortable: string[] = []; await expect( - client.index(index.uid).updateSortableAttributes(resetSortable) + client.index(index.uid).updateSortableAttributes(resetSortable), ).rejects.toHaveProperty( 'cause.code', - ErrorStatusCode.MISSING_AUTHORIZATION_HEADER - ) - }) + ErrorStatusCode.MISSING_AUTHORIZATION_HEADER, + ); + }); test(`${permission} key: try to reset sortable attributes and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect( - client.index(index.uid).resetSortableAttributes() + client.index(index.uid).resetSortableAttributes(), ).rejects.toHaveProperty( 'cause.code', - ErrorStatusCode.MISSING_AUTHORIZATION_HEADER - ) - }) - } -) + ErrorStatusCode.MISSING_AUTHORIZATION_HEADER, + ); + }); + }, +); describe.each([ { host: BAD_HOST, trailing: false }, @@ -154,38 +154,38 @@ describe.each([ { host: `${BAD_HOST}/trailing/`, trailing: true }, ])('Tests on url construction', ({ host, trailing }) => { test(`Test getSortableAttributes route`, async () => { - const route = `indexes/${index.uid}/settings/sortable-attributes` - const client = new MeiliSearch({ host }) - const strippedHost = trailing ? host.slice(0, -1) : host + const route = `indexes/${index.uid}/settings/sortable-attributes`; + const client = new MeiliSearch({ host }); + const strippedHost = trailing ? host.slice(0, -1) : host; await expect( - client.index(index.uid).getSortableAttributes() + client.index(index.uid).getSortableAttributes(), ).rejects.toHaveProperty( 'message', - `Request to ${strippedHost}/${route} has failed` - ) - }) + `Request to ${strippedHost}/${route} has failed`, + ); + }); test(`Test updateSortableAttributes route`, async () => { - const route = `indexes/${index.uid}/settings/sortable-attributes` - const client = new MeiliSearch({ host }) - const strippedHost = trailing ? host.slice(0, -1) : host + const route = `indexes/${index.uid}/settings/sortable-attributes`; + const client = new MeiliSearch({ host }); + const strippedHost = trailing ? host.slice(0, -1) : host; await expect( - client.index(index.uid).updateSortableAttributes([]) + client.index(index.uid).updateSortableAttributes([]), ).rejects.toHaveProperty( 'message', - `Request to ${strippedHost}/${route} has failed` - ) - }) + `Request to ${strippedHost}/${route} has failed`, + ); + }); test(`Test resetSortableAttributes route`, async () => { - const route = `indexes/${index.uid}/settings/sortable-attributes` - const client = new MeiliSearch({ host }) - const strippedHost = trailing ? host.slice(0, -1) : host + const route = `indexes/${index.uid}/settings/sortable-attributes`; + const client = new MeiliSearch({ host }); + const strippedHost = trailing ? host.slice(0, -1) : host; await expect( - client.index(index.uid).resetSortableAttributes() + client.index(index.uid).resetSortableAttributes(), ).rejects.toHaveProperty( 'message', - `Request to ${strippedHost}/${route} has failed` - ) - }) -}) + `Request to ${strippedHost}/${route} has failed`, + ); + }); +}); diff --git a/tests/stop_words.test.ts b/tests/stop_words.test.ts index 8eb923af4..5632b2b4c 100644 --- a/tests/stop_words.test.ts +++ b/tests/stop_words.test.ts @@ -1,5 +1,5 @@ -import { ErrorStatusCode } from '../src/types' -import { EnqueuedTask } from '../src/enqueued-task' +import { ErrorStatusCode } from '../src/types'; +import { EnqueuedTask } from '../src/enqueued-task'; import { clearAllIndexes, config, @@ -7,140 +7,140 @@ import { MeiliSearch, getClient, dataset, -} from './utils/meilisearch-test-utils' +} from './utils/meilisearch-test-utils'; const index = { uid: 'movies_test', -} +}; -jest.setTimeout(100 * 1000) +jest.setTimeout(100 * 1000); afterAll(() => { - return clearAllIndexes(config) -}) + return clearAllIndexes(config); +}); describe.each([{ permission: 'Master' }, { permission: 'Admin' }])( 'Test on stop words', ({ permission }) => { beforeEach(async () => { - const client = await getClient('Master') - const { taskUid } = await client.index(index.uid).addDocuments(dataset) - await client.waitForTask(taskUid) - }) + const client = await getClient('Master'); + const { taskUid } = await client.index(index.uid).addDocuments(dataset); + await client.waitForTask(taskUid); + }); test(`${permission} key: Get default stop words`, async () => { - const client = await getClient(permission) - const response: string[] = await client.index(index.uid).getStopWords() + const client = await getClient(permission); + const response: string[] = await client.index(index.uid).getStopWords(); - expect(response).toEqual([]) - }) + expect(response).toEqual([]); + }); test(`${permission} key: Update stop words`, async () => { - const client = await getClient(permission) - const newStopWords = ['the'] + const client = await getClient(permission); + const newStopWords = ['the']; const task: EnqueuedTask = await client .index(index.uid) - .updateStopWords(newStopWords) - await client.index(index.uid).waitForTask(task.taskUid) + .updateStopWords(newStopWords); + await client.index(index.uid).waitForTask(task.taskUid); - const response: string[] = await client.index(index.uid).getStopWords() + const response: string[] = await client.index(index.uid).getStopWords(); - expect(response).toEqual(newStopWords) - }) + expect(response).toEqual(newStopWords); + }); test(`${permission} key: Update stop words with null value`, async () => { - const client = await getClient(permission) - const newStopWords = null + const client = await getClient(permission); + const newStopWords = null; const task: EnqueuedTask = await client .index(index.uid) - .updateStopWords(newStopWords) - await client.index(index.uid).waitForTask(task.taskUid) + .updateStopWords(newStopWords); + await client.index(index.uid).waitForTask(task.taskUid); - const response: string[] = await client.index(index.uid).getStopWords() + const response: string[] = await client.index(index.uid).getStopWords(); - expect(response).toEqual([]) - }) + expect(response).toEqual([]); + }); test(`${permission} key: Reset stop words`, async () => { - const client = await getClient(permission) - const task: EnqueuedTask = await client.index(index.uid).resetStopWords() - await client.index(index.uid).waitForTask(task.taskUid) + const client = await getClient(permission); + const task: EnqueuedTask = await client.index(index.uid).resetStopWords(); + await client.index(index.uid).waitForTask(task.taskUid); - const response: string[] = await client.index(index.uid).getStopWords() + const response: string[] = await client.index(index.uid).getStopWords(); - expect(response).toEqual([]) - }) - } -) + expect(response).toEqual([]); + }); + }, +); describe.each([{ permission: 'Search' }])( 'Test on stop words', ({ permission }) => { beforeEach(async () => { - await clearAllIndexes(config) - }) + await clearAllIndexes(config); + }); test(`${permission} key: try to get stop words and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect( - client.index(index.uid).getStopWords() - ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY) - }) + client.index(index.uid).getStopWords(), + ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY); + }); test(`${permission} key: try to update stop words and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect( - client.index(index.uid).updateStopWords([]) - ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY) - }) + client.index(index.uid).updateStopWords([]), + ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY); + }); test(`${permission} key: try to reset stop words and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect( - client.index(index.uid).resetStopWords() - ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY) - }) - } -) + client.index(index.uid).resetStopWords(), + ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY); + }); + }, +); describe.each([{ permission: 'No' }])( 'Test on stop words', ({ permission }) => { beforeEach(async () => { - await clearAllIndexes(config) - }) + await clearAllIndexes(config); + }); test(`${permission} key: try to get stop words and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect( - client.index(index.uid).getStopWords() + client.index(index.uid).getStopWords(), ).rejects.toHaveProperty( 'cause.code', - ErrorStatusCode.MISSING_AUTHORIZATION_HEADER - ) - }) + ErrorStatusCode.MISSING_AUTHORIZATION_HEADER, + ); + }); test(`${permission} key: try to update stop words and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect( - client.index(index.uid).updateStopWords([]) + client.index(index.uid).updateStopWords([]), ).rejects.toHaveProperty( 'cause.code', - ErrorStatusCode.MISSING_AUTHORIZATION_HEADER - ) - }) + ErrorStatusCode.MISSING_AUTHORIZATION_HEADER, + ); + }); test(`${permission} key: try to reset stop words and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect( - client.index(index.uid).resetStopWords() + client.index(index.uid).resetStopWords(), ).rejects.toHaveProperty( 'cause.code', - ErrorStatusCode.MISSING_AUTHORIZATION_HEADER - ) - }) - } -) + ErrorStatusCode.MISSING_AUTHORIZATION_HEADER, + ); + }); + }, +); describe.each([ { host: BAD_HOST, trailing: false }, @@ -148,36 +148,36 @@ describe.each([ { host: `${BAD_HOST}/trailing/`, trailing: true }, ])('Tests on url construction', ({ host, trailing }) => { test(`Test getStopWords route`, async () => { - const route = `indexes/${index.uid}/settings/stop-words` - const client = new MeiliSearch({ host }) - const strippedHost = trailing ? host.slice(0, -1) : host + const route = `indexes/${index.uid}/settings/stop-words`; + const client = new MeiliSearch({ host }); + const strippedHost = trailing ? host.slice(0, -1) : host; await expect(client.index(index.uid).getStopWords()).rejects.toHaveProperty( 'message', - `Request to ${strippedHost}/${route} has failed` - ) - }) + `Request to ${strippedHost}/${route} has failed`, + ); + }); test(`Test updateStopWords route`, async () => { - const route = `indexes/${index.uid}/settings/stop-words` - const client = new MeiliSearch({ host }) - const strippedHost = trailing ? host.slice(0, -1) : host + const route = `indexes/${index.uid}/settings/stop-words`; + const client = new MeiliSearch({ host }); + const strippedHost = trailing ? host.slice(0, -1) : host; await expect( - client.index(index.uid).updateStopWords([]) + client.index(index.uid).updateStopWords([]), ).rejects.toHaveProperty( 'message', - `Request to ${strippedHost}/${route} has failed` - ) - }) + `Request to ${strippedHost}/${route} has failed`, + ); + }); test(`Test resetStopWords route`, async () => { - const route = `indexes/${index.uid}/settings/stop-words` - const client = new MeiliSearch({ host }) - const strippedHost = trailing ? host.slice(0, -1) : host + const route = `indexes/${index.uid}/settings/stop-words`; + const client = new MeiliSearch({ host }); + const strippedHost = trailing ? host.slice(0, -1) : host; await expect( - client.index(index.uid).resetStopWords() + client.index(index.uid).resetStopWords(), ).rejects.toHaveProperty( 'message', - `Request to ${strippedHost}/${route} has failed` - ) - }) -}) + `Request to ${strippedHost}/${route} has failed`, + ); + }); +}); diff --git a/tests/synonyms.test.ts b/tests/synonyms.test.ts index 4a8cec4f5..bc1171d85 100644 --- a/tests/synonyms.test.ts +++ b/tests/synonyms.test.ts @@ -1,4 +1,4 @@ -import { ErrorStatusCode } from '../src/types' +import { ErrorStatusCode } from '../src/types'; import { clearAllIndexes, config, @@ -6,133 +6,133 @@ import { MeiliSearch, getClient, dataset, -} from './utils/meilisearch-test-utils' +} from './utils/meilisearch-test-utils'; const index = { uid: 'movies_test', -} +}; -jest.setTimeout(100 * 1000) +jest.setTimeout(100 * 1000); afterAll(() => { - return clearAllIndexes(config) -}) + return clearAllIndexes(config); +}); describe.each([{ permission: 'Master' }, { permission: 'Admin' }])( 'Test on synonyms', ({ permission }) => { beforeEach(async () => { - const client = await getClient('Master') - const { taskUid } = await client.index(index.uid).addDocuments(dataset) - await client.waitForTask(taskUid) - }) + const client = await getClient('Master'); + const { taskUid } = await client.index(index.uid).addDocuments(dataset); + await client.waitForTask(taskUid); + }); test(`${permission} key: Get default synonyms`, async () => { - const client = await getClient(permission) - const response: object = await client.index(index.uid).getSynonyms() + const client = await getClient(permission); + const response: object = await client.index(index.uid).getSynonyms(); - expect(response).toEqual({}) - }) + expect(response).toEqual({}); + }); test(`${permission} key: Update synonyms`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const newSynonyms = { hp: ['harry potter'], - } - const task = await client.index(index.uid).updateSynonyms(newSynonyms) - await client.waitForTask(task.taskUid) + }; + const task = await client.index(index.uid).updateSynonyms(newSynonyms); + await client.waitForTask(task.taskUid); - const response: object = await client.index(index.uid).getSynonyms() + const response: object = await client.index(index.uid).getSynonyms(); - expect(response).toEqual(newSynonyms) - }) + expect(response).toEqual(newSynonyms); + }); test(`${permission} key: Update synonyms with null value`, async () => { - const client = await getClient(permission) - const newSynonyms = null - const task = await client.index(index.uid).updateSynonyms(newSynonyms) - await client.waitForTask(task.taskUid) + const client = await getClient(permission); + const newSynonyms = null; + const task = await client.index(index.uid).updateSynonyms(newSynonyms); + await client.waitForTask(task.taskUid); - const response: object = await client.index(index.uid).getSynonyms() + const response: object = await client.index(index.uid).getSynonyms(); - expect(response).toEqual({}) - }) + expect(response).toEqual({}); + }); test(`${permission} key: Reset synonyms`, async () => { - const client = await getClient(permission) - const task = await client.index(index.uid).resetSynonyms() - await client.waitForTask(task.taskUid) + const client = await getClient(permission); + const task = await client.index(index.uid).resetSynonyms(); + await client.waitForTask(task.taskUid); - const response: object = await client.index(index.uid).getSynonyms() + const response: object = await client.index(index.uid).getSynonyms(); - expect(response).toEqual({}) - }) - } -) + expect(response).toEqual({}); + }); + }, +); describe.each([{ permission: 'Search' }])( 'Test on synonyms', ({ permission }) => { beforeEach(async () => { - await clearAllIndexes(config) - }) + await clearAllIndexes(config); + }); test(`${permission} key: try to get synonyms and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect( - client.index(index.uid).getSynonyms() - ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY) - }) + client.index(index.uid).getSynonyms(), + ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY); + }); test(`${permission} key: try to update synonyms and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect( - client.index(index.uid).updateSynonyms({}) - ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY) - }) + client.index(index.uid).updateSynonyms({}), + ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY); + }); test(`${permission} key: try to reset synonyms and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect( - client.index(index.uid).resetSynonyms() - ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY) - }) - } -) + client.index(index.uid).resetSynonyms(), + ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY); + }); + }, +); describe.each([{ permission: 'No' }])('Test on synonyms', ({ permission }) => { beforeEach(async () => { - await clearAllIndexes(config) - }) + await clearAllIndexes(config); + }); test(`${permission} key: try to get synonyms and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect(client.index(index.uid).getSynonyms()).rejects.toHaveProperty( 'cause.code', - ErrorStatusCode.MISSING_AUTHORIZATION_HEADER - ) - }) + ErrorStatusCode.MISSING_AUTHORIZATION_HEADER, + ); + }); test(`${permission} key: try to update synonyms and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect( - client.index(index.uid).updateSynonyms({}) + client.index(index.uid).updateSynonyms({}), ).rejects.toHaveProperty( 'cause.code', - ErrorStatusCode.MISSING_AUTHORIZATION_HEADER - ) - }) + ErrorStatusCode.MISSING_AUTHORIZATION_HEADER, + ); + }); test(`${permission} key: try to reset synonyms and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect( - client.index(index.uid).resetSynonyms() + client.index(index.uid).resetSynonyms(), ).rejects.toHaveProperty( 'cause.code', - ErrorStatusCode.MISSING_AUTHORIZATION_HEADER - ) - }) -}) + ErrorStatusCode.MISSING_AUTHORIZATION_HEADER, + ); + }); +}); describe.each([ { host: BAD_HOST, trailing: false }, @@ -140,36 +140,36 @@ describe.each([ { host: `${BAD_HOST}/trailing/`, trailing: true }, ])('Tests on url construction', ({ host, trailing }) => { test(`Test getSynonyms route`, async () => { - const route = `indexes/${index.uid}/settings/synonyms` - const client = new MeiliSearch({ host }) - const strippedHost = trailing ? host.slice(0, -1) : host + const route = `indexes/${index.uid}/settings/synonyms`; + const client = new MeiliSearch({ host }); + const strippedHost = trailing ? host.slice(0, -1) : host; await expect(client.index(index.uid).getSynonyms()).rejects.toHaveProperty( 'message', - `Request to ${strippedHost}/${route} has failed` - ) - }) + `Request to ${strippedHost}/${route} has failed`, + ); + }); test(`Test updateSynonyms route`, async () => { - const route = `indexes/${index.uid}/settings/synonyms` - const client = new MeiliSearch({ host }) - const strippedHost = trailing ? host.slice(0, -1) : host + const route = `indexes/${index.uid}/settings/synonyms`; + const client = new MeiliSearch({ host }); + const strippedHost = trailing ? host.slice(0, -1) : host; await expect( - client.index(index.uid).updateSynonyms({}) + client.index(index.uid).updateSynonyms({}), ).rejects.toHaveProperty( 'message', - `Request to ${strippedHost}/${route} has failed` - ) - }) + `Request to ${strippedHost}/${route} has failed`, + ); + }); test(`Test resetSynonyms route`, async () => { - const route = `indexes/${index.uid}/settings/synonyms` - const client = new MeiliSearch({ host }) - const strippedHost = trailing ? host.slice(0, -1) : host + const route = `indexes/${index.uid}/settings/synonyms`; + const client = new MeiliSearch({ host }); + const strippedHost = trailing ? host.slice(0, -1) : host; await expect( - client.index(index.uid).resetSynonyms() + client.index(index.uid).resetSynonyms(), ).rejects.toHaveProperty( 'message', - `Request to ${strippedHost}/${route} has failed` - ) - }) -}) + `Request to ${strippedHost}/${route} has failed`, + ); + }); +}); diff --git a/tests/task.test.ts b/tests/task.test.ts index 37ec531e9..89cf421ec 100644 --- a/tests/task.test.ts +++ b/tests/task.test.ts @@ -1,5 +1,5 @@ -import { ErrorStatusCode, TaskTypes, TaskStatus } from '../src/types' -import { sleep } from '../src/utils' +import { ErrorStatusCode, TaskTypes, TaskStatus } from '../src/types'; +import { sleep } from '../src/utils'; import { clearAllIndexes, config, @@ -7,808 +7,811 @@ import { MeiliSearch, getClient, dataset, -} from './utils/meilisearch-test-utils' +} from './utils/meilisearch-test-utils'; const index = { uid: 'movies_test', -} +}; const index2 = { uid: 'movies_test2', -} +}; const index3 = { uid: 'movies_test2', -} +}; -jest.setTimeout(100 * 1000) +jest.setTimeout(100 * 1000); afterAll(() => { - return clearAllIndexes(config) -}) + return clearAllIndexes(config); +}); describe.each([{ permission: 'Master' }, { permission: 'Admin' }])( 'Tests on tasks', ({ permission }) => { beforeEach(async () => { - const client = await getClient('Master') - const { taskUid } = await client.createIndex(index.uid) - await client.waitForTask(taskUid) - }) + const client = await getClient('Master'); + const { taskUid } = await client.createIndex(index.uid); + await client.waitForTask(taskUid); + }); test(`${permission} key: Get one enqueued task`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); - const enqueuedTask = await client.index(index.uid).addDocuments(dataset) + const enqueuedTask = await client.index(index.uid).addDocuments(dataset); - expect(enqueuedTask.taskUid).toBeDefined() - expect(enqueuedTask.indexUid).toEqual(index.uid) - expect(enqueuedTask.status).toBeDefined() - expect(enqueuedTask.type).toEqual(TaskTypes.DOCUMENTS_ADDITION_OR_UPDATE) - expect(enqueuedTask.enqueuedAt).toBeDefined() - expect(enqueuedTask.enqueuedAt).toBeInstanceOf(Date) - }) + expect(enqueuedTask.taskUid).toBeDefined(); + expect(enqueuedTask.indexUid).toEqual(index.uid); + expect(enqueuedTask.status).toBeDefined(); + expect(enqueuedTask.type).toEqual(TaskTypes.DOCUMENTS_ADDITION_OR_UPDATE); + expect(enqueuedTask.enqueuedAt).toBeDefined(); + expect(enqueuedTask.enqueuedAt).toBeInstanceOf(Date); + }); test(`${permission} key: Get one task`, async () => { - const client = await getClient(permission) - const enqueuedTask = await client.index(index.uid).addDocuments(dataset) - await client.waitForTask(enqueuedTask.taskUid) - - const task = await client.getTask(enqueuedTask.taskUid) - - expect(task.indexUid).toEqual(index.uid) - expect(task.status).toEqual(TaskStatus.TASK_SUCCEEDED) - expect(task.type).toEqual(TaskTypes.DOCUMENTS_ADDITION_OR_UPDATE) - expect(task.uid).toEqual(enqueuedTask.taskUid) - expect(task).toHaveProperty('details') - expect(task.details.indexedDocuments).toEqual(7) - expect(task.details.receivedDocuments).toEqual(7) - expect(task.duration).toBeDefined() - expect(task.enqueuedAt).toBeDefined() - expect(task.enqueuedAt).toBeInstanceOf(Date) - expect(task.finishedAt).toBeDefined() - expect(task.finishedAt).toBeInstanceOf(Date) - expect(task.startedAt).toBeDefined() - expect(task.startedAt).toBeInstanceOf(Date) - expect(task.error).toBeNull() - }) + const client = await getClient(permission); + const enqueuedTask = await client.index(index.uid).addDocuments(dataset); + await client.waitForTask(enqueuedTask.taskUid); + + const task = await client.getTask(enqueuedTask.taskUid); + + expect(task.indexUid).toEqual(index.uid); + expect(task.status).toEqual(TaskStatus.TASK_SUCCEEDED); + expect(task.type).toEqual(TaskTypes.DOCUMENTS_ADDITION_OR_UPDATE); + expect(task.uid).toEqual(enqueuedTask.taskUid); + expect(task).toHaveProperty('details'); + expect(task.details.indexedDocuments).toEqual(7); + expect(task.details.receivedDocuments).toEqual(7); + expect(task.duration).toBeDefined(); + expect(task.enqueuedAt).toBeDefined(); + expect(task.enqueuedAt).toBeInstanceOf(Date); + expect(task.finishedAt).toBeDefined(); + expect(task.finishedAt).toBeInstanceOf(Date); + expect(task.startedAt).toBeDefined(); + expect(task.startedAt).toBeInstanceOf(Date); + expect(task.error).toBeNull(); + }); test(`${permission} key: Get one task with index instance`, async () => { - const client = await getClient(permission) - const enqueuedTask = await client.index(index.uid).addDocuments(dataset) - await client.waitForTask(enqueuedTask.taskUid) + const client = await getClient(permission); + const enqueuedTask = await client.index(index.uid).addDocuments(dataset); + await client.waitForTask(enqueuedTask.taskUid); - const task = await client.index(index.uid).getTask(enqueuedTask.taskUid) + const task = await client.index(index.uid).getTask(enqueuedTask.taskUid); - expect(task.indexUid).toEqual(index.uid) - expect(task.uid).toEqual(enqueuedTask.taskUid) - }) + expect(task.indexUid).toEqual(index.uid); + expect(task.uid).toEqual(enqueuedTask.taskUid); + }); // get tasks test(`${permission} key: Get all tasks`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const enqueuedTask = await client .index(index.uid) - .addDocuments([{ id: 1 }]) - await client.waitForTask(enqueuedTask.taskUid) + .addDocuments([{ id: 1 }]); + await client.waitForTask(enqueuedTask.taskUid); - const tasks = await client.getTasks() + const tasks = await client.getTasks(); - expect(tasks.results).toBeInstanceOf(Array) - expect(tasks.total).toBeDefined() - expect(tasks.results[0].uid).toEqual(enqueuedTask.taskUid) - }) + expect(tasks.results).toBeInstanceOf(Array); + expect(tasks.total).toBeDefined(); + expect(tasks.results[0].uid).toEqual(enqueuedTask.taskUid); + }); // get tasks: type test(`${permission} key: Get all tasks with type filter`, async () => { - 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) + 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); const tasks = await client.getTasks({ types: [ TaskTypes.DOCUMENTS_ADDITION_OR_UPDATE, TaskTypes.DOCUMENT_DELETION, ], - }) + }); const onlyDocumentAddition = new Set( - tasks.results.map((task) => task.type) - ) + tasks.results.map((task) => task.type), + ); - expect(onlyDocumentAddition.size).toEqual(2) - }) + expect(onlyDocumentAddition.size).toEqual(2); + }); // get tasks: type test(`${permission} key: Get all tasks with type filter on an index`, async () => { - const client = await getClient(permission) - await client.deleteIndex(index2.uid) - await client.createIndex(index2.uid) - await client.index(index.uid).addDocuments([{ id: 1 }]) - await client.index(index2.uid).addDocuments([{ id: 1 }]) - await client.index(index2.uid).deleteDocument(1) + const client = await getClient(permission); + await client.deleteIndex(index2.uid); + await client.createIndex(index2.uid); + await client.index(index.uid).addDocuments([{ id: 1 }]); + await client.index(index2.uid).addDocuments([{ id: 1 }]); + await client.index(index2.uid).deleteDocument(1); const tasks = await client.index(index.uid).getTasks({ types: [ TaskTypes.DOCUMENTS_ADDITION_OR_UPDATE, TaskTypes.DOCUMENT_DELETION, ], - }) + }); const onlyDocumentAddition = new Set( - tasks.results.map((task) => task.type) - ) + tasks.results.map((task) => task.type), + ); - expect(onlyDocumentAddition.size).toEqual(2) - }) + expect(onlyDocumentAddition.size).toEqual(2); + }); // get tasks: pagination test(`${permission} key: Get all tasks with pagination`, async () => { - const client = await getClient(permission) - const task1 = await client.index(index.uid).addDocuments([{ id: 1 }]) - const task2 = await client.index(index.uid).addDocuments([{ id: 1 }]) - await client.waitForTask(task1.taskUid) - await client.waitForTask(task2.taskUid) + const client = await getClient(permission); + const task1 = await client.index(index.uid).addDocuments([{ id: 1 }]); + const task2 = await client.index(index.uid).addDocuments([{ id: 1 }]); + await client.waitForTask(task1.taskUid); + await client.waitForTask(task2.taskUid); - const tasks = await client.getTasks({ from: task1.taskUid, limit: 1 }) + const tasks = await client.getTasks({ from: task1.taskUid, limit: 1 }); - expect(tasks.results.length).toEqual(1) - expect(tasks.from).toEqual(task1.taskUid) - expect(tasks.limit).toEqual(1) - expect(tasks.next).toEqual(task1.taskUid - 1) - }) + expect(tasks.results.length).toEqual(1); + expect(tasks.from).toEqual(task1.taskUid); + expect(tasks.limit).toEqual(1); + expect(tasks.next).toEqual(task1.taskUid - 1); + }); // get tasks: status test(`${permission} key: Get all tasks with status filter`, async () => { - const client = await getClient(permission) - const task1 = await client.index(index.uid).addDocuments([{ id: 1 }]) - const task2 = await client.index(index.uid).addDocuments([{}]) - await client.waitForTask(task1.taskUid) - await client.waitForTask(task2.taskUid) + const client = await getClient(permission); + const task1 = await client.index(index.uid).addDocuments([{ id: 1 }]); + const task2 = await client.index(index.uid).addDocuments([{}]); + await client.waitForTask(task1.taskUid); + await client.waitForTask(task2.taskUid); const tasks = await client.getTasks({ statuses: [TaskStatus.TASK_SUCCEEDED, TaskStatus.TASK_FAILED], - }) + }); const onlySuccesfullTasks = new Set( - tasks.results.map((task) => task.status) - ) + tasks.results.map((task) => task.status), + ); - expect(onlySuccesfullTasks.size).toEqual(2) - }) + expect(onlySuccesfullTasks.size).toEqual(2); + }); // get tasks: status test(`${permission} key: Get all tasks with status filter on an index`, async () => { - const client = await getClient(permission) - const task1 = await client.index(index.uid).addDocuments([{ id: 1 }]) - const task2 = await client.index(index.uid).addDocuments([{}]) - const task3 = await client.index(index2.uid).addDocuments([{}]) - await client.waitForTask(task1.taskUid) - await client.waitForTask(task2.taskUid) - await client.waitForTask(task3.taskUid) + const client = await getClient(permission); + const task1 = await client.index(index.uid).addDocuments([{ id: 1 }]); + const task2 = await client.index(index.uid).addDocuments([{}]); + const task3 = await client.index(index2.uid).addDocuments([{}]); + await client.waitForTask(task1.taskUid); + await client.waitForTask(task2.taskUid); + await client.waitForTask(task3.taskUid); const tasks = await client.index(index.uid).getTasks({ statuses: [TaskStatus.TASK_SUCCEEDED, TaskStatus.TASK_FAILED], - }) + }); const onlySuccesfullTasks = new Set( - tasks.results.map((task) => task.status) - ) + tasks.results.map((task) => task.status), + ); const onlyTaskWithSameUid = new Set( - tasks.results.map((task) => task.indexUid) - ) + tasks.results.map((task) => task.indexUid), + ); - expect(onlySuccesfullTasks.size).toEqual(2) - expect(onlyTaskWithSameUid.size).toEqual(1) - }) + expect(onlySuccesfullTasks.size).toEqual(2); + expect(onlyTaskWithSameUid.size).toEqual(1); + }); // get tasks: indexUid test(`${permission} key: Get all tasks with indexUid filter`, async () => { - const client = await getClient(permission) - await client.index(index.uid).addDocuments([{ id: 1 }]) - await client.index(index2.uid).addDocuments([{ id: 1 }]) - await client.index(index3.uid).addDocuments([{ id: 1 }]) + const client = await getClient(permission); + await client.index(index.uid).addDocuments([{ id: 1 }]); + await client.index(index2.uid).addDocuments([{ id: 1 }]); + await client.index(index3.uid).addDocuments([{ id: 1 }]); const tasks = await client.getTasks({ indexUids: [index.uid, index2.uid], - }) + }); const onlyTaskWithSameUid = new Set( - tasks.results.map((task) => task.indexUid) - ) + tasks.results.map((task) => task.indexUid), + ); - expect(onlyTaskWithSameUid.size).toEqual(2) - }) + expect(onlyTaskWithSameUid.size).toEqual(2); + }); // get tasks: uid test(`${permission} key: Get all tasks with uid filter`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const { taskUid } = await client .index(index.uid) - .addDocuments([{ id: 1 }]) + .addDocuments([{ id: 1 }]); const tasks = await client.getTasks({ uids: [taskUid], - }) + }); - expect(tasks.results[0].uid).toEqual(taskUid) - }) + expect(tasks.results[0].uid).toEqual(taskUid); + }); // get tasks: beforeEnqueuedAt test(`${permission} key: Get all tasks with beforeEnqueuedAt filter`, async () => { - const client = await getClient(permission) - const currentTimeStamp = Date.now() - const currentTime = new Date(currentTimeStamp) - await sleep(1) // in ms + const client = await getClient(permission); + const currentTimeStamp = Date.now(); + const currentTime = new Date(currentTimeStamp); + await sleep(1); // in ms const { taskUid } = await client .index(index.uid) - .addDocuments([{ id: 1 }]) + .addDocuments([{ id: 1 }]); const tasks = await client.getTasks({ beforeEnqueuedAt: currentTime, - }) - const tasksUids = tasks.results.map((t) => t.uid) + }); + const tasksUids = tasks.results.map((t) => t.uid); - expect(tasksUids.includes(taskUid)).toBeFalsy() - }) + expect(tasksUids.includes(taskUid)).toBeFalsy(); + }); // get tasks: afterEnqueuedAt test(`${permission} key: Get all tasks with afterEnqueuedAt filter`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const { taskUid } = await client .index(index.uid) - .addDocuments([{ id: 1 }]) - await sleep(1000) // in ms + .addDocuments([{ id: 1 }]); + await sleep(1000); // in ms - const currentTimeStamp = Date.now() - const currentTime = new Date(currentTimeStamp) + const currentTimeStamp = Date.now(); + const currentTime = new Date(currentTimeStamp); const tasks = await client.getTasks({ afterEnqueuedAt: currentTime, - }) - const tasksUids = tasks.results.map((t) => t.uid) + }); + const tasksUids = tasks.results.map((t) => t.uid); - expect(tasksUids.includes(taskUid)).toBeFalsy() - }) + expect(tasksUids.includes(taskUid)).toBeFalsy(); + }); // get tasks: beforeStartedAt test(`${permission} key: Get all tasks with beforeStartedAt filter`, async () => { - const client = await getClient(permission) - const currentTimeStamp = Date.now() - const currentTime = new Date(currentTimeStamp) - await sleep(1) // in ms + const client = await getClient(permission); + const currentTimeStamp = Date.now(); + const currentTime = new Date(currentTimeStamp); + await sleep(1); // in ms const { taskUid } = await client .index(index.uid) - .addDocuments([{ id: 1 }]) - await client.index(index.uid).waitForTask(taskUid) // ensures the tasks has a `startedAt` value + .addDocuments([{ id: 1 }]); + await client.index(index.uid).waitForTask(taskUid); // ensures the tasks has a `startedAt` value const tasks = await client.getTasks({ beforeStartedAt: currentTime, - }) - const tasksUids = tasks.results.map((t) => t.uid) + }); + const tasksUids = tasks.results.map((t) => t.uid); - expect(tasksUids.includes(taskUid)).toBeFalsy() - }) + expect(tasksUids.includes(taskUid)).toBeFalsy(); + }); // get tasks: afterStartedAt test(`${permission} key: Get all tasks with afterStartedAt filter`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const { taskUid } = await client .index(index.uid) - .addDocuments([{ id: 1 }]) - await client.index(index.uid).waitForTask(taskUid) // ensures the tasks has a `startedAt` value - await sleep(1) // in ms + .addDocuments([{ id: 1 }]); + await client.index(index.uid).waitForTask(taskUid); // ensures the tasks has a `startedAt` value + await sleep(1); // in ms - const currentTimeStamp = Date.now() - const currentTime = new Date(currentTimeStamp) + const currentTimeStamp = Date.now(); + const currentTime = new Date(currentTimeStamp); const tasks = await client.getTasks({ afterStartedAt: currentTime, - }) - const tasksUids = tasks.results.map((t) => t.uid) + }); + const tasksUids = tasks.results.map((t) => t.uid); - expect(tasksUids.includes(taskUid)).toBeFalsy() - }) + expect(tasksUids.includes(taskUid)).toBeFalsy(); + }); // get tasks: beforeFinishedAt test(`${permission} key: Get all tasks with beforeFinishedAt filter`, async () => { - const client = await getClient(permission) - const currentTimeStamp = Date.now() - const currentTime = new Date(currentTimeStamp) - await sleep(1) // in ms + const client = await getClient(permission); + const currentTimeStamp = Date.now(); + const currentTime = new Date(currentTimeStamp); + await sleep(1); // in ms const { taskUid } = await client .index(index.uid) - .addDocuments([{ id: 1 }]) - await client.index(index.uid).waitForTask(taskUid) // ensures the tasks has a `finishedAt` value + .addDocuments([{ id: 1 }]); + await client.index(index.uid).waitForTask(taskUid); // ensures the tasks has a `finishedAt` value const tasks = await client.getTasks({ beforeFinishedAt: currentTime, - }) - const tasksUids = tasks.results.map((t) => t.uid) + }); + const tasksUids = tasks.results.map((t) => t.uid); - expect(tasksUids.includes(taskUid)).toBeFalsy() - }) + expect(tasksUids.includes(taskUid)).toBeFalsy(); + }); // get tasks: afterFinishedAt test(`${permission} key: Get all tasks with afterFinishedAt filter`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const { taskUid } = await client .index(index.uid) - .addDocuments([{ id: 1 }]) - await client.index(index.uid).waitForTask(taskUid) // ensures the tasks has a `finishedAt` value - await sleep(1) // in ms + .addDocuments([{ id: 1 }]); + await client.index(index.uid).waitForTask(taskUid); // ensures the tasks has a `finishedAt` value + await sleep(1); // in ms - const currentTimeStamp = Date.now() - const currentTime = new Date(currentTimeStamp) + const currentTimeStamp = Date.now(); + const currentTime = new Date(currentTimeStamp); const tasks = await client.getTasks({ afterFinishedAt: currentTime, - }) - const tasksUids = tasks.results.map((t) => t.uid) + }); + const tasksUids = tasks.results.map((t) => t.uid); - expect(tasksUids.includes(taskUid)).toBeFalsy() - }) + expect(tasksUids.includes(taskUid)).toBeFalsy(); + }); // get tasks: canceledBy test(`${permission} key: Get all tasks with canceledBy filter`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const addDocumentsTask = await client .index(index.uid) - .addDocuments([{ id: 1 }]) + .addDocuments([{ id: 1 }]); // Cancel the task const enqueuedCancelationTask = await client.cancelTasks({ uids: [addDocumentsTask.taskUid], - }) + }); // wait for the task to be fully canceled const cancelationTask = await client.waitForTask( - enqueuedCancelationTask.taskUid - ) + enqueuedCancelationTask.taskUid, + ); - expect(cancelationTask.type).toEqual(TaskTypes.TASK_CANCELATION) + expect(cancelationTask.type).toEqual(TaskTypes.TASK_CANCELATION); expect(cancelationTask.details.originalFilter).toEqual( - `?uids=${addDocumentsTask.taskUid}` - ) - }) + `?uids=${addDocumentsTask.taskUid}`, + ); + }); // filters error code: INVALID_TASK_TYPES_FILTER test(`${permission} key: Try to filter on task types with wrong type`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect( // @ts-expect-error testing wrong argument type - client.getTasks({ types: ['wrong'] }) - ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_TASK_TYPES) - }) + client.getTasks({ types: ['wrong'] }), + ).rejects.toHaveProperty( + 'cause.code', + ErrorStatusCode.INVALID_TASK_TYPES, + ); + }); // filters error code: INVALID_TASK_STATUSES_FILTER test(`${permission} key: Try to filter on statuses with wrong type`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect( // @ts-expect-error testing wrong argument type - client.getTasks({ statuses: ['wrong'] }) + client.getTasks({ statuses: ['wrong'] }), ).rejects.toHaveProperty( 'cause.code', - ErrorStatusCode.INVALID_TASK_STATUSES - ) - }) + ErrorStatusCode.INVALID_TASK_STATUSES, + ); + }); // filters error code: INVALID_TASK_UIDS_FILTER test(`${permission} key: Try to filter on uids with wrong type`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect( // @ts-expect-error testing wrong argument type - client.getTasks({ uids: ['wrong'] }) - ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_TASK_UIDS) - }) + client.getTasks({ uids: ['wrong'] }), + ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_TASK_UIDS); + }); // filters error code: INVALID_TASK_CANCELED_BY_FILTER test(`${permission} key: Try to filter on canceledBy filter with wrong type`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect( // @ts-expect-error testing wrong canceledBy type - client.getTasks({ canceledBy: ['wrong'] }) + client.getTasks({ canceledBy: ['wrong'] }), ).rejects.toHaveProperty( 'cause.code', - ErrorStatusCode.INVALID_TASK_CANCELED_BY - ) - }) + ErrorStatusCode.INVALID_TASK_CANCELED_BY, + ); + }); // filters error code: INVALID_TASK_DATE_FILTER test(`${permission} key: Try to filter on dates with invalid date format`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect( // @ts-expect-error testing wrong date format - client.getTasks({ beforeEnqueuedAt: 'wrong' }) + client.getTasks({ beforeEnqueuedAt: 'wrong' }), ).rejects.toHaveProperty( 'cause.code', - ErrorStatusCode.INVALID_TASK_BEFORE_ENQUEUED_AT - ) - }) + ErrorStatusCode.INVALID_TASK_BEFORE_ENQUEUED_AT, + ); + }); // cancel: uid test(`${permission} key: Cancel a task using the uid filter`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const addDocuments = await client .index(index.uid) - .addDocuments([{ id: 1 }]) + .addDocuments([{ id: 1 }]); const enqueuedTask = await client.cancelTasks({ uids: [addDocuments.taskUid], - }) - const task = await client.waitForTask(enqueuedTask.taskUid) + }); + const task = await client.waitForTask(enqueuedTask.taskUid); - expect(task.type).toEqual(TaskTypes.TASK_CANCELATION) - expect(task.details?.originalFilter).toContain('uids=') - expect(task.details?.matchedTasks).toBeDefined() - expect(task.details?.canceledTasks).toBeDefined() - }) + expect(task.type).toEqual(TaskTypes.TASK_CANCELATION); + expect(task.details?.originalFilter).toContain('uids='); + expect(task.details?.matchedTasks).toBeDefined(); + expect(task.details?.canceledTasks).toBeDefined(); + }); // cancel: indexUid test(`${permission} key: Cancel a task using the indexUid filter`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const enqueuedTask = await client.cancelTasks({ indexUids: [index.uid], - }) - const task = await client.waitForTask(enqueuedTask.taskUid) + }); + const task = await client.waitForTask(enqueuedTask.taskUid); - expect(task.type).toEqual(TaskTypes.TASK_CANCELATION) - expect(task.details?.originalFilter).toEqual('?indexUids=movies_test') - }) + expect(task.type).toEqual(TaskTypes.TASK_CANCELATION); + expect(task.details?.originalFilter).toEqual('?indexUids=movies_test'); + }); // cancel: type test(`${permission} key: Cancel a task using the type filter`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const enqueuedTask = await client.cancelTasks({ types: [ TaskTypes.DOCUMENTS_ADDITION_OR_UPDATE, TaskTypes.DOCUMENT_DELETION, ], - }) - const task = await client.waitForTask(enqueuedTask.taskUid) + }); + const task = await client.waitForTask(enqueuedTask.taskUid); - expect(task.type).toEqual(TaskTypes.TASK_CANCELATION) + expect(task.type).toEqual(TaskTypes.TASK_CANCELATION); expect(task.details?.originalFilter).toEqual( - '?types=documentAdditionOrUpdate%2CdocumentDeletion' - ) - }) + '?types=documentAdditionOrUpdate%2CdocumentDeletion', + ); + }); // cancel: status test(`${permission} key: Cancel a task using the status filter`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const enqueuedTask = await client.cancelTasks({ statuses: [TaskStatus.TASK_ENQUEUED, TaskStatus.TASK_PROCESSING], - }) - const task = await client.waitForTask(enqueuedTask.taskUid) + }); + const task = await client.waitForTask(enqueuedTask.taskUid); - expect(task.type).toEqual(TaskTypes.TASK_CANCELATION) + expect(task.type).toEqual(TaskTypes.TASK_CANCELATION); expect(task.details?.originalFilter).toEqual( - '?statuses=enqueued%2Cprocessing' - ) - }) + '?statuses=enqueued%2Cprocessing', + ); + }); // cancel: beforeEnqueuedAt test(`${permission} key: Cancel a task using beforeEnqueuedAt filter`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); - const currentTimeStamp = Date.now() - const currentTime = new Date(currentTimeStamp) + const currentTimeStamp = Date.now(); + const currentTime = new Date(currentTimeStamp); const enqueuedTask = await client.cancelTasks({ beforeEnqueuedAt: currentTime, - }) - const task = await client.waitForTask(enqueuedTask.taskUid) + }); + const task = await client.waitForTask(enqueuedTask.taskUid); - expect(task.type).toEqual(TaskTypes.TASK_CANCELATION) - expect(task.details?.originalFilter).toContain('beforeEnqueuedAt') - }) + expect(task.type).toEqual(TaskTypes.TASK_CANCELATION); + expect(task.details?.originalFilter).toContain('beforeEnqueuedAt'); + }); // cancel: afterEnqueuedAt test(`${permission} key: Cancel a task using afterEnqueuedAt filter`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); - const currentTimeStamp = Date.now() - const currentTime = new Date(currentTimeStamp) + const currentTimeStamp = Date.now(); + const currentTime = new Date(currentTimeStamp); const enqueuedTask = await client.cancelTasks({ afterEnqueuedAt: currentTime, - }) - const task = await client.waitForTask(enqueuedTask.taskUid) + }); + const task = await client.waitForTask(enqueuedTask.taskUid); - expect(task.type).toEqual(TaskTypes.TASK_CANCELATION) - expect(task.details?.originalFilter).toContain('afterEnqueuedAt') - }) + expect(task.type).toEqual(TaskTypes.TASK_CANCELATION); + expect(task.details?.originalFilter).toContain('afterEnqueuedAt'); + }); // cancel: beforeStartedAt test(`${permission} key: Cancel a task using beforeStartedAt filter`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); - const currentTimeStamp = Date.now() - const currentTime = new Date(currentTimeStamp) + const currentTimeStamp = Date.now(); + const currentTime = new Date(currentTimeStamp); const enqueuedTask = await client.cancelTasks({ beforeStartedAt: currentTime, - }) - const task = await client.waitForTask(enqueuedTask.taskUid) + }); + const task = await client.waitForTask(enqueuedTask.taskUid); - expect(task.type).toEqual(TaskTypes.TASK_CANCELATION) - expect(task.details?.originalFilter).toContain('beforeStartedAt') - }) + expect(task.type).toEqual(TaskTypes.TASK_CANCELATION); + expect(task.details?.originalFilter).toContain('beforeStartedAt'); + }); // cancel: afterStartedAt test(`${permission} key: Cancel a task using afterStartedAt filter`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); - const currentTimeStamp = Date.now() - const currentTime = new Date(currentTimeStamp) + const currentTimeStamp = Date.now(); + const currentTime = new Date(currentTimeStamp); const enqueuedTask = await client.cancelTasks({ afterStartedAt: currentTime, - }) - const task = await client.waitForTask(enqueuedTask.taskUid) + }); + const task = await client.waitForTask(enqueuedTask.taskUid); - expect(task.type).toEqual(TaskTypes.TASK_CANCELATION) - expect(task.details?.originalFilter).toContain('afterStartedAt') - }) + expect(task.type).toEqual(TaskTypes.TASK_CANCELATION); + expect(task.details?.originalFilter).toContain('afterStartedAt'); + }); // cancel: beforeFinishedAt test(`${permission} key: Cancel a task using beforeFinishedAt filter`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); - const currentTimeStamp = Date.now() - const currentTime = new Date(currentTimeStamp) + const currentTimeStamp = Date.now(); + const currentTime = new Date(currentTimeStamp); const enqueuedTask = await client.cancelTasks({ beforeFinishedAt: currentTime, - }) - const task = await client.waitForTask(enqueuedTask.taskUid) + }); + const task = await client.waitForTask(enqueuedTask.taskUid); - expect(task.type).toEqual(TaskTypes.TASK_CANCELATION) - expect(task.details?.originalFilter).toContain('beforeFinishedAt') - }) + expect(task.type).toEqual(TaskTypes.TASK_CANCELATION); + expect(task.details?.originalFilter).toContain('beforeFinishedAt'); + }); // cancel: afterFinishedAt test(`${permission} key: Cancel a task using afterFinishedAt filter`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); - const currentTimeStamp = Date.now() - const currentTime = new Date(currentTimeStamp) + const currentTimeStamp = Date.now(); + const currentTime = new Date(currentTimeStamp); const enqueuedTask = await client.cancelTasks({ afterFinishedAt: currentTime, - }) - const task = await client.waitForTask(enqueuedTask.taskUid) + }); + const task = await client.waitForTask(enqueuedTask.taskUid); - expect(task.type).toEqual(TaskTypes.TASK_CANCELATION) - expect(task.details?.originalFilter).toContain('afterFinishedAt') - }) + expect(task.type).toEqual(TaskTypes.TASK_CANCELATION); + expect(task.details?.originalFilter).toContain('afterFinishedAt'); + }); // cancel error code: MISSING_TASK_FILTER test(`${permission} key: Try to cancel without filters and fail`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect( // @ts-expect-error testing wrong argument type - client.cancelTasks() + client.cancelTasks(), ).rejects.toHaveProperty( 'cause.code', - ErrorStatusCode.MISSING_TASK_FILTERS - ) - }) + ErrorStatusCode.MISSING_TASK_FILTERS, + ); + }); // delete: uid test(`${permission} key: Delete a task using the uid filter`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const addDocuments = await client .index(index.uid) - .addDocuments([{ id: 1 }]) + .addDocuments([{ id: 1 }]); const deleteTask = await client.deleteTasks({ uids: [addDocuments.taskUid], - }) - const task = await client.waitForTask(deleteTask.taskUid) + }); + const task = await client.waitForTask(deleteTask.taskUid); - expect(deleteTask.type).toEqual(TaskTypes.TASK_DELETION) - expect(task.details?.deletedTasks).toBeDefined() + expect(deleteTask.type).toEqual(TaskTypes.TASK_DELETION); + expect(task.details?.deletedTasks).toBeDefined(); await expect(client.getTask(addDocuments.taskUid)).rejects.toHaveProperty( 'cause.code', - ErrorStatusCode.TASK_NOT_FOUND - ) - }) + ErrorStatusCode.TASK_NOT_FOUND, + ); + }); // delete: indexUid test(`${permission} key: Delete a task using the indexUid filter`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const addDocuments = await client .index(index.uid) - .addDocuments([{ id: 1 }]) + .addDocuments([{ id: 1 }]); const enqueuedTask = await client.deleteTasks({ indexUids: [index.uid], - }) - const deleteTask = await client.waitForTask(enqueuedTask.taskUid) + }); + const deleteTask = await client.waitForTask(enqueuedTask.taskUid); - expect(deleteTask.type).toEqual(TaskTypes.TASK_DELETION) + expect(deleteTask.type).toEqual(TaskTypes.TASK_DELETION); await expect(client.getTask(addDocuments.taskUid)).rejects.toHaveProperty( 'cause.code', - ErrorStatusCode.TASK_NOT_FOUND - ) - }) + ErrorStatusCode.TASK_NOT_FOUND, + ); + }); // delete: type test(`${permission} key: Delete a task using the type filter`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const enqueuedTask = await client.deleteTasks({ types: [ TaskTypes.DOCUMENTS_ADDITION_OR_UPDATE, TaskTypes.DOCUMENT_DELETION, ], - }) - const deleteTask = await client.waitForTask(enqueuedTask.taskUid) + }); + const deleteTask = await client.waitForTask(enqueuedTask.taskUid); - expect(deleteTask.type).toEqual(TaskTypes.TASK_DELETION) + expect(deleteTask.type).toEqual(TaskTypes.TASK_DELETION); expect(deleteTask.details?.originalFilter).toEqual( - '?types=documentAdditionOrUpdate%2CdocumentDeletion' - ) - }) + '?types=documentAdditionOrUpdate%2CdocumentDeletion', + ); + }); // delete: status test(`${permission} key: Delete a task using the status filter`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const enqueuedTask = await client.deleteTasks({ statuses: [TaskStatus.TASK_ENQUEUED, TaskStatus.TASK_PROCESSING], - }) - const task = await client.waitForTask(enqueuedTask.taskUid) + }); + const task = await client.waitForTask(enqueuedTask.taskUid); - expect(task.type).toEqual(TaskTypes.TASK_DELETION) + expect(task.type).toEqual(TaskTypes.TASK_DELETION); expect(task.details?.originalFilter).toEqual( - '?statuses=enqueued%2Cprocessing' - ) - }) + '?statuses=enqueued%2Cprocessing', + ); + }); // delete: beforeEnqueuedAt test(`${permission} key: Delete a task using beforeEnqueuedAt filter`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); - const currentTimeStamp = Date.now() - const currentTime = new Date(currentTimeStamp) + const currentTimeStamp = Date.now(); + const currentTime = new Date(currentTimeStamp); const enqueuedTask = await client.deleteTasks({ beforeEnqueuedAt: currentTime, - }) - const task = await client.waitForTask(enqueuedTask.taskUid) + }); + const task = await client.waitForTask(enqueuedTask.taskUid); - expect(task.type).toEqual(TaskTypes.TASK_DELETION) - expect(task.details?.originalFilter).toContain('beforeEnqueuedAt') - }) + expect(task.type).toEqual(TaskTypes.TASK_DELETION); + expect(task.details?.originalFilter).toContain('beforeEnqueuedAt'); + }); // delete: afterEnqueuedAt test(`${permission} key: Delete a task using afterEnqueuedAt filter`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); - const currentTimeStamp = Date.now() - const currentTime = new Date(currentTimeStamp) + const currentTimeStamp = Date.now(); + const currentTime = new Date(currentTimeStamp); const enqueuedTask = await client.deleteTasks({ afterEnqueuedAt: currentTime, - }) - const task = await client.waitForTask(enqueuedTask.taskUid) + }); + const task = await client.waitForTask(enqueuedTask.taskUid); - expect(task.type).toEqual(TaskTypes.TASK_DELETION) - expect(task.details?.originalFilter).toContain('afterEnqueuedAt') - }) + expect(task.type).toEqual(TaskTypes.TASK_DELETION); + expect(task.details?.originalFilter).toContain('afterEnqueuedAt'); + }); // delete: beforeStartedAt test(`${permission} key: Delete a task using beforeStartedAt filter`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); - const currentTimeStamp = Date.now() - const currentTime = new Date(currentTimeStamp) + const currentTimeStamp = Date.now(); + const currentTime = new Date(currentTimeStamp); const enqueuedTask = await client.deleteTasks({ beforeStartedAt: currentTime, - }) - const task = await client.waitForTask(enqueuedTask.taskUid) + }); + const task = await client.waitForTask(enqueuedTask.taskUid); - expect(task.type).toEqual(TaskTypes.TASK_DELETION) - expect(task.details?.originalFilter).toContain('beforeStartedAt') - }) + expect(task.type).toEqual(TaskTypes.TASK_DELETION); + expect(task.details?.originalFilter).toContain('beforeStartedAt'); + }); // delete: afterStartedAt test(`${permission} key: Delete a task using afterStartedAt filter`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); - const currentTimeStamp = Date.now() - const currentTime = new Date(currentTimeStamp) + const currentTimeStamp = Date.now(); + const currentTime = new Date(currentTimeStamp); const enqueuedTask = await client.deleteTasks({ afterStartedAt: currentTime, - }) - const task = await client.waitForTask(enqueuedTask.taskUid) + }); + const task = await client.waitForTask(enqueuedTask.taskUid); - expect(task.type).toEqual(TaskTypes.TASK_DELETION) - expect(task.details?.originalFilter).toContain('afterStartedAt') - }) + expect(task.type).toEqual(TaskTypes.TASK_DELETION); + expect(task.details?.originalFilter).toContain('afterStartedAt'); + }); // delete: beforeFinishedAt test(`${permission} key: Delete a task using beforeFinishedAt filter`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); - const currentTimeStamp = Date.now() - const currentTime = new Date(currentTimeStamp) + const currentTimeStamp = Date.now(); + const currentTime = new Date(currentTimeStamp); const enqueuedTask = await client.deleteTasks({ beforeFinishedAt: currentTime, - }) - const task = await client.waitForTask(enqueuedTask.taskUid) + }); + const task = await client.waitForTask(enqueuedTask.taskUid); - expect(task.type).toEqual(TaskTypes.TASK_DELETION) - expect(task.details?.originalFilter).toContain('beforeFinishedAt') - }) + expect(task.type).toEqual(TaskTypes.TASK_DELETION); + expect(task.details?.originalFilter).toContain('beforeFinishedAt'); + }); // delete: afterFinishedAt test(`${permission} key: Delete a task using afterFinishedAt filter`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); - const currentTimeStamp = Date.now() - const currentTime = new Date(currentTimeStamp) + const currentTimeStamp = Date.now(); + const currentTime = new Date(currentTimeStamp); const enqueuedTask = await client.deleteTasks({ afterFinishedAt: currentTime, - }) - const task = await client.waitForTask(enqueuedTask.taskUid) + }); + const task = await client.waitForTask(enqueuedTask.taskUid); - expect(task.type).toEqual(TaskTypes.TASK_DELETION) - expect(task.details?.originalFilter).toContain('afterFinishedAt') - }) + expect(task.type).toEqual(TaskTypes.TASK_DELETION); + expect(task.details?.originalFilter).toContain('afterFinishedAt'); + }); test(`${permission} key: Get all indexes tasks with index instance`, async () => { - const client = await getClient(permission) - await client.index(index.uid).addDocuments([{ id: 1 }]) - await client.index(index2.uid).addDocuments([{ id: 1 }]) + const client = await getClient(permission); + await client.index(index.uid).addDocuments([{ id: 1 }]); + await client.index(index2.uid).addDocuments([{ id: 1 }]); - const tasks = await client.index(index.uid).getTasks() + const tasks = await client.index(index.uid).getTasks(); const onlyTaskWithSameUid = new Set( - tasks.results.map((task) => task.indexUid) - ) + tasks.results.map((task) => task.indexUid), + ); - expect(onlyTaskWithSameUid.size).toEqual(1) - }) + expect(onlyTaskWithSameUid.size).toEqual(1); + }); test(`${permission} key: Try to get a task that does not exist`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect(client.getTask(254500)).rejects.toHaveProperty( 'cause.code', - ErrorStatusCode.TASK_NOT_FOUND - ) - }) - } -) + ErrorStatusCode.TASK_NOT_FOUND, + ); + }); + }, +); describe.each([{ permission: 'Search' }])('Test on tasks', ({ permission }) => { beforeEach(async () => { - await clearAllIndexes(config) - }) + await clearAllIndexes(config); + }); test(`${permission} key: Try to get a task and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect(client.getTask(0)).rejects.toHaveProperty( 'cause.code', - ErrorStatusCode.INVALID_API_KEY - ) - }) -}) + ErrorStatusCode.INVALID_API_KEY, + ); + }); +}); describe.each([{ permission: 'No' }])('Test on tasks', ({ permission }) => { beforeEach(async () => { - await clearAllIndexes(config) - }) + await clearAllIndexes(config); + }); test(`${permission} key: Try to get an task and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect(client.getTask(0)).rejects.toHaveProperty( 'cause.code', - ErrorStatusCode.MISSING_AUTHORIZATION_HEADER - ) - }) -}) + ErrorStatusCode.MISSING_AUTHORIZATION_HEADER, + ); + }); +}); describe.each([ { host: BAD_HOST, trailing: false }, @@ -816,24 +819,24 @@ describe.each([ { host: `${BAD_HOST}/trailing/`, trailing: true }, ])('Tests on task url construction', ({ host, trailing }) => { test(`Test on getTask route`, async () => { - const route = `tasks/1` - const client = new MeiliSearch({ host }) - const strippedHost = trailing ? host.slice(0, -1) : host + const route = `tasks/1`; + const client = new MeiliSearch({ host }); + const strippedHost = trailing ? host.slice(0, -1) : host; await expect(client.index(index.uid).getTask(1)).rejects.toHaveProperty( 'message', - `Request to ${strippedHost}/${route} has failed` - ) - }) + `Request to ${strippedHost}/${route} has failed`, + ); + }); test(`Test on getTasks route`, async () => { - const route = `tasks?indexUids=movies_test` - const client = new MeiliSearch({ host }) - const strippedHost = trailing ? host.slice(0, -1) : host + const route = `tasks?indexUids=movies_test`; + const client = new MeiliSearch({ host }); + const strippedHost = trailing ? host.slice(0, -1) : host; await expect(client.index(index.uid).getTasks()).rejects.toHaveProperty( 'message', - `Request to ${strippedHost}/${route} has failed` - ) - }) -}) + `Request to ${strippedHost}/${route} has failed`, + ); + }); +}); diff --git a/tests/token.test.ts b/tests/token.test.ts index 4c81d9248..73ac88eea 100644 --- a/tests/token.test.ts +++ b/tests/token.test.ts @@ -6,58 +6,58 @@ import { clearAllIndexes, config, HOST, -} from './utils/meilisearch-test-utils' -import { createHmac } from 'crypto' -import MeiliSearch from '../src' +} from './utils/meilisearch-test-utils'; +import { createHmac } from 'crypto'; +import MeiliSearch from '../src'; -const HASH_ALGORITHM = 'HS256' -const TOKEN_TYP = 'JWT' -const UID = 'movies_test' +const HASH_ALGORITHM = 'HS256'; +const TOKEN_TYP = 'JWT'; +const UID = 'movies_test'; afterAll(() => { - return clearAllIndexes(config) -}) + return clearAllIndexes(config); +}); describe.each([{ permission: 'Admin' }])( 'Tests on token generation', ({ permission }) => { beforeEach(async () => { - const client = await getClient('Master') - await client.index(UID).delete() - const { taskUid } = await client.index(UID).addDocuments(dataset) - await client.waitForTask(taskUid) + const client = await getClient('Master'); + await client.index(UID).delete(); + const { taskUid } = await client.index(UID).addDocuments(dataset); + await client.waitForTask(taskUid); - const keys = await client.getKeys() + const keys = await client.getKeys(); const customKeys = keys.results.filter( (key) => key.name !== 'Default Search API Key' && - key.name !== 'Default Admin API Key' - ) + key.name !== 'Default Admin API Key', + ); // Delete all custom keys - await Promise.all(customKeys.map((key) => client.deleteKey(key.uid))) - }) + await Promise.all(customKeys.map((key) => client.deleteKey(key.uid))); + }); test(`${permission} key: create a tenant token and test header`, async () => { - const client = await getClient(permission) - const apiKey = await getKey(permission) - const { uid } = await client.getKey(apiKey) - const token = await client.generateTenantToken(uid, [], {}) - const [header64] = token.split('.') + const client = await getClient(permission); + const apiKey = await getKey(permission); + const { uid } = await client.getKey(apiKey); + const token = await client.generateTenantToken(uid, [], {}); + const [header64] = token.split('.'); // header - const { typ, alg } = JSON.parse(decode64(header64)) - expect(alg).toEqual(HASH_ALGORITHM) - expect(typ).toEqual(TOKEN_TYP) - }) + const { typ, alg } = JSON.parse(decode64(header64)); + expect(alg).toEqual(HASH_ALGORITHM); + expect(typ).toEqual(TOKEN_TYP); + }); test(`${permission} key: create a tenant token and test signature`, async () => { - const client = await getClient(permission) - const apiKey = await getKey(permission) - const { uid } = await client.getKey(apiKey) - const token = await client.generateTenantToken(uid, [], {}) - const [header64, payload64, signature64] = token.split('.') + const client = await getClient(permission); + const apiKey = await getKey(permission); + const { uid } = await client.getKey(apiKey); + const token = await client.generateTenantToken(uid, [], {}); + const [header64, payload64, signature64] = token.split('.'); // signature const newSignature = createHmac('sha256', apiKey) @@ -65,185 +65,185 @@ describe.each([{ permission: 'Admin' }])( .digest('base64') .replace(/\+/g, '-') .replace(/\//g, '_') - .replace(/=/g, '') + .replace(/=/g, ''); - expect(signature64).toEqual(newSignature) - }) + expect(signature64).toEqual(newSignature); + }); test(`${permission} key: create a tenant token with default values and test payload`, async () => { - const client = await getClient(permission) - const apiKey = await getKey(permission) - const { uid } = await client.getKey(apiKey) - const token = await client.generateTenantToken(uid, [], {}) - const [_, payload64] = token.split('.') + const client = await getClient(permission); + const apiKey = await getKey(permission); + const { uid } = await client.getKey(apiKey); + const token = await client.generateTenantToken(uid, [], {}); + const [_, payload64] = token.split('.'); // payload - const { apiKeyUid, exp, searchRules } = JSON.parse(decode64(payload64)) + const { apiKeyUid, exp, searchRules } = JSON.parse(decode64(payload64)); - expect(apiKeyUid).toEqual(uid) - expect(exp).toBeUndefined() - expect(searchRules).toEqual([]) - }) + expect(apiKeyUid).toEqual(uid); + expect(exp).toBeUndefined(); + expect(searchRules).toEqual([]); + }); test(`${permission} key: create a tenant token with array searchRules and test payload`, async () => { - const client = await getClient(permission) - const apiKey = await getKey(permission) - const { uid } = await client.getKey(apiKey) - const token = await client.generateTenantToken(uid, [UID]) - const [_, payload64] = token.split('.') + const client = await getClient(permission); + const apiKey = await getKey(permission); + const { uid } = await client.getKey(apiKey); + const token = await client.generateTenantToken(uid, [UID]); + const [_, payload64] = token.split('.'); // payload - const { apiKeyUid, exp, searchRules } = JSON.parse(decode64(payload64)) + const { apiKeyUid, exp, searchRules } = JSON.parse(decode64(payload64)); - expect(apiKeyUid).toEqual(uid) - expect(exp).toBeUndefined() - expect(searchRules).toEqual([UID]) - }) + expect(apiKeyUid).toEqual(uid); + expect(exp).toBeUndefined(); + expect(searchRules).toEqual([UID]); + }); test(`${permission} key: create a tenant token with oject search rules and test payload`, async () => { - const client = await getClient(permission) - const apiKey = await getKey(permission) - const { uid } = await client.getKey(apiKey) - const token = await client.generateTenantToken(uid, { [UID]: {} }) - const [_, payload64] = token.split('.') + const client = await getClient(permission); + const apiKey = await getKey(permission); + const { uid } = await client.getKey(apiKey); + const token = await client.generateTenantToken(uid, { [UID]: {} }); + const [_, payload64] = token.split('.'); // payload - const { apiKeyUid, exp, searchRules } = JSON.parse(decode64(payload64)) - expect(apiKeyUid).toEqual(uid) - expect(exp).toBeUndefined() - expect(searchRules).toEqual({ [UID]: {} }) - }) + const { apiKeyUid, exp, searchRules } = JSON.parse(decode64(payload64)); + expect(apiKeyUid).toEqual(uid); + expect(exp).toBeUndefined(); + expect(searchRules).toEqual({ [UID]: {} }); + }); test(`${permission} key: Search in tenant token with wildcard`, async () => { - const client = await getClient(permission) - const apiKey = await getKey(permission) - const { uid } = await client.getKey(apiKey) + const client = await getClient(permission); + const apiKey = await getKey(permission); + const { uid } = await client.getKey(apiKey); - const token = await client.generateTenantToken(uid, ['*']) + const token = await client.generateTenantToken(uid, ['*']); - const searchClient = new MeiliSearch({ host: HOST, apiKey: token }) + const searchClient = new MeiliSearch({ host: HOST, apiKey: token }); // search - expect(searchClient.index(UID).search()).resolves.not.toBeUndefined() - }) + expect(searchClient.index(UID).search()).resolves.not.toBeUndefined(); + }); test(`${permission} key: Search in tenant token with custom api key`, async () => { - const masterClient = await getClient('master') + const masterClient = await getClient('master'); const { uid, key } = await masterClient.createKey({ expiresAt: null, description: 'Custom key', actions: ['search'], indexes: [UID], - }) - const client = await getClient(permission) + }); + const client = await getClient(permission); const token = await client.generateTenantToken(uid, ['*'], { apiKey: key, - }) + }); - const searchClient = new MeiliSearch({ host: HOST, apiKey: token }) + const searchClient = new MeiliSearch({ host: HOST, apiKey: token }); // search - expect(searchClient.index(UID).search()).resolves.toBeDefined() - }) + expect(searchClient.index(UID).search()).resolves.toBeDefined(); + }); test(`${permission} key: Search in tenant token with expireAt`, async () => { - const client = await getClient(permission) - const date = new Date('December 17, 4000 03:24:00') - const apiKey = await getKey(permission) - const { uid } = await client.getKey(apiKey) + const client = await getClient(permission); + const date = new Date('December 17, 4000 03:24:00'); + const apiKey = await getKey(permission); + const { uid } = await client.getKey(apiKey); const token = await client.generateTenantToken(uid, ['*'], { expiresAt: date, - }) + }); - const [_, payload] = token.split('.') - const searchClient = new MeiliSearch({ host: HOST, apiKey: token }) + const [_, payload] = token.split('.'); + const searchClient = new MeiliSearch({ host: HOST, apiKey: token }); expect(JSON.parse(decode64(payload)).exp).toEqual( - Math.floor(date.getTime() / 1000) - ) - expect(searchClient.index(UID).search()).resolves.not.toBeUndefined() - }) + Math.floor(date.getTime() / 1000), + ); + expect(searchClient.index(UID).search()).resolves.not.toBeUndefined(); + }); test(`${permission} key: Search in tenant token with expireAt value set in the past`, async () => { - const client = await getClient(permission) - const apiKey = await getKey(permission) - const { uid } = await client.getKey(apiKey) - const date = new Date('December 17, 2000 03:24:00') + const client = await getClient(permission); + const apiKey = await getKey(permission); + const { uid } = await client.getKey(apiKey); + const date = new Date('December 17, 2000 03:24:00'); expect( - client.generateTenantToken(uid, ['*'], { expiresAt: date }) + client.generateTenantToken(uid, ['*'], { expiresAt: date }), ).rejects.toThrow( - `Meilisearch: The expiresAt field must be a date in the future.` - ) - }) + `Meilisearch: The expiresAt field must be a date in the future.`, + ); + }); test(`${permission} key: Search in tenant token with specific index set to null`, async () => { - const client = await getClient(permission) - const apiKey = await getKey(permission) - const { uid } = await client.getKey(apiKey) + const client = await getClient(permission); + const apiKey = await getKey(permission); + const { uid } = await client.getKey(apiKey); const token = await client.generateTenantToken(uid, { [UID]: null, - }) + }); - const searchClient = new MeiliSearch({ host: HOST, apiKey: token }) + const searchClient = new MeiliSearch({ host: HOST, apiKey: token }); // search - expect(searchClient.index(UID).search()).resolves.not.toBeUndefined() - }) + expect(searchClient.index(UID).search()).resolves.not.toBeUndefined(); + }); test(`${permission} key: Search in tenant token with specific index and specific rules`, async () => { // add filterable - const masterClient = await getClient('master') + const masterClient = await getClient('master'); const { taskUid } = await masterClient .index(UID) - .updateFilterableAttributes(['id']) - await masterClient.waitForTask(taskUid) - const client = await getClient(permission) - const apiKey = await getKey(permission) - const { uid } = await client.getKey(apiKey) + .updateFilterableAttributes(['id']); + await masterClient.waitForTask(taskUid); + const client = await getClient(permission); + const apiKey = await getKey(permission); + const { uid } = await client.getKey(apiKey); const token = await client.generateTenantToken(uid, { [UID]: { filter: 'id = 2' }, - }) + }); - const searchClient = new MeiliSearch({ host: HOST, apiKey: token }) + const searchClient = new MeiliSearch({ host: HOST, apiKey: token }); // search - expect(searchClient.index(UID).search()).resolves.not.toBeUndefined() - }) + expect(searchClient.index(UID).search()).resolves.not.toBeUndefined(); + }); test(`${permission} key: Search in tenant token with empty array throws an error`, async () => { - const client = await getClient(permission) - const apiKey = await getKey(permission) - const { uid } = await client.getKey(apiKey) - const token = await client.generateTenantToken(uid, []) + const client = await getClient(permission); + const apiKey = await getKey(permission); + const { uid } = await client.getKey(apiKey); + const token = await client.generateTenantToken(uid, []); - const searchClient = new MeiliSearch({ host: HOST, apiKey: token }) + const searchClient = new MeiliSearch({ host: HOST, apiKey: token }); // search await expect( - searchClient.index(UID).search('pride') - ).rejects.toHaveProperty('cause.code', 'invalid_api_key') - }) + searchClient.index(UID).search('pride'), + ).rejects.toHaveProperty('cause.code', 'invalid_api_key'); + }); test(`${permission} key: Search in tenant token on index with no permissions `, async () => { - const client = await getClient(permission) - const apiKey = await getKey(permission) - const { uid } = await client.getKey(apiKey) - const token = await client.generateTenantToken(uid, { misc: null }) + const client = await getClient(permission); + const apiKey = await getKey(permission); + const { uid } = await client.getKey(apiKey); + const token = await client.generateTenantToken(uid, { misc: null }); - const searchClient = new MeiliSearch({ host: HOST, apiKey: token }) + const searchClient = new MeiliSearch({ host: HOST, apiKey: token }); // search await expect( - searchClient.index(UID).search('pride') - ).rejects.toHaveProperty('cause.code', 'invalid_api_key') - }) + searchClient.index(UID).search('pride'), + ).rejects.toHaveProperty('cause.code', 'invalid_api_key'); + }); test(`${permission} key: Creates tenant token with an expiration date in the past throws an error`, async () => { - const client = await getClient(permission) - const apiKey = await getKey(permission) - const { uid } = await client.getKey(apiKey) - const date = new Date('December 17, 2000 03:24:00') + const client = await getClient(permission); + const apiKey = await getKey(permission); + const { uid } = await client.getKey(apiKey); + const date = new Date('December 17, 2000 03:24:00'); expect( client.generateTenantToken( @@ -251,27 +251,27 @@ describe.each([{ permission: 'Admin' }])( {}, { expiresAt: date, - } - ) + }, + ), ).rejects.toThrow( - `Meilisearch: The expiresAt field must be a date in the future.` - ) - }) + `Meilisearch: The expiresAt field must be a date in the future.`, + ); + }); test(`${permission} key: Creates tenant token with wrong uid type throws an error`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); expect(client.generateTenantToken('1234', ['*'])).rejects.toThrow( - `Meilisearch: The uid of your key is not a valid uuid4. To find out the uid of your key use getKey().` - ) - }) + `Meilisearch: The uid of your key is not a valid uuid4. To find out the uid of your key use getKey().`, + ); + }); test(`${permission} key: Creates a tenant token with no api key in client and in parameters throws an error`, () => { - const client = new MeiliSearch({ host: HOST }) + const client = new MeiliSearch({ host: HOST }); expect(client.generateTenantToken('123', [])).rejects.toThrow( - `Meilisearch: The API key used for the token generation must exist and be of type string.` - ) - }) - } -) + `Meilisearch: The API key used for the token generation must exist and be of type string.`, + ); + }); + }, +); diff --git a/tests/typed_search.test.ts b/tests/typed_search.test.ts index e1f5c1804..64cc019bc 100644 --- a/tests/typed_search.test.ts +++ b/tests/typed_search.test.ts @@ -1,5 +1,5 @@ -import { ErrorStatusCode, SearchResponse } from '../src/types' -import { EnqueuedTask } from '../src/enqueued-task' +import { ErrorStatusCode, SearchResponse } from '../src/types'; +import { EnqueuedTask } from '../src/enqueued-task'; import { clearAllIndexes, config, @@ -7,31 +7,31 @@ import { MeiliSearch, getClient, datasetWithNests, -} from './utils/meilisearch-test-utils' +} from './utils/meilisearch-test-utils'; const index = { uid: 'movies_test', -} +}; const emptyIndex = { uid: 'empty_test', -} +}; interface Movie { - id: number - title: string - comment?: string - genre?: string - isNull?: null - isTrue?: boolean + id: number; + title: string; + comment?: string; + genre?: string; + isNull?: null; + isTrue?: boolean; } interface NestedDocument { - id: number - title: string + id: number; + title: string; info: { - comment?: string - reviewNb?: number - } + comment?: string; + reviewNb?: number; + }; } const dataset = [ @@ -74,13 +74,13 @@ const dataset = [ genre: 'fantasy', }, { id: 42, title: "The Hitchhiker's Guide to the Galaxy", genre: 'fantasy' }, -] +]; -jest.setTimeout(100 * 1000) +jest.setTimeout(100 * 1000); afterAll(() => { - return clearAllIndexes(config) -}) + return clearAllIndexes(config); +}); describe.each([ { permission: 'Master' }, @@ -88,97 +88,97 @@ describe.each([ { permission: 'Search' }, ])('Test on search', ({ permission }) => { beforeAll(async () => { - const client = await getClient('Master') - await clearAllIndexes(config) + const client = await getClient('Master'); + await clearAllIndexes(config); - const task1 = await client.createIndex(index.uid) - await client.waitForTask(task1.taskUid) - const task2 = await client.createIndex(emptyIndex.uid) - await client.waitForTask(task2.taskUid) + const task1 = await client.createIndex(index.uid); + await client.waitForTask(task1.taskUid); + const task2 = await client.createIndex(emptyIndex.uid); + await client.waitForTask(task2.taskUid); - const newFilterableAttributes = ['genre', 'title'] + const newFilterableAttributes = ['genre', 'title']; const task: EnqueuedTask = await client .index(index.uid) - .updateFilterableAttributes(newFilterableAttributes) + .updateFilterableAttributes(newFilterableAttributes); - await client.waitForTask(task.taskUid) + await client.waitForTask(task.taskUid); const { taskUid } = await client .index(index.uid) - .addDocuments(dataset) - await client.waitForTask(taskUid) - }) + .addDocuments(dataset); + await client.waitForTask(taskUid); + }); test(`${permission} key: Basic search`, async () => { - const client = await getClient(permission) - const response = await client.index(index.uid).search('prince', {}) - expect(response.hits.length === 2).toBeTruthy() - expect(response.limit === 20).toBeTruthy() - expect(response.offset === 0).toBeTruthy() - expect(response).toHaveProperty('processingTimeMs', expect.any(Number)) - expect(response.query === 'prince').toBeTruthy() - }) + const client = await getClient(permission); + const response = await client.index(index.uid).search('prince', {}); + expect(response.hits.length === 2).toBeTruthy(); + expect(response.limit === 20).toBeTruthy(); + expect(response.offset === 0).toBeTruthy(); + expect(response).toHaveProperty('processingTimeMs', expect.any(Number)); + expect(response.query === 'prince').toBeTruthy(); + }); test(`${permission} key: Search with query in searchParams`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const response = await client .index(index.uid) - .search('other', { q: 'prince' }) // ensures `q` is a valid field in SearchParams type + .search('other', { q: 'prince' }); // ensures `q` is a valid field in SearchParams type - expect(response).toHaveProperty('query', 'prince') - }) + expect(response).toHaveProperty('query', 'prince'); + }); test(`${permission} key: Search with options`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const response = await client .index(index.uid) - .search('prince', { limit: 1 }) - expect(response.hits.length === 1).toBeTruthy() - expect(response.offset === 0).toBeTruthy() - expect(response.limit === 1).toBeTruthy() - expect(response).toHaveProperty('processingTimeMs', expect.any(Number)) - expect(response.query === 'prince').toBeTruthy() - }) + .search('prince', { limit: 1 }); + expect(response.hits.length === 1).toBeTruthy(); + expect(response.offset === 0).toBeTruthy(); + expect(response.limit === 1).toBeTruthy(); + expect(response).toHaveProperty('processingTimeMs', expect.any(Number)); + expect(response.query === 'prince').toBeTruthy(); + }); test(`${permission} key: Search with limit and offset`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const response = await client.index(index.uid).search('prince', { limit: 1, offset: 1, - }) - expect(response.hits.length === 1).toBeTruthy() - expect(response.offset === 1).toBeTruthy() + }); + expect(response.hits.length === 1).toBeTruthy(); + expect(response.offset === 1).toBeTruthy(); // expect(response.bloub).toEqual(0) -> ERROR, bloub does not exist on type Response - expect(response.limit === 1).toBeTruthy() - expect(response).toHaveProperty('processingTimeMs', expect.any(Number)) - expect(response.query === 'prince').toBeTruthy() - expect(response.hits[0].id).toEqual(4) + expect(response.limit === 1).toBeTruthy(); + expect(response).toHaveProperty('processingTimeMs', expect.any(Number)); + expect(response.query === 'prince').toBeTruthy(); + expect(response.hits[0].id).toEqual(4); expect(response.hits[0].title).toEqual( - 'Harry Potter and the Half-Blood Prince' - ) - expect(response.hits[0].comment).toEqual('The best book') - expect(response.hits[0].genre).toEqual('fantasy') - expect(response.query === 'prince').toBeTruthy() - }) + 'Harry Potter and the Half-Blood Prince', + ); + expect(response.hits[0].comment).toEqual('The best book'); + expect(response.hits[0].genre).toEqual('fantasy'); + expect(response.query === 'prince').toBeTruthy(); + }); test(`${permission} key: Search with matches parameter and small croplength`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const response = await client.index(index.uid).search('prince', { filter: 'title = "Le Petit Prince"', attributesToCrop: ['*'], cropLength: 5, showMatchesPosition: true, - }) - expect(response.hits.length === 1).toBeTruthy() + }); + expect(response.hits.length === 1).toBeTruthy(); expect(response.hits[0]?._matchesPosition?.comment).toEqual([ { start: 22, length: 6 }, - ]) + ]); expect(response.hits[0]?._matchesPosition?.title).toEqual([ { start: 9, length: 6 }, - ]) - }) + ]); + }); test(`${permission} key: Search with all options but not all fields`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const response = await client.index(index.uid).search('prince', { limit: 5, offset: 0, @@ -188,30 +188,30 @@ describe.each([ attributesToHighlight: ['*'], filter: 'title = "Le Petit Prince"', showMatchesPosition: true, - }) - expect(response.hits.length === 1).toBeTruthy() - expect(response.offset === 0).toBeTruthy() - expect(response.limit === 5).toBeTruthy() - expect(response).toHaveProperty('processingTimeMs', expect.any(Number)) - expect(response.query === 'prince').toBeTruthy() + }); + expect(response.hits.length === 1).toBeTruthy(); + expect(response.offset === 0).toBeTruthy(); + expect(response.limit === 5).toBeTruthy(); + expect(response).toHaveProperty('processingTimeMs', expect.any(Number)); + expect(response.query === 'prince').toBeTruthy(); expect(response.hits[0]._formatted).toHaveProperty( 'title', - 'Le Petit Prince' - ) - expect(response.hits[0]._formatted?.id).toEqual('456') - expect(response.hits[0]).not.toHaveProperty('comment') - expect(response.hits[0]).not.toHaveProperty('description') - expect(response.hits[0]._formatted).toHaveProperty('comment') - expect(response.hits[0]._formatted).not.toHaveProperty('description') - expect(response.hits.length === 1).toBeTruthy() + 'Le Petit Prince', + ); + expect(response.hits[0]._formatted?.id).toEqual('456'); + expect(response.hits[0]).not.toHaveProperty('comment'); + expect(response.hits[0]).not.toHaveProperty('description'); + expect(response.hits[0]._formatted).toHaveProperty('comment'); + expect(response.hits[0]._formatted).not.toHaveProperty('description'); + expect(response.hits.length === 1).toBeTruthy(); expect(response.hits[0]).toHaveProperty( '_matchesPosition', - expect.any(Object) - ) - }) + expect.any(Object), + ); + }); test(`${permission} key: Search with all options and all fields`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const response = await client.index(index.uid).search('prince', { limit: 5, offset: 0, @@ -221,27 +221,27 @@ describe.each([ attributesToHighlight: ['*'], filter: 'title = "Le Petit Prince"', showMatchesPosition: true, - }) - expect(response.hits.length === 1).toBeTruthy() - expect(response.offset === 0).toBeTruthy() - expect(response.limit === 5).toBeTruthy() - expect(response).toHaveProperty('processingTimeMs', expect.any(Number)) - expect(response.query === 'prince').toBeTruthy() - expect(response.hits[0]?.title === 'Le Petit Prince').toBeTruthy() + }); + expect(response.hits.length === 1).toBeTruthy(); + expect(response.offset === 0).toBeTruthy(); + expect(response.limit === 5).toBeTruthy(); + expect(response).toHaveProperty('processingTimeMs', expect.any(Number)); + expect(response.query === 'prince').toBeTruthy(); + expect(response.hits[0]?.title === 'Le Petit Prince').toBeTruthy(); expect( - response.hits[0]?._matchesPosition?.title?.[0]?.start === 9 - ).toBeTruthy() + response.hits[0]?._matchesPosition?.title?.[0]?.start === 9, + ).toBeTruthy(); expect( - response.hits[0]?._matchesPosition?.title?.[0]?.length === 6 - ).toBeTruthy() + response.hits[0]?._matchesPosition?.title?.[0]?.length === 6, + ).toBeTruthy(); expect(response.hits[0]._formatted).toHaveProperty( 'title', - 'Le Petit Prince' - ) - }) + 'Le Petit Prince', + ); + }); test(`${permission} key: Search with all options but specific fields`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const response = await client.index(index.uid).search('prince', { limit: 5, offset: 0, @@ -251,221 +251,221 @@ describe.each([ attributesToHighlight: ['id', 'title'], filter: 'title = "Le Petit Prince"', showMatchesPosition: true, - }) - expect(response.hits.length === 1).toBeTruthy() - expect(response.offset === 0).toBeTruthy() - expect(response.limit === 5).toBeTruthy() - expect(response).toHaveProperty('processingTimeMs', expect.any(Number)) - expect(response.query === 'prince').toBeTruthy() - - expect(response.hits[0].id).toEqual(456) - expect(response.hits[0].title).toEqual('Le Petit Prince') + }); + expect(response.hits.length === 1).toBeTruthy(); + expect(response.offset === 0).toBeTruthy(); + expect(response.limit === 5).toBeTruthy(); + expect(response).toHaveProperty('processingTimeMs', expect.any(Number)); + expect(response.query === 'prince').toBeTruthy(); + + expect(response.hits[0].id).toEqual(456); + expect(response.hits[0].title).toEqual('Le Petit Prince'); // ERROR Property 'comment' does not exist on type 'Hit>'. // expect(response.hits[0].comment).toEqual('comment') - expect(response.hits[0]?.title === 'Le Petit Prince').toBeTruthy() + expect(response.hits[0]?.title === 'Le Petit Prince').toBeTruthy(); expect(response.hits[0]?._matchesPosition?.title).toEqual([ { start: 9, length: 6 }, - ]) + ]); expect(response.hits[0]._formatted).toHaveProperty( 'title', - 'Le Petit Prince' - ) + 'Le Petit Prince', + ); expect(response.hits[0]).not.toHaveProperty( 'description', - expect.any(Object) - ) - expect(response.hits[0]._formatted).not.toHaveProperty('comment') - }) + expect.any(Object), + ); + expect(response.hits[0]._formatted).not.toHaveProperty('comment'); + }); test(`${permission} key: Search with specific fields in attributesToHighlight and check for types of number fields`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const response = await client.index(index.uid).search('prince', { attributesToHighlight: ['title'], - }) - expect(response.hits[0]._formatted?.id).toEqual('456') - expect(response.hits[0]._formatted?.isNull).toEqual(null) - expect(response.hits[0]._formatted?.isTrue).toEqual(true) - }) + }); + expect(response.hits[0]._formatted?.id).toEqual('456'); + expect(response.hits[0]._formatted?.isNull).toEqual(null); + expect(response.hits[0]._formatted?.isTrue).toEqual(true); + }); test(`${permission} key: Search with specific fields in attributesToHighlight and check for types of number fields`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const response = await client.index(index.uid).search('prince', { attributesToHighlight: ['title', 'id'], - }) - expect(response.hits[0]._formatted?.id).toEqual('456') - expect(response.hits[0]._formatted?.isNull).toEqual(null) - expect(response.hits[0]._formatted?.isTrue).toEqual(true) - }) + }); + expect(response.hits[0]._formatted?.id).toEqual('456'); + expect(response.hits[0]._formatted?.isNull).toEqual(null); + expect(response.hits[0]._formatted?.isTrue).toEqual(true); + }); test(`${permission} key: Search with filter and facets`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const response = await client.index(index.uid).search('a', { filter: ['genre=romance'], facets: ['genre'], - }) - expect(response.facetDistribution?.genre?.romance === 2).toBeTruthy() - expect(response.hits.length === 2).toBeTruthy() - }) + }); + expect(response.facetDistribution?.genre?.romance === 2).toBeTruthy(); + expect(response.hits.length === 2).toBeTruthy(); + }); test(`${permission} key: Search with filter with spaces`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const response = await client.index(index.uid).search('h', { filter: ['genre="sci fi"'], - }) - expect(response).toHaveProperty('hits') - expect(Array.isArray(response.hits)).toBe(true) - expect(response.hits.length === 1).toBeTruthy() - }) + }); + expect(response).toHaveProperty('hits'); + expect(Array.isArray(response.hits)).toBe(true); + expect(response.hits.length === 1).toBeTruthy(); + }); test(`${permission} key: Search with multiple filter`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const response = await client.index(index.uid).search('a', { filter: ['genre=romance', ['genre=romance', 'genre=romance']], facets: ['genre'], - }) - expect(response.facetDistribution?.genre?.romance === 2).toBeTruthy() - expect(response.hits.length === 2).toBeTruthy() - }) + }); + expect(response.facetDistribution?.genre?.romance === 2).toBeTruthy(); + expect(response.hits.length === 2).toBeTruthy(); + }); test(`${permission} key: Search with multiple filter and placeholder search using undefined`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const response = await client.index(index.uid).search(undefined, { filter: ['genre = fantasy'], facets: ['genre'], - }) - expect(response.facetDistribution?.genre?.fantasy === 2).toBeTruthy() - expect(response.hits.length === 2).toBeTruthy() - }) + }); + expect(response.facetDistribution?.genre?.fantasy === 2).toBeTruthy(); + expect(response.hits.length === 2).toBeTruthy(); + }); test(`${permission} key: Search with multiple filter and placeholder search using NULL`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const response = await client.index(index.uid).search(null, { filter: ['genre = fantasy'], facets: ['genre'], - }) - expect(response.facetDistribution?.genre?.fantasy === 2).toBeTruthy() - expect(response.hits.length === 2).toBeTruthy() - }) + }); + expect(response.facetDistribution?.genre?.fantasy === 2).toBeTruthy(); + expect(response.hits.length === 2).toBeTruthy(); + }); test(`${permission} key: Search on index with no documents and no primary key`, async () => { - const client = await getClient(permission) - const response = await client.index(emptyIndex.uid).search('prince', {}) + const client = await getClient(permission); + const response = await client.index(emptyIndex.uid).search('prince', {}); - expect(response.hits.length === 0).toBeTruthy() - expect(response).toHaveProperty('processingTimeMs', expect.any(Number)) - expect(response.query === 'prince').toBeTruthy() - }) + expect(response.hits.length === 0).toBeTruthy(); + expect(response).toHaveProperty('processingTimeMs', expect.any(Number)); + expect(response.query === 'prince').toBeTruthy(); + }); test(`${permission} key: search with pagination parameters hitsPerPage/page and offset`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const response = await client.index(index.uid).search('', { hitsPerPage: 1, page: 1, limit: 1, - }) + }); - expect(response.hits.length).toEqual(1) - expect(response.hitsPerPage === 1).toBeTruthy() - expect(response.page === 1).toBeTruthy() - expect(response.totalPages === 7).toBeTruthy() - expect(response.totalHits === 7).toBeTruthy() - }) + expect(response.hits.length).toEqual(1); + expect(response.hitsPerPage === 1).toBeTruthy(); + expect(response.page === 1).toBeTruthy(); + expect(response.totalPages === 7).toBeTruthy(); + expect(response.totalHits === 7).toBeTruthy(); + }); test(`${permission} key: Try to Search on deleted index and fail`, async () => { - const client = await getClient(permission) - const masterClient = await getClient('Master') - const { taskUid } = await masterClient.index(index.uid).delete() - await masterClient.waitForTask(taskUid) + const client = await getClient(permission); + const masterClient = await getClient('Master'); + const { taskUid } = await masterClient.index(index.uid).delete(); + await masterClient.waitForTask(taskUid); await expect( - client.index(index.uid).search('prince') - ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INDEX_NOT_FOUND) - }) -}) + client.index(index.uid).search('prince'), + ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INDEX_NOT_FOUND); + }); +}); describe.each([{ permission: 'Master' }])( 'Tests on documents with nested objects', ({ permission }) => { beforeEach(async () => { - await clearAllIndexes(config) - const client = await getClient('Master') - await client.createIndex(index.uid) + await clearAllIndexes(config); + const client = await getClient('Master'); + await client.createIndex(index.uid); const { taskUid: documentAdditionTask } = await client .index(index.uid) - .addDocuments(datasetWithNests) - await client.waitForTask(documentAdditionTask) - }) + .addDocuments(datasetWithNests); + await client.waitForTask(documentAdditionTask); + }); test(`${permission} key: search on nested content with no parameters`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const response: SearchResponse = await client .index(index.uid) - .search('An awesome', {}) + .search('An awesome', {}); - expect(response.hits[0].info?.comment === 'An awesome book').toBeTruthy() - expect(response.hits[0].info?.reviewNb === 900).toBeTruthy() - }) + expect(response.hits[0].info?.comment === 'An awesome book').toBeTruthy(); + expect(response.hits[0].info?.reviewNb === 900).toBeTruthy(); + }); test(`${permission} key: search on nested content with searchable on specific nested field`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const { taskUid: settingsUpdateTask }: EnqueuedTask = await client .index(index.uid) .updateSettings({ searchableAttributes: ['title', 'info.comment'], - }) - await client.waitForTask(settingsUpdateTask) + }); + await client.waitForTask(settingsUpdateTask); const response: SearchResponse = await client .index(index.uid) - .search('An awesome', {}) + .search('An awesome', {}); - expect(response.hits[0].info?.comment === 'An awesome book').toBeTruthy() - expect(response.hits[0].info?.reviewNb === 900).toBeTruthy() - }) + expect(response.hits[0].info?.comment === 'An awesome book').toBeTruthy(); + expect(response.hits[0].info?.reviewNb === 900).toBeTruthy(); + }); test(`${permission} key: search on nested content with sort`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const { taskUid: settingsUpdateTask }: EnqueuedTask = await client .index(index.uid) .updateSettings({ searchableAttributes: ['title', 'info.comment'], sortableAttributes: ['info.reviewNb'], - }) - await client.waitForTask(settingsUpdateTask) + }); + await client.waitForTask(settingsUpdateTask); const response: SearchResponse = await client .index(index.uid) .search('', { sort: ['info.reviewNb:desc'], - }) + }); - expect(response.hits[0].info?.comment === 'The best book').toBeTruthy() - expect(response.hits[0].info?.reviewNb === 1000).toBeTruthy() - }) - } -) + expect(response.hits[0].info?.comment === 'The best book').toBeTruthy(); + expect(response.hits[0].info?.reviewNb === 1000).toBeTruthy(); + }); + }, +); describe.each([{ permission: 'No' }])( 'Test failing test on search', ({ permission }) => { beforeEach(async () => { - await clearAllIndexes(config) - }) + await clearAllIndexes(config); + }); test(`${permission} key: Try Basic search and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect( - client.index(index.uid).search('prince') + client.index(index.uid).search('prince'), ).rejects.toHaveProperty( 'cause.code', - ErrorStatusCode.MISSING_AUTHORIZATION_HEADER - ) - }) - } -) + ErrorStatusCode.MISSING_AUTHORIZATION_HEADER, + ); + }); + }, +); describe.each([ { host: BAD_HOST, trailing: false }, @@ -473,26 +473,26 @@ describe.each([ { host: `${BAD_HOST}/trailing/`, trailing: true }, ])('Tests on url construction', ({ host, trailing }) => { test(`Test get search route`, async () => { - const route = `indexes/${index.uid}/search` - const client = new MeiliSearch({ host }) - const strippedHost = trailing ? host.slice(0, -1) : host + const route = `indexes/${index.uid}/search`; + const client = new MeiliSearch({ host }); + const strippedHost = trailing ? host.slice(0, -1) : host; await expect( - client.index(index.uid).search() + client.index(index.uid).search(), ).rejects.toHaveProperty( 'message', - `Request to ${strippedHost}/${route} has failed` - ) - }) + `Request to ${strippedHost}/${route} has failed`, + ); + }); test(`Test post search route`, async () => { - const route = `indexes/${index.uid}/search` - const client = new MeiliSearch({ host }) - const strippedHost = trailing ? host.slice(0, -1) : host + const route = `indexes/${index.uid}/search`; + const client = new MeiliSearch({ host }); + const strippedHost = trailing ? host.slice(0, -1) : host; await expect( - client.index(index.uid).search() + client.index(index.uid).search(), ).rejects.toHaveProperty( 'message', - `Request to ${strippedHost}/${route} has failed` - ) - }) -}) + `Request to ${strippedHost}/${route} has failed`, + ); + }); +}); diff --git a/tests/typo_tolerance.test.ts b/tests/typo_tolerance.test.ts index 844d814b4..e559bb2df 100644 --- a/tests/typo_tolerance.test.ts +++ b/tests/typo_tolerance.test.ts @@ -1,4 +1,4 @@ -import { ErrorStatusCode } from '../src/types' +import { ErrorStatusCode } from '../src/types'; import { clearAllIndexes, config, @@ -6,11 +6,11 @@ import { MeiliSearch, getClient, dataset, -} from './utils/meilisearch-test-utils' +} from './utils/meilisearch-test-utils'; const index = { uid: 'movies_test', -} +}; const defaultTypoTolerance = { enabled: true, @@ -20,32 +20,32 @@ const defaultTypoTolerance = { }, disableOnWords: [], disableOnAttributes: [], -} +}; -jest.setTimeout(100 * 1000) +jest.setTimeout(100 * 1000); afterAll(() => { - return clearAllIndexes(config) -}) + return clearAllIndexes(config); +}); describe.each([{ permission: 'Master' }, { permission: 'Admin' }])( 'Tests on typo tolerance', ({ permission }) => { beforeEach(async () => { - await clearAllIndexes(config) - const client = await getClient('master') - const { taskUid } = await client.index(index.uid).addDocuments(dataset) - await client.waitForTask(taskUid) - }) + await clearAllIndexes(config); + const client = await getClient('master'); + const { taskUid } = await client.index(index.uid).addDocuments(dataset); + await client.waitForTask(taskUid); + }); test(`${permission} key: Get default typo tolerance settings`, async () => { - const client = await getClient(permission) - const response = await client.index(index.uid).getTypoTolerance() - expect(response).toEqual(defaultTypoTolerance) - }) + const client = await getClient(permission); + const response = await client.index(index.uid).getTypoTolerance(); + expect(response).toEqual(defaultTypoTolerance); + }); test(`${permission} key: Update typo tolerance settings`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const newTypoTolerance = { enabled: false, minWordSizeForTypos: { @@ -54,107 +54,107 @@ describe.each([{ permission: 'Master' }, { permission: 'Admin' }])( }, disableOnWords: ['title'], disableOnAttributes: ['hello'], - } + }; const task = await client .index(index.uid) - .updateTypoTolerance(newTypoTolerance) - await client.index(index.uid).waitForTask(task.taskUid) + .updateTypoTolerance(newTypoTolerance); + await client.index(index.uid).waitForTask(task.taskUid); - const response = await client.index(index.uid).getTypoTolerance() + const response = await client.index(index.uid).getTypoTolerance(); - expect(response).toEqual(newTypoTolerance) - }) + expect(response).toEqual(newTypoTolerance); + }); test(`${permission} key: Update typo tolerance using null as value`, async () => { - const client = await getClient(permission) - const task = await client.index(index.uid).updateTypoTolerance(null) - await client.index(index.uid).waitForTask(task.taskUid) + const client = await getClient(permission); + const task = await client.index(index.uid).updateTypoTolerance(null); + await client.index(index.uid).waitForTask(task.taskUid); - const response = await client.index(index.uid).getTypoTolerance() + const response = await client.index(index.uid).getTypoTolerance(); - expect(response).toEqual(defaultTypoTolerance) - }) + expect(response).toEqual(defaultTypoTolerance); + }); test(`${permission} key: Reset typo tolerance settings`, async () => { - const client = await getClient(permission) - const task = await client.index(index.uid).resetTypoTolerance() - await client.index(index.uid).waitForTask(task.taskUid) + const client = await getClient(permission); + const task = await client.index(index.uid).resetTypoTolerance(); + await client.index(index.uid).waitForTask(task.taskUid); - const response = await client.index(index.uid).getTypoTolerance() + const response = await client.index(index.uid).getTypoTolerance(); - expect(response).toEqual(defaultTypoTolerance) - }) - } -) + expect(response).toEqual(defaultTypoTolerance); + }); + }, +); describe.each([{ permission: 'Search' }])( 'Tests on typo tolerance', ({ permission }) => { beforeEach(async () => { - await clearAllIndexes(config) - }) + await clearAllIndexes(config); + }); test(`${permission} key: try to get typo tolerance settings and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect( - client.index(index.uid).getTypoTolerance() - ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY) - }) + client.index(index.uid).getTypoTolerance(), + ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY); + }); test(`${permission} key: try to update typo tolerance settings and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect( - client.index(index.uid).updateTypoTolerance({}) - ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY) - }) + client.index(index.uid).updateTypoTolerance({}), + ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY); + }); test(`${permission} key: try to reset typo tolerance settings and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect( - client.index(index.uid).resetTypoTolerance() - ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY) - }) - } -) + client.index(index.uid).resetTypoTolerance(), + ).rejects.toHaveProperty('cause.code', ErrorStatusCode.INVALID_API_KEY); + }); + }, +); describe.each([{ permission: 'No' }])( 'Tests on typo tolerance', ({ permission }) => { beforeEach(async () => { - await clearAllIndexes(config) - }) + await clearAllIndexes(config); + }); test(`${permission} key: try to get typo tolerance settings and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect( - client.index(index.uid).getTypoTolerance() + client.index(index.uid).getTypoTolerance(), ).rejects.toHaveProperty( 'cause.code', - ErrorStatusCode.MISSING_AUTHORIZATION_HEADER - ) - }) + ErrorStatusCode.MISSING_AUTHORIZATION_HEADER, + ); + }); test(`${permission} key: try to update typo tolerance settings and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect( - client.index(index.uid).updateTypoTolerance({}) + client.index(index.uid).updateTypoTolerance({}), ).rejects.toHaveProperty( 'cause.code', - ErrorStatusCode.MISSING_AUTHORIZATION_HEADER - ) - }) + ErrorStatusCode.MISSING_AUTHORIZATION_HEADER, + ); + }); test(`${permission} key: try to reset typo tolerance settings and be denied`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); await expect( - client.index(index.uid).resetTypoTolerance() + client.index(index.uid).resetTypoTolerance(), ).rejects.toHaveProperty( 'cause.code', - ErrorStatusCode.MISSING_AUTHORIZATION_HEADER - ) - }) - } -) + ErrorStatusCode.MISSING_AUTHORIZATION_HEADER, + ); + }); + }, +); describe.each([ { host: BAD_HOST, trailing: false }, @@ -162,38 +162,38 @@ describe.each([ { host: `${BAD_HOST}/trailing/`, trailing: true }, ])('Tests on url construction', ({ host, trailing }) => { test(`Test get typo tolerance route`, async () => { - const route = `indexes/${index.uid}/settings/typo-tolerance` - const client = new MeiliSearch({ host }) - const strippedHost = trailing ? host.slice(0, -1) : host + const route = `indexes/${index.uid}/settings/typo-tolerance`; + const client = new MeiliSearch({ host }); + const strippedHost = trailing ? host.slice(0, -1) : host; await expect( - client.index(index.uid).getTypoTolerance() + client.index(index.uid).getTypoTolerance(), ).rejects.toHaveProperty( 'message', - `Request to ${strippedHost}/${route} has failed` - ) - }) + `Request to ${strippedHost}/${route} has failed`, + ); + }); test(`Test update typo tolerance route`, async () => { - const route = `indexes/${index.uid}/settings/typo-tolerance` - const client = new MeiliSearch({ host }) - const strippedHost = trailing ? host.slice(0, -1) : host + const route = `indexes/${index.uid}/settings/typo-tolerance`; + const client = new MeiliSearch({ host }); + const strippedHost = trailing ? host.slice(0, -1) : host; await expect( - client.index(index.uid).updateTypoTolerance({}) + client.index(index.uid).updateTypoTolerance({}), ).rejects.toHaveProperty( 'message', - `Request to ${strippedHost}/${route} has failed` - ) - }) + `Request to ${strippedHost}/${route} has failed`, + ); + }); test(`Test reset typo tolerance route`, async () => { - const route = `indexes/${index.uid}/settings/typo-tolerance` - const client = new MeiliSearch({ host }) - const strippedHost = trailing ? host.slice(0, -1) : host + const route = `indexes/${index.uid}/settings/typo-tolerance`; + const client = new MeiliSearch({ host }); + const strippedHost = trailing ? host.slice(0, -1) : host; await expect( - client.index(index.uid).resetTypoTolerance() + client.index(index.uid).resetTypoTolerance(), ).rejects.toHaveProperty( 'message', - `Request to ${strippedHost}/${route} has failed` - ) - }) -}) + `Request to ${strippedHost}/${route} has failed`, + ); + }); +}); diff --git a/tests/unit.test.ts b/tests/unit.test.ts index 4d16e38cf..69ef30b9a 100644 --- a/tests/unit.test.ts +++ b/tests/unit.test.ts @@ -2,25 +2,25 @@ import { clearAllIndexes, config, MeiliSearch, -} from './utils/meilisearch-test-utils' +} from './utils/meilisearch-test-utils'; afterAll(() => { - return clearAllIndexes(config) -}) + return clearAllIndexes(config); +}); test(`Client handles host URL with domain and path`, () => { - const customHost = `${config.host}/api/` + const customHost = `${config.host}/api/`; const client = new MeiliSearch({ host: customHost, - }) - expect(client.config.host).toBe(customHost) - expect(client.httpRequest.url.href).toBe(customHost) -}) + }); + expect(client.config.host).toBe(customHost); + expect(client.httpRequest.url.href).toBe(customHost); +}); test(`Client handles host URL with domain and path and no trailing slash`, () => { - const customHost = `${config.host}/api` + const customHost = `${config.host}/api`; const client = new MeiliSearch({ host: customHost, - }) - expect(client.httpRequest.url.href).toBe(customHost + '/') -}) + }); + expect(client.httpRequest.url.href).toBe(customHost + '/'); +}); diff --git a/tests/utils/meilisearch-test-utils.ts b/tests/utils/meilisearch-test-utils.ts index bbe8b6aed..d1313328c 100644 --- a/tests/utils/meilisearch-test-utils.ts +++ b/tests/utils/meilisearch-test-utils.ts @@ -1,95 +1,95 @@ -import { MeiliSearch, Index } from '../../src' -import { Config } from '../../src/types' +import { MeiliSearch, Index } from '../../src'; +import { Config } from '../../src/types'; // testing -const MASTER_KEY = 'masterKey' -const HOST = process.env.MEILISEARCH_URL || 'http://127.0.0.1:7700' -const BAD_HOST = 'http://127.0.0.1:7701' +const MASTER_KEY = 'masterKey'; +const HOST = process.env.MEILISEARCH_URL || 'http://127.0.0.1:7700'; +const BAD_HOST = 'http://127.0.0.1:7701'; const config = { host: HOST, apiKey: MASTER_KEY, -} +}; const badHostClient = new MeiliSearch({ host: BAD_HOST, apiKey: MASTER_KEY, -}) +}); const masterClient = new MeiliSearch({ host: HOST, apiKey: MASTER_KEY, -}) +}); const anonymousClient = new MeiliSearch({ host: HOST, -}) +}); async function getKey(permission: string): Promise { if (permission === 'No') { - return '' + return ''; } - const { results: keys } = await masterClient.getKeys() + const { results: keys } = await masterClient.getKeys(); if (permission === 'Search') { const key = keys.find( - (key: any) => key.name === 'Default Search API Key' - )?.key - return key || '' + (key: any) => key.name === 'Default Search API Key', + )?.key; + return key || ''; } if (permission === 'Admin') { const key = keys.find( - (key: any) => key.name === 'Default Admin API Key' - )?.key - return key || '' + (key: any) => key.name === 'Default Admin API Key', + )?.key; + return key || ''; } - return MASTER_KEY + return MASTER_KEY; } async function getClient(permission: string): Promise { if (permission === 'No') { const anonymousClient = new MeiliSearch({ host: HOST, - }) - return anonymousClient + }); + return anonymousClient; } if (permission === 'Search') { - const searchKey = await getKey(permission) + const searchKey = await getKey(permission); const searchClient = new MeiliSearch({ host: HOST, apiKey: searchKey, - }) - return searchClient + }); + return searchClient; } if (permission === 'Admin') { - const adminKey = await getKey(permission) + const adminKey = await getKey(permission); const adminClient = new MeiliSearch({ host: HOST, apiKey: adminKey, - }) - return adminClient + }); + return adminClient; } - return masterClient + return masterClient; } const clearAllIndexes = async (config: Config): Promise => { - const client = new MeiliSearch(config) + const client = new MeiliSearch(config); - const { results } = await client.getRawIndexes() - const indexes = results.map((elem) => elem.uid) + const { results } = await client.getRawIndexes(); + const indexes = results.map((elem) => elem.uid); - const taskIds = [] + const taskIds = []; for (const indexUid of indexes) { - const { taskUid } = await client.index(indexUid).delete() - taskIds.push(taskUid) + const { taskUid } = await client.index(indexUid).delete(); + taskIds.push(taskUid); } - await client.waitForTasks(taskIds) -} + await client.waitForTasks(taskIds); +}; function decode64(buff: string) { - return Buffer.from(buff, 'base64').toString() + return Buffer.from(buff, 'base64').toString(); } const datasetWithNests = [ @@ -142,7 +142,7 @@ const datasetWithNests = [ }, }, { id: 7, title: "The Hitchhiker's Guide to the Galaxy" }, -] +]; const dataset = [ { id: 123, title: 'Pride and Prejudice', comment: 'A great book' }, @@ -156,13 +156,13 @@ const dataset = [ comment: 'The best book', }, { id: 42, title: "The Hitchhiker's Guide to the Galaxy" }, -] +]; export type Book = { - id: number - title: string - comment: string -} + id: number; + title: string; + comment: string; +}; export { clearAllIndexes, @@ -180,4 +180,4 @@ export { decode64, dataset, datasetWithNests, -} +}; diff --git a/tests/wait_for_task.test.ts b/tests/wait_for_task.test.ts index f0a4d8b57..98a518444 100644 --- a/tests/wait_for_task.test.ts +++ b/tests/wait_for_task.test.ts @@ -1,169 +1,169 @@ -import { TaskStatus } from '../src' +import { TaskStatus } from '../src'; import { clearAllIndexes, config, getClient, dataset, -} from './utils/meilisearch-test-utils' +} from './utils/meilisearch-test-utils'; const index = { uid: 'movies_test', -} +}; -jest.setTimeout(100 * 1000) +jest.setTimeout(100 * 1000); afterAll(() => { - return clearAllIndexes(config) -}) + return clearAllIndexes(config); +}); describe.each([{ permission: 'Master' }, { permission: 'Admin' }])( 'Test on wait for task', ({ permission }) => { beforeEach(async () => { - const client = await getClient('Master') - const { taskUid } = await client.createIndex(index.uid) - await client.waitForTask(taskUid) - }) + const client = await getClient('Master'); + const { taskUid } = await client.createIndex(index.uid); + await client.waitForTask(taskUid); + }); // Client Wait for task test(`${permission} key: Tests wait for task in client until done and resolved`, async () => { - const client = await getClient(permission) - const { taskUid } = await client.index(index.uid).addDocuments(dataset) + const client = await getClient(permission); + const { taskUid } = await client.index(index.uid).addDocuments(dataset); - const update = await client.waitForTask(taskUid) + const update = await client.waitForTask(taskUid); - expect(update).toHaveProperty('status', TaskStatus.TASK_SUCCEEDED) - }) + expect(update).toHaveProperty('status', TaskStatus.TASK_SUCCEEDED); + }); test(`${permission} key: Tests wait for task in client with custom interval and timeout until done and resolved`, async () => { - const client = await getClient(permission) - const { taskUid } = await client.index(index.uid).addDocuments(dataset) + const client = await getClient(permission); + const { taskUid } = await client.index(index.uid).addDocuments(dataset); const update = await client.waitForTask(taskUid, { timeOutMs: 6000, intervalMs: 100, - }) + }); - expect(update).toHaveProperty('status', TaskStatus.TASK_SUCCEEDED) - }) + expect(update).toHaveProperty('status', TaskStatus.TASK_SUCCEEDED); + }); test(`${permission} key: Tests wait for task in client with custom timeout and interval at 0 done and resolved`, async () => { - const client = await getClient(permission) - const { taskUid } = await client.index(index.uid).addDocuments(dataset) + const client = await getClient(permission); + const { taskUid } = await client.index(index.uid).addDocuments(dataset); const update = await client.waitForTask(taskUid, { timeOutMs: 6000, intervalMs: 0, - }) + }); - expect(update).toHaveProperty('status', TaskStatus.TASK_SUCCEEDED) - }) + expect(update).toHaveProperty('status', TaskStatus.TASK_SUCCEEDED); + }); test(`${permission} key: Try to wait for task in client with small timeout and raise an error`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); - const { taskUid } = await client.index(index.uid).addDocuments(dataset) + const { taskUid } = await client.index(index.uid).addDocuments(dataset); await expect( - client.waitForTask(taskUid, { timeOutMs: 0 }) - ).rejects.toHaveProperty('name', 'MeiliSearchTimeOutError') - }) + client.waitForTask(taskUid, { timeOutMs: 0 }), + ).rejects.toHaveProperty('name', 'MeiliSearchTimeOutError'); + }); // Index Wait for task test(`${permission} key: Tests wait for task with an index instance`, async () => { - const client = await getClient(permission) - const { taskUid } = await client.index(index.uid).addDocuments(dataset) + const client = await getClient(permission); + const { taskUid } = await client.index(index.uid).addDocuments(dataset); - const update = await client.index(index.uid).waitForTask(taskUid) + const update = await client.index(index.uid).waitForTask(taskUid); - expect(update).toHaveProperty('status', TaskStatus.TASK_SUCCEEDED) - }) + expect(update).toHaveProperty('status', TaskStatus.TASK_SUCCEEDED); + }); // Client Wait for tasks test(`${permission} key: Tests wait for tasks in client until done and resolved`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const { taskUid: task1 } = await client .index(index.uid) - .addDocuments(dataset) + .addDocuments(dataset); const { taskUid: task2 } = await client .index(index.uid) - .addDocuments(dataset) + .addDocuments(dataset); - const tasks = await client.waitForTasks([task1, task2]) - const [update1, update2] = tasks + const tasks = await client.waitForTasks([task1, task2]); + const [update1, update2] = tasks; - expect(update1).toHaveProperty('status', TaskStatus.TASK_SUCCEEDED) - expect(update2).toHaveProperty('status', TaskStatus.TASK_SUCCEEDED) - }) + expect(update1).toHaveProperty('status', TaskStatus.TASK_SUCCEEDED); + expect(update2).toHaveProperty('status', TaskStatus.TASK_SUCCEEDED); + }); test(`${permission} key: Tests wait for tasks in client with custom interval and timeout until done and resolved`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const { taskUid: task1 } = await client .index(index.uid) - .addDocuments(dataset) + .addDocuments(dataset); const { taskUid: task2 } = await client .index(index.uid) - .addDocuments(dataset) + .addDocuments(dataset); const tasks = await client.waitForTasks([task1, task2], { timeOutMs: 6000, intervalMs: 100, - }) - const [update1, update2] = tasks + }); + const [update1, update2] = tasks; - expect(update1).toHaveProperty('status', TaskStatus.TASK_SUCCEEDED) - expect(update2).toHaveProperty('status', TaskStatus.TASK_SUCCEEDED) - }) + expect(update1).toHaveProperty('status', TaskStatus.TASK_SUCCEEDED); + expect(update2).toHaveProperty('status', TaskStatus.TASK_SUCCEEDED); + }); test(`${permission} key: Tests wait for tasks in client with custom timeout and interval at 0 done and resolved`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const { taskUid: task1 } = await client .index(index.uid) - .addDocuments(dataset) + .addDocuments(dataset); const { taskUid: task2 } = await client .index(index.uid) - .addDocuments(dataset) + .addDocuments(dataset); const tasks = await client.waitForTasks([task1, task2], { timeOutMs: 6000, intervalMs: 0, - }) - const [update1, update2] = tasks + }); + const [update1, update2] = tasks; - expect(update1).toHaveProperty('status', TaskStatus.TASK_SUCCEEDED) - expect(update2).toHaveProperty('status', TaskStatus.TASK_SUCCEEDED) - }) + expect(update1).toHaveProperty('status', TaskStatus.TASK_SUCCEEDED); + expect(update2).toHaveProperty('status', TaskStatus.TASK_SUCCEEDED); + }); test(`${permission} key: Tests to wait for tasks in client with small timeout and raise an error`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const { taskUid: task1 } = await client .index(index.uid) - .addDocuments(dataset) + .addDocuments(dataset); const { taskUid: task2 } = await client .index(index.uid) - .addDocuments(dataset) + .addDocuments(dataset); await expect( - client.waitForTasks([task1, task2], { timeOutMs: 0 }) - ).rejects.toHaveProperty('name', 'MeiliSearchTimeOutError') - }) + client.waitForTasks([task1, task2], { timeOutMs: 0 }), + ).rejects.toHaveProperty('name', 'MeiliSearchTimeOutError'); + }); // Index Wait for tasks test(`${permission} key: Tests wait for tasks with indx instance`, async () => { - const client = await getClient(permission) + const client = await getClient(permission); const { taskUid: task1 } = await client .index(index.uid) - .addDocuments(dataset) + .addDocuments(dataset); const { taskUid: task2 } = await client .index(index.uid) - .addDocuments(dataset) + .addDocuments(dataset); - const tasks = await client.index(index.uid).waitForTasks([task1, task2]) - const [update1, update2] = tasks + const tasks = await client.index(index.uid).waitForTasks([task1, task2]); + const [update1, update2] = tasks; - expect(update1).toHaveProperty('status', TaskStatus.TASK_SUCCEEDED) - expect(update2).toHaveProperty('status', TaskStatus.TASK_SUCCEEDED) - }) - } -) + expect(update1).toHaveProperty('status', TaskStatus.TASK_SUCCEEDED); + expect(update2).toHaveProperty('status', TaskStatus.TASK_SUCCEEDED); + }); + }, +); From d3f490f917c1b117cdf4e78ab770628e1276ffbf Mon Sep 17 00:00:00 2001 From: "F. Levi" <55688616+flevi29@users.noreply.github.com> Date: Thu, 30 May 2024 11:37:52 +0300 Subject: [PATCH 9/9] Delete accidentally re-included file from merge --- src/errors/meilisearch-communication-error.ts | 47 ------------------- 1 file changed, 47 deletions(-) delete mode 100644 src/errors/meilisearch-communication-error.ts diff --git a/src/errors/meilisearch-communication-error.ts b/src/errors/meilisearch-communication-error.ts deleted file mode 100644 index 92fe8e865..000000000 --- a/src/errors/meilisearch-communication-error.ts +++ /dev/null @@ -1,47 +0,0 @@ -import { FetchError } from '../types'; -import { MeiliSearchError } from './meilisearch-error'; - -class MeiliSearchCommunicationError extends MeiliSearchError { - statusCode?: number; - errno?: string; - code?: string; - stack?: string; - - constructor( - message: string, - body: Response | FetchError, - url?: string, - stack?: string, - ) { - super(message); - - // Make errors comparison possible. ex: error instanceof MeiliSearchCommunicationError. - Object.setPrototypeOf(this, MeiliSearchCommunicationError.prototype); - - this.name = 'MeiliSearchCommunicationError'; - - if (body instanceof Response) { - this.message = body.statusText; - this.statusCode = body.status; - } - if (body instanceof Error) { - this.errno = body.errno; - this.code = body.code; - } - if (stack) { - this.stack = stack; - this.stack = this.stack?.replace(/(TypeError|FetchError)/, this.name); - this.stack = this.stack?.replace( - 'Failed to fetch', - `request to ${url} failed, reason: connect ECONNREFUSED`, - ); - this.stack = this.stack?.replace('Not Found', `Not Found: ${url}`); - } else { - if (Error.captureStackTrace) { - Error.captureStackTrace(this, MeiliSearchCommunicationError); - } - } - } -} - -export { MeiliSearchCommunicationError };