All files / app/util build-find-query-options.ts

100% Statements 14/14
100% Branches 8/8
100% Functions 2/2
100% Lines 13/13

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                                                                1x     4x       221x 221x 96x   221x 55x           221x     221x 308x   308x 68x       221x        
import {Includeable} from 'sequelize/types';
 
/**
 * The options which can be used for the sequelize query options.
 */
export interface QueryOptions {
  include: Includeable[] | undefined;
}
 
/**
 * One entry of the options list.
 *
 * This entry defines an options which should be
 * checked and how to handle it.
 */
export interface OptionsListEntry {
  /**
   * Key of the option.
   */
  key: string;
 
  /**
   * List of models to include in the query.
   */
  include: Includeable[];
}
/**
 * Builds a method for handling options and generating
 * include from it.
 * @param optionsList     - The list of options to handle
 * @param defaultOptions  - The default options
 */
export const buildFindQueryOptionsMethod = (
    optionsList: OptionsListEntry[],
    defaultOptions?: Record<string, unknown>,
) => (
    options?: Record<string, unknown>,
): QueryOptions => {
  // Merge option objects
  let mergedOptions: Record<string, unknown> = {};
  if (defaultOptions) {
    mergedOptions = defaultOptions;
  }
  if (options) {
    mergedOptions = {
      ...mergedOptions,
      ...options,
    };
  }
 
  const include: Includeable[] = [];
 
  // Iterate through options and update include and exclude list.
  for (let i = 0; i < optionsList.length; i++) {
    const entry = optionsList[i];
 
    if (mergedOptions[entry.key]) {
      include.push(...entry.include);
    }
  }
 
  return {
    include: include.length <= 0 ? undefined : include,
  };
};