All files / items filtering.js

95.89% Statements 140/146
85.71% Branches 126/147
100% Functions 25/25
98.29% Lines 115/117

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 4039x 9x         9x             9x 9x   9x           9x                         44x     16x 16x   2x     14x   13x 13x 13x 12x 11x 9x 10x   9x     9x                                     41x 15x 15x 15x   14x 14x   10x   10x   4x 1x   3x 3x 3x   3x 2x       9x                             29x   29x   29x 30x                 30x 30x 30x 1x 1x 1x       29x                             11x 3x 3x   8x                   13x 2x   11x                                   29x 14x 15x 15x   14x 1x     14x 13x                                                                         19x 8x 8x   8x 10x 10x     10x 2x                 2x 2x   8x 8x 9x 9x                 1211x 9x               10x 4x 10x     8x                         42x     19x 19x   2x     17x 15x 14x 1x     13x                       18x 22x 11x 3x   8x                                 54x 54x 51x 50x                                       13x   13x 5x 1209x 1209x 1209x       10x 8x   7x   7x 19x 19x 19x       9x                        
const { QueryCommand } = require('@aws-sdk/lib-dynamodb')
const { PLAIN_VALUE_LANG, getUniqueLanguageValues } = require('../utils/uniqueFieldValue')
const {
  needsEqualityIndex,
  getEqualityIndexValues,
  queryItemIdsForEqualityValue
} = require('../utils/equalityIndexValue')
const {
  needsTextSearchIndex,
  normalizeForSearch,
  MIN_QUERY_LENGTH,
  resolveContainsCandidates,
  matchesContains
} = require('../utils/textSearchIndex')
const { MAX_FILTER_INDEX_RESULTS } = require('../utils/constants')
 
const SINGLE_WORD_REGEX = /^[\p{L}\p{N}]+$/u
 
// Reserved `sort.fieldId` for the item's own `createdAt` — not a real entity
// field, always sortable regardless of entity size (backed by the
// createdAtIndex GSI or, once already materialized in memory, a plain
// string compare), unlike text-field sort which is threshold-gated.
const CREATED_AT_SORT_FIELD_ID = 'createdAt'
 
/**
 * Parses+validates the `filters` query param: a URL-encoded JSON array of
 * `{ fieldId, op?, values }`. `op` is `'eq'` (default, exact match) or
 * `'contains'` (substring search) — AND across array entries, OR within one
 * entry's `values`. Absent/empty input is valid (no filtering) and returns
 * `[]`; malformed input returns `null` so the caller can 400.
 *
 * @param {string | undefined} rawParam
 * @returns {Array<{fieldId: string, op?: 'eq'|'contains', values: Array<string|number|boolean>}> | null}
 */
function parseFilters(rawParam) {
  if (rawParam === undefined || rawParam === null || rawParam === '') return []
 
  let parsed
  try {
    parsed = JSON.parse(rawParam)
  } catch {
    return null
  }
 
  if (!Array.isArray(parsed)) return null
 
  for (const entry of parsed) {
    Iif (!entry || typeof entry !== 'object') return null
    if (typeof entry.fieldId !== 'string' || entry.fieldId === '') return null
    if (entry.op !== undefined && entry.op !== 'eq' && entry.op !== 'contains') return null
    if (!Array.isArray(entry.values) || entry.values.length === 0) return null
    const validValues = entry.values.every(
      (v) => typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean'
    )
    Iif (!validValues) return null
  }
 
  return parsed
}
 
/**
 * Every fieldId referenced by a parsed `filters` array must exist on the
 * entity and support the requested `op`: `eq` requires an automatic
 * equality-indexed scalar type, or a `unique` text/email field (which gets
 * exact lookup for free via its existing reservation row); `contains`
 * requires a text-search-indexed type (text/textarea/email), and every
 * search value must be a single word of at least MIN_QUERY_LENGTH
 * (normalized) characters — enforced uniformly regardless of entity size, so
 * a filter's validity doesn't silently change as an entity crosses the
 * small/large-entity threshold.
 *
 * @param {Array<{fieldId: string, op?: string, values: Array<string|number|boolean>}>} filters
 * @param {Array<{fieldId: string, type: string, unique?: boolean}>} entityFields
 * @returns {{ valid: true } | { valid: false, fieldId: string, code: string }}
 */
