knowmax-quest-utils
Version:
Utilities for creating a Knowmax Quest client.
54 lines • 1.99 kB
JavaScript
/** 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.
*/
export 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 (!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;
}
};
/** 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.
*/
export 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;
};
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