web/src/utils/fetch-data.ts

47 lines · 1342 bytes

 1import * as yaml from 'js-yaml';
 2import { error } from './logger';
 3import { safeFetch } from './safe-fetch';
 4
 5import type { AwesomePrivacy, Category } from '../types/Service';
 6
 7const awesomePrivacyData =
 8  'https://raw.githubusercontent.com/Lissy93/awesome-privacy/main/awesome-privacy.yml';
 9
10export const fetchData = async (): Promise<AwesomePrivacy> => {
11  try {
12    const res = await safeFetch(awesomePrivacyData, {}, 15000);
13    if (!res.ok) {
14      error(
15        'Data',
16        `HTTP ${res.status} fetching awesome-privacy.yml (${awesomePrivacyData})`,
17      );
18      return {} as AwesomePrivacy;
19    }
20    const text = await res.text();
21    return yaml.load(text) as AwesomePrivacy;
22  } catch (err) {
23    error('Data', `Failed to fetch awesome-privacy.yml: ${err}`);
24    return {} as AwesomePrivacy;
25  }
26};
27
28/**
29 * Loads the dataset from the browser, ready for the islands who need it
30 */
31export const fetchCategories = async (): Promise<Category[]> => {
32  try {
33    const res = await fetch('/api/awesome-privacy.json');
34    return (await res.json())?.categories || [];
35  } catch (err) {
36    error('Data', `Failed to fetch dataset: ${err}`);
37    return [];
38  }
39};
40
41export const slugify = (title: string) => {
42  return (title || '')
43    .toLowerCase()
44    .replace(/\s/g, '-')
45    .replace(/\+|&/g, 'and')
46    .replaceAll('?', '');
47};