function validateFilterFields(filters, entityFields) {
  const fieldsById = new Map((entityFields || []).map((f) => [f.fieldId, f]))
  for (const filter of filters) {
    const field = fieldsById.get(filter.fieldId)
    if (!field) return { valid: false, fieldId: filter.fieldId, code: 'INVALID_FILTER_FIELD' }
 
    const op = filter.op || 'eq'
    if (op === 'eq') {
      const eligible =
        needsEqualityIndex(field) ||
        (field.unique === true && (field.type === 'text' || field.type === 'email'))
      if (!eligible) return { valid: false, fieldId: filter.fieldId, code: 'INVALID_FILTER_FIELD' }
    } else {
      if (!needsTextSearchIndex(field)) {
        return { valid: false, fieldId: filter.fieldId, code: 'INVALID_FILTER_FIELD' }
      }
      const invalidValue = filter.values.some((v) => {
        const normalized = normalizeForSearch(String(v))
        return normalized.length < MIN_QUERY_LENGTH || !SINGLE_WORD_REGEX.test(normalized)
      })
      if (invalidValue) {
        return { valid: false, fieldId: filter.fieldId, code: 'CONTAINS_QUERY_INVALID' }
      }
    }
  }
  return { valid: true }
}
 
/**
 * Small-entity path: fetches every item of the entity (paginated), for
 * in-memory filtering/sorting. Mirrors the pagination loop already used by
 * items/list.js's getItemCounts / entities/update.js's scanUniqueFieldValues.
 *
 * @param {import('@aws-sdk/lib-dynamodb').DynamoDBDocumentClient} docClient
 * @param {string} tableName
 * @param {string} entityId
 * @param {string} flowId
 * @returns {Promise<Array<Record<string, unknown>>>}
 */
async function fetchAllItems(docClient, tableName, entityId, flowId) {
  const items = []
  let ExclusiveStartKey
  const seenKeys = new Set()
 
  do {
    const result = await docClient.send(
      new QueryCommand({
        TableName: tableName,
        KeyConditionExpression: 'entityId = :entityId',
        FilterExpression: 'flowId = :flowId',
        ExpressionAttributeValues: { ':entityId': entityId, ':flowId': flowId },
        ExclusiveStartKey
      })
    )
    items.push(...(result.Items || []))
    ExclusiveStartKey = result.LastEvaluatedKey
    if (ExclusiveStartKey) {
      const keySignature = JSON.stringify(ExclusiveStartKey)
      Iif (seenKeys.has(keySignature)) break
      seenKeys.add(keySignature)
    }
  } while (ExclusiveStartKey)
 
  return items
}
 
/**
 * A multilingual (text/email/textarea) field's value can be stored under any
 * of the entity's enabled languages — since the `filters` param doesn't
 * specify which language a value belongs to, every enabled language is a
 * candidate `lang` to query. Non-multilingual types always use the
 * PLAIN_VALUE_LANG sentinel.
 *
 * @param {{ type: string }} field
 * @param {{ enabledLanguages?: string[] }} entity
 * @returns {string[]}
 */
function getCandidateLangs(field, entity) {
  if (field.type === 'text' || field.type === 'textarea' || field.type === 'email') {
    const langs = entity.enabledLanguages
    return Array.isArray(langs) && langs.length > 0 ? langs : [PLAIN_VALUE_LANG]
  }
  return [PLAIN_VALUE_LANG]
}
 
/**
 * The (language, value) pairs of a field's value on one item, for `eq`
 * in-memory matching — a `unique` text/email field is canonicalized the same
 * way its reservation row is (getUniqueLanguageValues); every other
 * equality-indexed scalar type uses getEqualityIndexValues.
 */
function getEqMatchValues(field, item) {
  if (field.unique === true && (field.type === 'text' || field.type === 'email')) {
    return getUniqueLanguageValues(field, item)
  }
  return getEqualityIndexValues(field, item)
}
 
/**
 * In-memory predicate: AND across `filters[]`, OR within one filter's
 * `values`. `eq` matches exactly (case-sensitive, unlike the lowercased `q`
 * search); `contains` does a normalized (accent/case-insensitive) substring
 * check with no index involved and no length/single-word restriction — a
 * full scan is happening anyway, so this path can be more permissive than
 * the large-entity indexed path.
 *
 * @param {Record<string, unknown>} item
 * @param {Array<{fieldId: string, op?: string, values: Array<string|number|boolean>}>} filters
 * @param {Array<{fieldId: string, type: string, unique?: boolean}>} entityFields
 * @param {{ enabledLanguages?: string[] }} entity
 * @returns {boolean}
 */
