Skip to content

simplifyQuery

Category
Export size
min 1.65 kB · gzip 0.74 kB
See also

Normalizes the logical structure of a Feathers query without changing what it matches: empty $and/$or are dropped, duplicate branches removed, nested same-operator branches hoisted ($and-in-$and, pure $or-in-$or), and branches merged up into the parent where it is safe — all of an $and when no key collides, a single-branch $or. Runs recursively. Inputs are not mutated; a query with nothing to simplify is returned unchanged.

ts
  import {  } from 'feathers-utils/utils';

Example

ts
import { simplifyQuery } from 'feathers-utils/utils'

// non-colliding $and branches (here also a hoisted nested $and) merge up
simplifyQuery({ $and: [{ id: 1 }, { $and: [{ status: 'a' }] }] })
// => { id: 1, status: 'a' }

simplifyQuery({ $or: [{ id: 1 }] })
// => { id: 1 }

// a colliding key keeps the $and intact
simplifyQuery({ $and: [{ price: { $gt: 1 } }, { price: { $lt: 9 } }] })
// => { $and: [{ price: { $gt: 1 } }, { price: { $lt: 9 } }] }

Type declaration

Show Type Declarations
ts
export interface SimplifyQueryOptions {
  /**
   * Dissolve a top-level single-branch `$and` by merging its branch up into the
   * query (only when no key would collide). Nested levels are always dissolved.
   * Default `true`.
   */
  replaceAnd?: boolean
  /**
   * Dissolve a top-level single-branch `$or` by merging its branch up into the
   * query (only when no key would collide). Nested levels are always dissolved.
   * Default `true`.
   */
  replaceOr?: boolean
}
/**
 * Normalizes the logical structure of a Feathers query without changing what it
 * matches: empty `$and`/`$or` are dropped, duplicate branches removed, nested
 * same-operator branches hoisted (`$and`-in-`$and`, pure `$or`-in-`$or`), and
 * branches merged up into the parent where it is safe — all of an `$and` when no
 * key collides, a single-branch `$or`. Runs recursively. Inputs are not mutated;
 * a query with nothing to simplify is returned unchanged.
 *
 * @param query the query to simplify (a falsy query is returned as-is)
 * @param options
 * @returns the simplified query
 *
 * @example
 * ```ts
 *
 *
 * // non-colliding $and branches (here also a hoisted nested $and) merge up
 * simplifyQuery({ $and: [{ id: 1 }, { $and: [{ status: 'a' }] }] })
 * // => { id: 1, status: 'a' }
 *
 * simplifyQuery({ $or: [{ id: 1 }] })
 * // => { id: 1 }
 *
 * // a colliding key keeps the $and intact
 * simplifyQuery({ $and: [{ price: { $gt: 1 } }, { price: { $lt: 9 } }] })
 * // => { $and: [{ price: { $gt: 1 } }, { price: { $lt: 9 } }] }
 * ```
 *
 * @see https://utils.feathersjs.com/utils/simplify-query.html
 */
export declare function simplifyQuery<Q extends Query | null | undefined>(
  query: Q,
  options?: SimplifyQueryOptions,
): Q
ArgumentTypeDescription
queryQ
optionsSimplifyQueryOptions

Released under the MIT License.