aboutsummaryrefslogtreecommitdiff
path: root/src/components/hooks/queries/useWebsiteValuesQuery.ts
blob: 1e097369e7ffcbc79305fb0c0b789a282a09c42d (plain) (blame)
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
import { useCountryNames } from '@/components/hooks/useCountryNames';
import { useRegionNames } from '@/components/hooks/useRegionNames';
import { useApi } from '../useApi';
import { useLocale } from '../useLocale';

export function useWebsiteValuesQuery({
  websiteId,
  type,
  startDate,
  endDate,
  search,
}: {
  websiteId: string;
  type: string;
  startDate: Date;
  endDate: Date;
  search?: string;
}) {
  const { get, useQuery } = useApi();
  const { locale } = useLocale();
  const { countryNames } = useCountryNames(locale);
  const { regionNames } = useRegionNames(locale);

  const names = {
    country: countryNames,
    region: regionNames,
  };

  const getSearch = (type: string, value: string) => {
    if (value) {
      const values = names[type];

      if (values) {
        return (
          Object.keys(values)
            .reduce((arr: string[], key: string) => {
              if (values[key].toLowerCase().includes(value.toLowerCase())) {
                return arr.concat(key);
              }
              return arr;
            }, [])
            .slice(0, 5)
            .join(',') || value
        );
      }

      return value;
    }
  };

  return useQuery({
    queryKey: ['websites:values', { websiteId, type, startDate, endDate, search }],
    queryFn: () =>
      get(`/websites/${websiteId}/values`, {
        type,
        startAt: +startDate,
        endAt: +endDate,
        search: getSearch(type, search),
      }),
    enabled: !!(websiteId && type && startDate && endDate),
  });
}