UNPKG

@unito/integration-sdk

Version:

Integration SDK

36 lines (35 loc) 1.69 kB
import { OperatorTypes } from '@unito/integration-api'; // The operators are ordered by their symbol length, in descending order. // This is necessary because the symbol of an operator can be // a subset of the symbol of another operator. // // For example, the symbol "=" (EQUAL) is a subset of the symbol "!=" (NOT_EQUAL). const ORDERED_OPERATORS = Object.values(OperatorTypes).sort((o1, o2) => o2.length - o1.length); function extractFilters(req, res, next) { const rawFilters = req.query.filter; res.locals.filters = []; if (typeof rawFilters === 'string') { for (const rawFilter of rawFilters.split(',')) { // Find the operator that appears earliest in the string. // When two operators start at the same index (e.g. ">=" and ">" both at position 5), // the longer one wins because ORDERED_OPERATORS is sorted longest-first. let bestIdx = -1; let bestOperator; for (const operator of ORDERED_OPERATORS) { const idx = rawFilter.indexOf(operator); if (idx !== -1 && (bestIdx === -1 || idx < bestIdx)) { bestIdx = idx; bestOperator = operator; } } if (bestIdx !== -1 && bestOperator) { const field = rawFilter.slice(0, bestIdx); const valuesRaw = rawFilter.slice(bestIdx + bestOperator.length); const values = valuesRaw ? valuesRaw.split('|').map(decodeURIComponent) : []; res.locals.filters.push({ field, operator: bestOperator, values }); } } } next(); } export default extractFilters;