UNPKG

knowmax-quest-utils

Version:

Utilities for creating a Knowmax Quest client.

59 lines 2.18 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.isQuoted = exports.sanitizeQuery = void 0; /** Sanitizes query by replacing unquoted colons (:) with a space since these would result in a field specification (and possibly error) when using them in Azure Cognitive Search. * Also makes sure string is always terminated with closing "-sign if one was opened but never closed. * @param query Query to sanitize. * @returns Sanitized query. */ const sanitizeQuery = (query) => { if (query) { // Make sure query is always terminated with closing "-sign if one was opened but never closed. if (countOccurence(query, '"') % 2 !== 0) { query = query + '"'; } // Escape "/" for compatibility with Azure Cognitive Search. query = query.replace(/\//g, '\\$&'); let colonindex = findNextColon(query); while (colonindex !== -1) { if (!(0, exports.isQuoted)(query, colonindex)) { query = `${query.substring(0, colonindex)} ${query.substring(colonindex + 1)}`; } colonindex = findNextColon(query, colonindex + 1); } return query.trim() === '' ? undefined : query.trim(); } else { return query; } }; exports.sanitizeQuery = sanitizeQuery; /** Returns true in case position in given string is within double quotes. * @param query String to check. * @param index Zero based position within query to check for double quotes. * @returns True if index is within double quotes. */ const isQuoted = (query, index) => { const indexleft = query.indexOf('"'); if (indexleft < index && indexleft !== -1) { const indexright = query.indexOf('"', index); if (indexright > index) { return true; } } return false; }; exports.isQuoted = isQuoted; const findNextColon = (query, index) => { return query.indexOf(':', index); }; const countOccurence = (query, char) => { let count = 0; for (let i = 0; i < query.length; i++) { if (query[i] === char) { count++; } } return count; }; //# sourceMappingURL=query.js.map