export function filterToQueryObject()

in app/assets/javascripts/vue_shared/components/filtered_search_bar/filtered_search_utils.js [118:171]


export function filterToQueryObject(filters = {}, options = {}) {
  const { filteredSearchTermKey, customOperators, shouldExcludeEmpty = false } = options;

  return Object.keys(filters).reduce((memo, key) => {
    const filter = filters[key];

    if (typeof filteredSearchTermKey === 'string' && key === FILTERED_SEARCH_TERM && filter) {
      const combinedFilteredSearchTerm = filteredSearchQueryParam(filter);
      if (combinedFilteredSearchTerm === '' && shouldExcludeEmpty) {
        return memo;
      }

      return { ...memo, [filteredSearchTermKey]: filteredSearchQueryParam(filter) };
    }

    const operators = [
      { operator: '=' },
      { operator: '!=', prefix: 'not' },
      ...(customOperators ?? []),
    ];

    const result = {};

    for (const op of operators) {
      const { operator, prefix, applyOnlyToKey } = op;

      if (!applyOnlyToKey || applyOnlyToKey === key) {
        let value;
        if (Array.isArray(filter)) {
          value = filter.filter((item) => item.operator === operator).map((item) => item.value);
        } else {
          value = filter?.operator === operator ? filter.value : null;
        }

        if (isEmpty(value)) {
          value = null;
        }

        if (shouldExcludeEmpty && (value?.[0] === '' || value === '' || value === null)) {
          // eslint-disable-next-line no-continue
          continue;
        }

        if (prefix) {
          result[`${prefix}[${key}]`] = value;
        } else {
          result[key] = value;
        }
      }
    }

    return { ...memo, ...result };
  }, {});
}