function matchesFilters(item, filters, entityFields, entity) {
  const fieldsById = new Map((entityFields || []).map((f) => [f.fieldId, f]))
  return filters.every((filter) => {
    const field = fieldsById.get(filter.fieldId)
    if (!field) return false
 
    if ((filter.op || 'eq') === 'contains') {
      return matchesContains(item, field, getCandidateLangs(field, entity || {}), filter.values)
    }
 
    const itemValues = new Set(getEqMatchValues(field, item).map((v) => v.value))
    return filter.values.some((v) => itemValues.has(String(v)))
  })
}
 
/**
 * Large-entity path: resolves `filters` to a bounded set of item ids via the
 * FieldValueIndexTable instead of scanning the entity's partition. Per
 * filter entry: `eq` unions queryItemIdsForEqualityValue over the filter's
 * `values` (OR) and every candidate language (this also transparently covers
 * a `unique` text/email field — it queries by the same `pk` a reservation
 * row lives under, and doesn't care about `sk`); `contains` delegates to
 * resolveContainsCandidates (which verifies internally). Results are
 * intersected across filter entries (AND), short-circuiting once the running
 * intersection is empty. Bounded by MAX_FILTER_INDEX_RESULTS; sets
 * `truncated: true` if any filter's candidate generation hit the cap (the
 * true result may be larger than what's returned).
 *
 * Note: filters are intersected in the order given, not smallest-first — a
 * true smallest-first ordering would need each filter's cardinality known
 * before querying any of them, which isn't available without querying.
 *
 * @param {import('@aws-sdk/lib-dynamodb').DynamoDBDocumentClient} docClient
 * @param {string} fieldValueIndexTableName
 * @param {string} itemsTableName
 * @param {string} entityId
 * @param {Array<{fieldId: string, op?: string, values: Array<string|number|boolean>}>} filters
 * @param {{ fields: Array<{fieldId: string, type: string}>, enabledLanguages?: string[] }} entity
 * @returns {Promise<{ itemIds: Set<string>, truncated: boolean }>}
 */
async function queryLargeEntityFilteredItemIds(
  docClient,
  fieldValueIndexTableName,
  itemsTableName,
  entityId,
  filters,
  entity
) {
  const fieldsById = new Map((entity.fields || []).map((f) => [f.fieldId, f]))
  let intersected = null
  let truncated = false
 
  for (const filter of filters) {
    const field = fieldsById.get(filter.fieldId)
    const langs = getCandidateLangs(field, entity)
    let union
 
    if ((filter.op || 'eq') === 'contains') {
      const result = await resolveContainsCandidates(docClient, {
        fieldValueIndexTableName,
        itemsTableName,
        entityId,
        field,
        langs,
        searchValues: filter.values,
        maxResults: MAX_FILTER_INDEX_RESULTS
      })
      union = result.itemIds
      Iif (result.truncated) truncated = true
    } else {
      union = new Set()
      outer: for (const rawValue of filter.values) {
        for (const lang of langs) {
          const ids = await queryItemIdsForEqualityValue(
            docClient,
            fieldValueIndexTableName,
            entityId,
            filter.fieldId,
            lang,
            String(rawValue),
            { maxResults: MAX_FILTER_INDEX_RESULTS }
          )
          for (const id of ids) union.add(id)
          Iif (union.size >= MAX_FILTER_INDEX_RESULTS) {
            truncated = true
            break outer
          }
        }
      }
    }
 
    intersected =
      intersected === null ? union : new Set([...intersected].filter((id) => union.has(id)))
    if (intersected.size === 0) break
  }
 
  return { itemIds: intersected || new Set(), truncated }
}
 
/**
 * Parses+validates the `sort` query param: a URL-encoded JSON object
 * `{ fieldId, direction? }`. `direction` defaults to `'asc'`. Absent/empty
 * input is valid (no sort requested) and returns `null`; malformed input
 * returns the `{ error: true }` sentinel so the caller can 400.
 *
 * @param {string | undefined} rawParam
 * @returns {{ fieldId: string, direction: 'asc' | 'desc' } | { error: true } | null}
 */
