All files / app/utils searchFilters.ts

81.57% Statements 31/38
54.16% Branches 13/24
87.5% Functions 7/8
82.85% Lines 29/35

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      69x                 69x 4x 4x 8x       3x 3x 3x         2x 2x 2x                             1x   1x   1x 2x 2x 1x     2x 2x     4x           69x 3x 3x 7x 1x 2x     6x     3x 3x    
import { Coordinates } from "features/search/constants";
import { ParsedUrlQuery } from "querystring";
import { UserSearchFilters as ServiceUserSearchFilters } from "service/search";
import stringOrFirstString from "utils/stringOrFirstString";
 
export default interface SearchFilters extends ServiceUserSearchFilters {
  location?: string;
}
 
/**
 * Parses a URL search query into an object with all the search filter properties found
 */
export function parsedQueryToSearchFilters(urlQuery: ParsedUrlQuery) {
  const filters: SearchFilters = {};
  Array.from(Object.keys(urlQuery)).forEach((key) => {
    switch (key) {
      //strings
      case "location":
      case "query":
        const str = stringOrFirstString(urlQuery[key]);
        if (str) filters[key] = str;
        break;
 
      //ints
      case "lastActive":
      case "numGuests":
        const int = Number.parseInt(stringOrFirstString(urlQuery[key]) || "");
        if (int) filters[key] = int;
        break;
 
      case "bbox":
        const list = urlQuery[key] || [];
        Iif (list && list.length && Array.isArray(list)) {
          const parsedList = list.map((value) => Number.parseFloat(value));
 
          Iif (parsedList.length === 4) {
            filters[key] = parsedList as Coordinates;
          }
        }
        break;
 
      //others
      case "hostingStatusOptions":
        const rawOptions = urlQuery[key];
        const options =
          typeof rawOptions === "string" ? [rawOptions] : rawOptions ?? [];
 
        filters[key] = options
          .map((o) => Number.parseInt(o))
          .filter((o) => !!o);
        break;
 
      default:
        console.warn(`Unhandled search parameter ${key} ignored`);
        break;
    }
  });
  return filters;
}
 
/**
 * Parses a search filter object into a URL encoded search query
 */
export function parseSearchFiltersToQuery(filters: SearchFilters) {
  const entries: [string, string][] = [];
  Object.entries(filters).forEach(([key, filterValue]) => {
    if (Array.isArray(filterValue)) {
      filterValue.forEach((value) => {
        entries.push([key, `${value}`]);
      });
    } else {
      entries.push([key, filterValue]);
    }
  });
  const searchParams = new URLSearchParams(entries);
  return searchParams.toString();
}