UNPKG

meilisearch

Version:

The Meilisearch JS client for Node.js and the browser.

1,325 lines (1,304 loc) 76 kB
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var crypto = require('crypto'); function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } var crypto__default = /*#__PURE__*/_interopDefaultLegacy(crypto); // Type definitions for meilisearch // Project: https://github.com/meilisearch/meilisearch-js // Definitions by: qdequele <quentin@meilisearch.com> <https://github.com/meilisearch> // Definitions: https://github.com/meilisearch/meilisearch-js // TypeScript Version: ^3.8.3 /* * SEARCH PARAMETERS */ const MatchingStrategies = { ALL: 'all', LAST: 'last', }; const ContentTypeEnum = { JSON: 'application/json', CSV: 'text/csv', NDJSON: 'application/x-ndjson', }; /****************************************************************************** Copyright (c) Microsoft Corporation. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ***************************************************************************** */ function __awaiter(thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); } class MeiliSearchCommunicationError extends Error { constructor(message, body, url, stack) { var _a, _b, _c; 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 = (_a = this.stack) === null || _a === void 0 ? void 0 : _a.replace(/(TypeError|FetchError)/, this.name); this.stack = (_b = this.stack) === null || _b === void 0 ? void 0 : _b.replace('Failed to fetch', `request to ${url} failed, reason: connect ECONNREFUSED`); this.stack = (_c = this.stack) === null || _c === void 0 ? void 0 : _c.replace('Not Found', `Not Found: ${url}`); } else { if (Error.captureStackTrace) { Error.captureStackTrace(this, MeiliSearchCommunicationError); } } } } const MeiliSearchApiError = class extends Error { constructor(error, status) { 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); } } }; function httpResponseErrorHandler(response) { return __awaiter(this, void 0, void 0, function* () { 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 = yield response.json(); } catch (e) { // 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, stack, url) { if (response.name !== 'MeiliSearchApiError') { throw new MeiliSearchCommunicationError(response.message, response, url, stack); } throw response; } class MeiliSearchError extends Error { constructor(message) { super(message); // Make errors comparison possible. ex: error instanceof MeiliSearchError. Object.setPrototypeOf(this, MeiliSearchError.prototype); this.name = 'MeiliSearchError'; if (Error.captureStackTrace) { Error.captureStackTrace(this, MeiliSearchError); } } } class MeiliSearchTimeOutError extends Error { constructor(message) { 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); } } } function versionErrorHintMessage(message, method) { return `${message}\nHint: It might not be working because maybe you're not up to date with the Meilisearch version that ${method} call requires.`; } /** Removes undefined entries from object */ function removeUndefinedFromObject(obj) { return Object.entries(obj).reduce((acc, curEntry) => { const [key, val] = curEntry; if (val !== undefined) acc[key] = val; return acc; }, {}); } function sleep(ms) { return __awaiter(this, void 0, void 0, function* () { return yield new Promise((resolve) => setTimeout(resolve, ms)); }); } function addProtocolIfNotPresent(host) { if (!(host.startsWith('https://') || host.startsWith('http://'))) { return `http://${host}`; } return host; } function addTrailingSlash(url) { if (!url.endsWith('/')) { url += '/'; } return url; } function validateUuid4(uuid) { 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); } const PACKAGE_VERSION = '0.35.0'; function toQueryParams(parameters) { const params = Object.keys(parameters); const queryParams = params.reduce((acc, key) => { const value = parameters[key]; if (value === undefined) { return acc; } else if (Array.isArray(value)) { return Object.assign(Object.assign({}, acc), { [key]: value.join(',') }); } else if (value instanceof Date) { return Object.assign(Object.assign({}, acc), { [key]: value.toISOString() }); } return Object.assign(Object.assign({}, acc), { [key]: value }); }, {}); return queryParams; } function constructHostURL(host) { try { host = addProtocolIfNotPresent(host); host = addTrailingSlash(host); return host; } catch (e) { throw new MeiliSearchError('The provided host is not valid.'); } } function cloneAndParseHeaders(headers) { if (Array.isArray(headers)) { return headers.reduce((acc, headerPair) => { acc[headerPair[0]] = headerPair[1]; return acc; }, {}); } else if ('has' in headers) { const clonedHeaders = {}; headers.forEach((value, key) => (clonedHeaders[key] = value)); return clonedHeaders; } else { return Object.assign({}, headers); } } function createHeaders(config) { var _a, _b; const agentHeader = 'X-Meilisearch-Client'; const packageAgent = `Meilisearch JavaScript (v${PACKAGE_VERSION})`; const contentType = 'Content-Type'; const authorization = 'Authorization'; const headers = cloneAndParseHeaders((_b = (_a = config.requestConfig) === null || _a === void 0 ? void 0 : _a.headers) !== null && _b !== void 0 ? _b : {}); // do not override if user provided the header if (config.apiKey && !headers[authorization]) { headers[authorization] = `Bearer ${config.apiKey}`; } if (!headers[contentType]) { 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); 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`); } else { headers[agentHeader] = packageAgent; } return headers; } class HttpRequests { constructor(config) { this.headers = createHeaders(config); this.requestConfig = config.requestConfig; this.httpClient = config.httpClient; try { const host = constructHostURL(config.host); this.url = new URL(host); } catch (e) { throw new MeiliSearchError('The provided host is not valid.'); } } request({ method, url, params, body, config = {}, }) { var _a; return __awaiter(this, void 0, void 0, function* () { if (typeof fetch === 'undefined') { require('cross-fetch/polyfill'); } const constructURL = new URL(url, this.url); if (params) { const queryParams = new URLSearchParams(); Object.keys(params) .filter((x) => params[x] !== null) .map((x) => queryParams.set(x, params[x])); constructURL.search = queryParams.toString(); } // in case a custom content-type is provided // do not stringify body if (!((_a = config.headers) === null || _a === void 0 ? void 0 : _a['Content-Type'])) { body = JSON.stringify(body); } const headers = Object.assign(Object.assign({}, this.headers), config.headers); try { const fetchFn = this.httpClient ? this.httpClient : fetch; const result = fetchFn(constructURL.toString(), Object.assign(Object.assign(Object.assign({}, config), this.requestConfig), { method, body, headers })); // 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 yield result; } const response = yield result.then((res) => httpResponseErrorHandler(res)); const parsedBody = yield response.json().catch(() => undefined); return parsedBody; } catch (e) { const stack = e.stack; httpErrorHandler(e, stack, constructURL.toString()); } }); } get(url, params, config) { return __awaiter(this, void 0, void 0, function* () { return yield this.request({ method: 'GET', url, params, config, }); }); } post(url, data, params, config) { return __awaiter(this, void 0, void 0, function* () { return yield this.request({ method: 'POST', url, body: data, params, config, }); }); } put(url, data, params, config) { return __awaiter(this, void 0, void 0, function* () { return yield this.request({ method: 'PUT', url, body: data, params, config, }); }); } patch(url, data, params, config) { return __awaiter(this, void 0, void 0, function* () { return yield this.request({ method: 'PATCH', url, body: data, params, config, }); }); } delete(url, data, params, config) { return __awaiter(this, void 0, void 0, function* () { return yield this.request({ method: 'DELETE', url, body: data, params, config, }); }); } } class EnqueuedTask { constructor(task) { this.taskUid = task.taskUid; this.indexUid = task.indexUid; this.status = task.status; this.type = task.type; this.enqueuedAt = new Date(task.enqueuedAt); } } class Task { constructor(task) { 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 { constructor(config) { this.httpRequest = new HttpRequests(config); } /** * Get one task * * @param uid - Unique identifier of the task * @returns */ getTask(uid) { return __awaiter(this, void 0, void 0, function* () { const url = `tasks/${uid}`; const taskItem = yield this.httpRequest.get(url); return new Task(taskItem); }); } /** * Get tasks * * @param parameters - Parameters to browse the tasks * @returns Promise containing all tasks */ getTasks(parameters = {}) { return __awaiter(this, void 0, void 0, function* () { const url = `tasks`; const tasks = yield this.httpRequest.get(url, toQueryParams(parameters)); return Object.assign(Object.assign({}, tasks), { results: tasks.results.map((task) => new Task(task)) }); }); } /** * Wait for a task to be processed. * * @param taskUid - Task identifier * @param options - Additional configuration options * @returns Promise returning a task after it has been processed */ waitForTask(taskUid, { timeOutMs = 5000, intervalMs = 50 } = {}) { return __awaiter(this, void 0, void 0, function* () { const startingTime = Date.now(); while (Date.now() - startingTime < timeOutMs) { const response = yield this.getTask(taskUid); if (!["enqueued" /* TaskStatus.TASK_ENQUEUED */, "processing" /* TaskStatus.TASK_PROCESSING */].includes(response.status)) return response; yield sleep(intervalMs); } throw new MeiliSearchTimeOutError(`timeout of ${timeOutMs}ms has exceeded on process ${taskUid} when waiting a task to be resolved.`); }); } /** * Waits for multiple tasks to be processed * * @param taskUids - Tasks identifier list * @param options - Wait options * @returns Promise returning a list of tasks after they have been processed */ waitForTasks(taskUids, { timeOutMs = 5000, intervalMs = 50 } = {}) { return __awaiter(this, void 0, void 0, function* () { const tasks = []; for (const taskUid of taskUids) { const task = yield this.waitForTask(taskUid, { timeOutMs, intervalMs, }); tasks.push(task); } return tasks; }); } /** * Cancel a list of enqueued or processing tasks. * * @param parameters - Parameters to filter the tasks. * @returns Promise containing an EnqueuedTask */ cancelTasks(parameters = {}) { return __awaiter(this, void 0, void 0, function* () { const url = `tasks/cancel`; const task = yield this.httpRequest.post(url, {}, toQueryParams(parameters)); return new EnqueuedTask(task); }); } /** * Delete a list tasks. * * @param parameters - Parameters to filter the tasks. * @returns Promise containing an EnqueuedTask */ deleteTasks(parameters = {}) { return __awaiter(this, void 0, void 0, function* () { const url = `tasks`; const task = yield this.httpRequest.delete(url, {}, toQueryParams(parameters)); return new EnqueuedTask(task); }); } } /* * Bundle: MeiliSearch / Indexes * Project: MeiliSearch - Javascript API * Author: Quentin de Quelen <quentin@meilisearch.com> * Copyright: 2019, MeiliSearch */ class Index { /** * @param config - Request configuration options * @param uid - UID of the index * @param primaryKey - Primary Key of the index */ constructor(config, uid, primaryKey) { this.uid = uid; this.primaryKey = primaryKey; this.httpRequest = new HttpRequests(config); this.tasks = new TaskClient(config); } /// /// SEARCH /// /** * Search for documents into an index * * @param query - Query string * @param options - Search options * @param config - Additional request configuration options * @returns Promise containing the search response */ search(query, options, config) { return __awaiter(this, void 0, void 0, function* () { const url = `indexes/${this.uid}/search`; return yield this.httpRequest.post(url, removeUndefinedFromObject(Object.assign({ q: query }, options)), undefined, config); }); } /** * Search for documents into an index using the GET method * * @param query - Query string * @param options - Search options * @param config - Additional request configuration options * @returns Promise containing the search response */ searchGet(query, options, config) { var _a, _b, _c, _d, _e, _f, _g; return __awaiter(this, void 0, void 0, function* () { const url = `indexes/${this.uid}/search`; const parseFilter = (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; }; const getParams = Object.assign(Object.assign({ q: query }, options), { filter: parseFilter(options === null || options === void 0 ? void 0 : options.filter), sort: (_a = options === null || options === void 0 ? void 0 : options.sort) === null || _a === void 0 ? void 0 : _a.join(','), facets: (_b = options === null || options === void 0 ? void 0 : options.facets) === null || _b === void 0 ? void 0 : _b.join(','), attributesToRetrieve: (_c = options === null || options === void 0 ? void 0 : options.attributesToRetrieve) === null || _c === void 0 ? void 0 : _c.join(','), attributesToCrop: (_d = options === null || options === void 0 ? void 0 : options.attributesToCrop) === null || _d === void 0 ? void 0 : _d.join(','), attributesToHighlight: (_e = options === null || options === void 0 ? void 0 : options.attributesToHighlight) === null || _e === void 0 ? void 0 : _e.join(','), vector: (_f = options === null || options === void 0 ? void 0 : options.vector) === null || _f === void 0 ? void 0 : _f.join(','), attributesToSearchOn: (_g = options === null || options === void 0 ? void 0 : options.attributesToSearchOn) === null || _g === void 0 ? void 0 : _g.join(',') }); return yield this.httpRequest.get(url, removeUndefinedFromObject(getParams), config); }); } /** * Search for facet values * * @param params - Parameters used to search on the facets * @param config - Additional request configuration options * @returns Promise containing the search response */ searchForFacetValues(params, config) { return __awaiter(this, void 0, void 0, function* () { const url = `indexes/${this.uid}/facet-search`; return yield this.httpRequest.post(url, removeUndefinedFromObject(params), undefined, config); }); } /// /// INDEX /// /** * Get index information. * * @returns Promise containing index information */ getRawInfo() { return __awaiter(this, void 0, void 0, function* () { const url = `indexes/${this.uid}`; const res = yield this.httpRequest.get(url); this.primaryKey = res.primaryKey; this.updatedAt = new Date(res.updatedAt); this.createdAt = new Date(res.createdAt); return res; }); } /** * Fetch and update Index information. * * @returns Promise to the current Index object with updated information */ fetchInfo() { return __awaiter(this, void 0, void 0, function* () { yield this.getRawInfo(); return this; }); } /** * Get Primary Key. * * @returns Promise containing the Primary Key of the index */ fetchPrimaryKey() { return __awaiter(this, void 0, void 0, function* () { this.primaryKey = (yield this.getRawInfo()).primaryKey; return this.primaryKey; }); } /** * Create an index. * * @param uid - Unique identifier of the Index * @param options - Index options * @param config - Request configuration options * @returns Newly created Index object */ static create(uid, options = {}, config) { return __awaiter(this, void 0, void 0, function* () { const url = `indexes`; const req = new HttpRequests(config); const task = yield req.post(url, Object.assign(Object.assign({}, options), { uid })); return new EnqueuedTask(task); }); } /** * Update an index. * * @param data - Data to update * @returns Promise to the current Index object with updated information */ update(data) { return __awaiter(this, void 0, void 0, function* () { const url = `indexes/${this.uid}`; const task = yield this.httpRequest.patch(url, data); task.enqueuedAt = new Date(task.enqueuedAt); return task; }); } /** * Delete an index. * * @returns Promise which resolves when index is deleted successfully */ delete() { return __awaiter(this, void 0, void 0, function* () { const url = `indexes/${this.uid}`; const task = yield this.httpRequest.delete(url); return new EnqueuedTask(task); }); } /// /// TASKS /// /** * Get the list of all the tasks of the index. * * @param parameters - Parameters to browse the tasks * @returns Promise containing all tasks */ getTasks(parameters = {}) { return __awaiter(this, void 0, void 0, function* () { return yield this.tasks.getTasks(Object.assign(Object.assign({}, parameters), { indexUids: [this.uid] })); }); } /** * Get one task of the index. * * @param taskUid - Task identifier * @returns Promise containing a task */ getTask(taskUid) { return __awaiter(this, void 0, void 0, function* () { return yield this.tasks.getTask(taskUid); }); } /** * Wait for multiple tasks to be processed. * * @param taskUids - Tasks identifier * @param waitOptions - Options on timeout and interval * @returns Promise containing an array of tasks */ waitForTasks(taskUids, { timeOutMs = 5000, intervalMs = 50 } = {}) { return __awaiter(this, void 0, void 0, function* () { return yield this.tasks.waitForTasks(taskUids, { timeOutMs, intervalMs, }); }); } /** * Wait for a task to be processed. * * @param taskUid - Task identifier * @param waitOptions - Options on timeout and interval * @returns Promise containing an array of tasks */ waitForTask(taskUid, { timeOutMs = 5000, intervalMs = 50 } = {}) { return __awaiter(this, void 0, void 0, function* () { return yield this.tasks.waitForTask(taskUid, { timeOutMs, intervalMs, }); }); } /// /// STATS /// /** * Get stats of an index * * @returns Promise containing object with stats of the index */ getStats() { return __awaiter(this, void 0, void 0, function* () { const url = `indexes/${this.uid}/stats`; return yield this.httpRequest.get(url); }); } /// /// DOCUMENTS /// /** * Get documents of an index. * * @param parameters - Parameters to browse the documents. Parameters can * contain the `filter` field only available in Meilisearch v1.2 and newer * @returns Promise containing the returned documents */ getDocuments(parameters = {}) { var _a; return __awaiter(this, void 0, void 0, function* () { parameters = removeUndefinedFromObject(parameters); // In case `filter` is provided, use `POST /documents/fetch` if (parameters.filter !== undefined) { try { const url = `indexes/${this.uid}/documents/fetch`; return yield this.httpRequest.post(url, parameters); } catch (e) { if (e instanceof MeiliSearchCommunicationError) { e.message = versionErrorHintMessage(e.message, 'getDocuments'); } else if (e instanceof MeiliSearchApiError) { e.message = versionErrorHintMessage(e.message, 'getDocuments'); } throw e; } // Else use `GET /documents` method } else { const url = `indexes/${this.uid}/documents`; // Transform fields to query parameter string format const fields = Array.isArray(parameters === null || parameters === void 0 ? void 0 : parameters.fields) ? { fields: (_a = parameters === null || parameters === void 0 ? void 0 : parameters.fields) === null || _a === void 0 ? void 0 : _a.join(',') } : {}; return yield this.httpRequest.get(url, Object.assign(Object.assign({}, parameters), fields)); } }); } /** * Get one document * * @param documentId - Document ID * @param parameters - Parameters applied on a document * @returns Promise containing Document response */ getDocument(documentId, parameters) { return __awaiter(this, void 0, void 0, function* () { const url = `indexes/${this.uid}/documents/${documentId}`; const fields = (() => { var _a; if (Array.isArray(parameters === null || parameters === void 0 ? void 0 : parameters.fields)) { return (_a = parameters === null || parameters === void 0 ? void 0 : parameters.fields) === null || _a === void 0 ? void 0 : _a.join(','); } return undefined; })(); return yield this.httpRequest.get(url, removeUndefinedFromObject(Object.assign(Object.assign({}, parameters), { fields }))); }); } /** * Add or replace multiples documents to an index * * @param documents - Array of Document objects to add/replace * @param options - Options on document addition * @returns Promise containing an EnqueuedTask */ addDocuments(documents, options) { return __awaiter(this, void 0, void 0, function* () { const url = `indexes/${this.uid}/documents`; const task = yield this.httpRequest.post(url, documents, options); return new EnqueuedTask(task); }); } /** * Add or replace multiples documents in a string format to an index. It only * supports csv, ndjson and json formats. * * @param documents - Documents provided in a string to add/replace * @param contentType - Content type of your document: * 'text/csv'|'application/x-ndjson'|'application/json' * @param options - Options on document addition * @returns Promise containing an EnqueuedTask */ addDocumentsFromString(documents, contentType, queryParams) { return __awaiter(this, void 0, void 0, function* () { const url = `indexes/${this.uid}/documents`; const task = yield this.httpRequest.post(url, documents, queryParams, { headers: { 'Content-Type': contentType, }, }); return new EnqueuedTask(task); }); } /** * Add or replace multiples documents to an index in batches * * @param documents - Array of Document objects to add/replace * @param batchSize - Size of the batch * @param options - Options on document addition * @returns Promise containing array of enqueued task objects for each batch */ addDocumentsInBatches(documents, batchSize = 1000, options) { return __awaiter(this, void 0, void 0, function* () { const updates = []; for (let i = 0; i < documents.length; i += batchSize) { updates.push(yield this.addDocuments(documents.slice(i, i + batchSize), options)); } return updates; }); } /** * Add or update multiples documents to an index * * @param documents - Array of Document objects to add/update * @param options - Options on document update * @returns Promise containing an EnqueuedTask */ updateDocuments(documents, options) { return __awaiter(this, void 0, void 0, function* () { const url = `indexes/${this.uid}/documents`; const task = yield this.httpRequest.put(url, documents, options); return new EnqueuedTask(task); }); } /** * Add or update multiples documents to an index in batches * * @param documents - Array of Document objects to add/update * @param batchSize - Size of the batch * @param options - Options on document update * @returns Promise containing array of enqueued task objects for each batch */ updateDocumentsInBatches(documents, batchSize = 1000, options) { return __awaiter(this, void 0, void 0, function* () { const updates = []; for (let i = 0; i < documents.length; i += batchSize) { updates.push(yield this.updateDocuments(documents.slice(i, i + batchSize), options)); } return updates; }); } /** * Add or update multiples documents in a string format to an index. It only * supports csv, ndjson and json formats. * * @param documents - Documents provided in a string to add/update * @param contentType - Content type of your document: * 'text/csv'|'application/x-ndjson'|'application/json' * @param queryParams - Options on raw document addition * @returns Promise containing an EnqueuedTask */ updateDocumentsFromString(documents, contentType, queryParams) { return __awaiter(this, void 0, void 0, function* () { const url = `indexes/${this.uid}/documents`; const task = yield this.httpRequest.put(url, documents, queryParams, { headers: { 'Content-Type': contentType, }, }); return new EnqueuedTask(task); }); } /** * Delete one document * * @param documentId - Id of Document to delete * @returns Promise containing an EnqueuedTask */ deleteDocument(documentId) { return __awaiter(this, void 0, void 0, function* () { const url = `indexes/${this.uid}/documents/${documentId}`; const task = yield this.httpRequest.delete(url); task.enqueuedAt = new Date(task.enqueuedAt); return task; }); } /** * Delete multiples documents of an index. * * @param params - Params value can be: * * - DocumentsDeletionQuery: An object containing the parameters to customize * your document deletion. Only available in Meilisearch v1.2 and newer * - DocumentsIds: An array of document ids to delete * * @returns Promise containing an EnqueuedTask */ deleteDocuments(params) { return __awaiter(this, void 0, void 0, function* () { // If params is of type DocumentsDeletionQuery const isDocumentsDeletionQuery = !Array.isArray(params) && typeof params === 'object'; const endpoint = isDocumentsDeletionQuery ? 'documents/delete' : 'documents/delete-batch'; const url = `indexes/${this.uid}/${endpoint}`; try { const task = yield this.httpRequest.post(url, params); return new EnqueuedTask(task); } catch (e) { if (e instanceof MeiliSearchCommunicationError && isDocumentsDeletionQuery) { e.message = versionErrorHintMessage(e.message, 'deleteDocuments'); } else if (e instanceof MeiliSearchApiError) { e.message = versionErrorHintMessage(e.message, 'deleteDocuments'); } throw e; } }); } /** * Delete all documents of an index * * @returns Promise containing an EnqueuedTask */ deleteAllDocuments() { return __awaiter(this, void 0, void 0, function* () { const url = `indexes/${this.uid}/documents`; const task = yield this.httpRequest.delete(url); task.enqueuedAt = new Date(task.enqueuedAt); return task; }); } /// /// SETTINGS /// /** * Retrieve all settings * * @returns Promise containing Settings object */ getSettings() { return __awaiter(this, void 0, void 0, function* () { const url = `indexes/${this.uid}/settings`; return yield this.httpRequest.get(url); }); } /** * Update all settings Any parameters not provided will be left unchanged. * * @param settings - Object containing parameters with their updated values * @returns Promise containing an EnqueuedTask */ updateSettings(settings) { return __awaiter(this, void 0, void 0, function* () { const url = `indexes/${this.uid}/settings`; const task = yield this.httpRequest.patch(url, settings); task.enqueued = new Date(task.enqueuedAt); return task; }); } /** * Reset settings. * * @returns Promise containing an EnqueuedTask */ resetSettings() { return __awaiter(this, void 0, void 0, function* () { const url = `indexes/${this.uid}/settings`; const task = yield this.httpRequest.delete(url); task.enqueuedAt = new Date(task.enqueuedAt); return task; }); } /// /// PAGINATION SETTINGS /// /** * Get the pagination settings. * * @returns Promise containing object of pagination settings */ getPagination() { return __awaiter(this, void 0, void 0, function* () { const url = `indexes/${this.uid}/settings/pagination`; return yield this.httpRequest.get(url); }); } /** * Update the pagination settings. * * @param pagination - Pagination object * @returns Promise containing an EnqueuedTask */ updatePagination(pagination) { return __awaiter(this, void 0, void 0, function* () { const url = `indexes/${this.uid}/settings/pagination`; const task = yield this.httpRequest.patch(url, pagination); return new EnqueuedTask(task); }); } /** * Reset the pagination settings. * * @returns Promise containing an EnqueuedTask */ resetPagination() { return __awaiter(this, void 0, void 0, function* () { const url = `indexes/${this.uid}/settings/pagination`; const task = yield this.httpRequest.delete(url); return new EnqueuedTask(task); }); } /// /// SYNONYMS /// /** * Get the list of all synonyms * * @returns Promise containing object of synonym mappings */ getSynonyms() { return __awaiter(this, void 0, void 0, function* () { const url = `indexes/${this.uid}/settings/synonyms`; return yield this.httpRequest.get(url); }); } /** * Update the list of synonyms. Overwrite the old list. * * @param synonyms - Mapping of synonyms with their associated words * @returns Promise containing an EnqueuedTask */ updateSynonyms(synonyms) { return __awaiter(this, void 0, void 0, function* () { const url = `indexes/${this.uid}/settings/synonyms`; const task = yield this.httpRequest.put(url, synonyms); return new EnqueuedTask(task); }); } /** * Reset the synonym list to be empty again * * @returns Promise containing an EnqueuedTask */ resetSynonyms() { return __awaiter(this, void 0, void 0, function* () { const url = `indexes/${this.uid}/settings/synonyms`; const task = yield this.httpRequest.delete(url); task.enqueuedAt = new Date(task.enqueuedAt); return task; }); } /// /// STOP WORDS /// /** * Get the list of all stop-words * * @returns Promise containing array of stop-words */ getStopWords() { return __awaiter(this, void 0, void 0, function* () { const url = `indexes/${this.uid}/settings/stop-words`; return yield this.httpRequest.get(url); }); } /** * Update the list of stop-words. Overwrite the old list. * * @param stopWords - Array of strings that contains the stop-words. * @returns Promise containing an EnqueuedTask */ updateStopWords(stopWords) { return __awaiter(this, void 0, void 0, function* () { const url = `indexes/${this.uid}/settings/stop-words`; const task = yield this.httpRequest.put(url, stopWords); return new EnqueuedTask(task); }); } /** * Reset the stop-words list to be empty again * * @returns Promise containing an EnqueuedTask */ resetStopWords() { return __awaiter(this, void 0, void 0, function* () { const url = `indexes/${this.uid}/settings/stop-words`; const task = yield this.httpRequest.delete(url); task.enqueuedAt = new Date(task.enqueuedAt); return task; }); } /// /// RANKING RULES /// /** * Get the list of all ranking-rules * * @returns Promise containing array of ranking-rules */ getRankingRules() { return __awaiter(this, void 0, void 0, function* () { const url = `indexes/${this.uid}/settings/ranking-rules`; return yield this.httpRequest.get(url); }); } /** * Update the list of ranking-rules. Overwrite the old list. * * @param rankingRules - Array that contain ranking rules sorted by order of * importance. * @returns Promise containing an EnqueuedTask */ updateRankingRules(rankingRules) { return __awaiter(this, void 0, void 0, function* () { const url = `indexes/${this.uid}/settings/ranking-rules`; const task = yield this.httpRequest.put(url, rankingRules); return new EnqueuedTask(task); }); } /** * Reset the ranking rules list to its default value * * @returns Promise containing an EnqueuedTask */ resetRankingRules() { return __awaiter(this, void 0, void 0, function* () { const url = `indexes/${this.uid}/settings/ranking-rules`; const task = yield this.httpRequest.delete(url); task.enqueuedAt = new Date(task.enqueuedAt); return task; }); } /// /// DISTINCT ATTRIBUTE /// /** * Get the distinct-attribute * * @returns Promise containing the distinct-attribute of the index */ getDistinctAttribute() { return __awaiter(this, void 0, void 0, function* () { const url = `indexes/${this.uid}/settings/distinct-attribute`; return yield this.httpRequest.get(url); }); } /** * Update the distinct-attribute. * * @param distinctAttribute - Field name of the distinct-attribute * @returns Promise containing an EnqueuedTask */ updateDistinctAttribute(distinctAttribute) { return __awaiter(this, void 0, void 0, function* () { const url = `indexes/${this.uid}/settings/distinct-attribute`; const task = yield this.httpRequest.put(url, distinctAttribute); return new EnqueuedTask(task); }); } /** * Reset the distinct-attribute. * * @returns Promise containing an EnqueuedTask */ resetDistinctAttribute() { return __awaiter(this, void 0, void 0, function* () { const url = `indexes/${this.uid}/settings/distinct-attribute`; const task = yield this.httpRequest.delete(url); task.enqueuedAt = new Date(task.enqueuedAt); return task; }); } /// /// FILTERABLE ATTRIBUTES /// /** * Get the filterable-attributes * * @returns Promise containing an array of filterable-attributes */ getFilterableAttributes() { return __awaiter(this, void 0, void 0, function* () { const url = `indexes/${this.uid}/settings/filterable-attributes`; return yield this.httpRequest.get(url); }); } /** * Update the filterable-attributes. * * @param filterableAttributes - Array of strings containing the attributes * that can be used as filters at query time * @returns Promise containing an EnqueuedTask */ updateFilterableAttributes(filterableAttributes) { return __awaiter(this, void 0, void 0, function* () { const url = `indexes/${this.uid}/settings/filterable-attributes`; const task = yield this.httpRequest.put(url, filterableAttributes); return new EnqueuedTask(task); }); } /** * Reset the filterable-attributes. * * @returns Promise containing an EnqueuedTask */ resetFilterableAttributes() { return __awaiter(this, void 0, void 0, function* () { const url = `indexes/${this.uid}/settings/filterable-attributes`; const task = yield this.httpRequest.delete(url); task.enqueuedAt = new Date(task.enqueuedAt); return task; }); } /// /// SORTABLE ATTRIBUTES /// /** * Get the sortable-attributes * * @returns Promise containing array of sortable-attributes */ getSortableAttributes() { return __awaiter(this, void 0, void 0, function* () { const url = `indexes/${this.uid}/settings/sortable-attributes`; return yield this.httpRequest.get(url); }); } /** * Update the sortable-attributes. * * @param sortableAttributes - Array of strings containing the attributes that * can be used to sort search results at query time * @returns Promise containing an EnqueuedTask */ updateSortableAttributes(sortableAttributes) { return __awaiter(this, void 0, void 0, function* () { const url = `indexes/${this.uid}/settings/sortable-attributes`; const task = yield this.httpRequest.put(url, sortableAttributes); return new EnqueuedTask(task); }); } /** * Reset the sortable-attributes. * * @returns Promise containing an EnqueuedTask */ resetSortableAttributes() { return __awaiter(this, void 0, void 0, function* () { const url = `indexes/${this.uid}/settings/sortable-attributes`; const task = yield this.httpRequest.delete(url); task.enqueuedAt = new Date(task.enqueuedAt); return task; }); } /// /// SEARCHABLE ATTRIBUTE /// /** * Get the searchable-attributes * * @returns Promise containing array of searchable-attributes */ getSearchableAttributes() { return __awaiter(this, void 0, void 0, function* () { const url = `indexes/${this.uid}/settings/searchable-attributes`; return yield this.httpRequest.get(url); }); } /** * Update the searchable-attributes. * * @param searchableAttributes - Array of strings that contains searchable * attributes sorted by order of importance(most to least important) * @returns Promise containing an EnqueuedTask */ updateSearchableAttributes(searchableAttributes) { return __awaiter(this, void 0, void 0, function* () { const url = `indexes/${this.uid}/settings/searchable-attributes`; const task = yield this.httpRequest.put(url, searchableAttributes); return new EnqueuedTask(task); }); } /** * Reset the searchable-attributes. * * @returns Promise containing an EnqueuedTask */ resetSearchableAttributes() { return __awaiter(this, void 0, void 0, function* () { const url = `indexes/${this.uid}/settings/searchable-attributes`; const task = yield this.httpRequest.delete(url); task.enqueuedAt = new Date(task.enqueuedAt); return task; }); } /// /// DISPLAYED ATTRIBUTE /// /** * Get the displayed-attributes * * @returns Promise containing array of displayed-attributes */ getDisplayedAttributes() { return __awaiter(this, void 0, void 0, function* () { const url = `indexes/${this.uid}/settings/displayed-attributes`; return yield this.httpRequest.get(url); }); } /** * Update the displayed-attributes. * * @param displayedAttributes - Array of strings that contains attributes of * an index to display * @returns Promise containing an EnqueuedTask */ updateDisplayedAttributes(displayedAttributes) { return __awaiter(this, void 0, void