function parseSort(rawParam) {
  if (rawParam === undefined || rawParam === null || rawParam === '') return null
 
  let parsed
  try {
    parsed = JSON.parse(rawParam)
  } catch {
    return { error: true }
  }
 
  if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return { error: true }
  if (typeof parsed.fieldId !== 'string' || parsed.fieldId === '') return { error: true }
  if (parsed.direction !== undefined && parsed.direction !== 'asc' && parsed.direction !== 'desc') {
    return { error: true }
  }
 
  return { fieldId: parsed.fieldId, direction: parsed.direction || 'asc' }
}
 
/**
 * A `sort.fieldId` must reference an existing text-like field — the only
 * types sorting supports (see utils/textSearchIndex.js's TEXT_SEARCH_TYPES).
 *
 * @param {{ fieldId: string }} sort
 * @param {Array<{fieldId: string, type: string}>} entityFields
 * @returns {{ valid: true } | { valid: false, code: string }}
 */
function validateSortField(sort, entityFields) {
  if (sort.fieldId === CREATED_AT_SORT_FIELD_ID) return { valid: true }
  const field = (entityFields || []).find((f) => f.fieldId === sort.fieldId)
  if (!field || !needsTextSearchIndex(field)) {
    return { valid: false, code: 'INVALID_SORT_FIELD' }
  }
  return { valid: true }
}
 
/**
 * Extracts the string to sort a text-like field's value by: the entity's
 * default-language variant when the value is multilingual-map-shaped,
 * falling back to the plain (non-multilingual) value, then to whichever
 * language is present, then to '' for a missing value. Reuses
 * getUniqueLanguageValues, which is purely shape-based (not gated on
 * `field.unique`).
 *
 * @param {{ fieldId: string }} field
 * @param {Record<string, unknown>} item
 * @param {{ defaultLanguage?: string }} entity
 * @returns {string}
 */
function getSortValue(field, item, entity) {
  const pairs = getUniqueLanguageValues(field, item)
  if (pairs.length === 0) return ''
  const byLang = new Map(pairs.map((p) => [p.lang, p.value]))
  return byLang.get(entity?.defaultLanguage) ?? byLang.get(PLAIN_VALUE_LANG) ?? pairs[0].value
}
 
/**
 * Stably sorts `items` in place by a single field, ascending or descending.
 * `fieldId === CREATED_AT_SORT_FIELD_ID` is a special pseudo-field — every
 * item's own `createdAt` (an ISO-8601 string, always present, never
 * multilingual) compared directly, no entity-field lookup needed. Any other
 * `fieldId` is a real text-like entity field, compared via getSortValue with
 * locale-aware comparison (`entity.defaultLanguage`, base sensitivity so
 * case/accents don't affect ordering) — sort order is a stable per-entity
 * property rather than varying per viewer's own language preference.
 *
 * @param {Array<Record<string, unknown>>} items
 * @param {{ fieldId: string, direction: 'asc' | 'desc' }} sort
 * @param {Array<{fieldId: string, type: string}>} entityFields
 * @param {{ defaultLanguage?: string }} entity
 * @returns {Array<Record<string, unknown>>}
 */
function sortItems(items, sort, entityFields, entity) {
  const direction = sort.direction === 'desc' ? -1 : 1
 
  if (sort.fieldId === CREATED_AT_SORT_FIELD_ID) {
    return items.sort((a, b) => {
      const va = a?.createdAt || ''
      const vb = b?.createdAt || ''
      return direction * (va < vb ? -1 : va > vb ? 1 : 0)
    })
  }
 
  const field = (entityFields || []).find((f) => f.fieldId === sort.fieldId)
  if (!field) return items
 
  const locale = entity?.defaultLanguage || 'en'
 
  return items.sort((a, b) => {
    const va = getSortValue(field, a, entity)
    const vb = getSortValue(field, b, entity)
    return direction * va.localeCompare(vb, locale, { sensitivity: 'base', numeric: true })
  })
}
 
module.exports = {
  parseFilters,
  validateFilterFields,
  fetchAllItems,
  matchesFilters,
  queryLargeEntityFilteredItemIds,
  parseSort,
  validateSortField,
  getSortValue,
  sortItems,
  CREATED_AT_SORT_FIELD_ID
}