api/src/utils.ts
36 lines · 1461 bytes
1import * as yaml from 'js-yaml';
2
3import type { AwesomePrivacy, Service } from './types';
4
5
6/* Given a category/section/listing title, return it's slug/ID */
7export const slugify = (title: string): string => title.toLowerCase().replace(/\s+/g, '-');
8
9/* Fetches and parses Awesome Privacy source data from GitHub CDN */
10export const fetchAwesomePrivacyData = async (): Promise<AwesomePrivacy> => {
11 const res = await fetch('https://raw.githubusercontent.com/Lissy93/awesome-privacy/main/awesome-privacy.yml');
12 const text = await res.text();
13 return yaml.load(text) as AwesomePrivacy;
14};
15
16/* Returns all services as a flat array from Awesome Privacy */
17export const fetchAllServices = async (): Promise<Service[]> => {
18 const { categories } = await fetchAwesomePrivacyData();
19 return categories.flatMap(category => category.sections.flatMap(section => section.services));
20};
21
22/* Find a given item by it's slug */
23export const findBySlug = <T extends { name: string }>(collection: T[], slug: string): T | undefined =>
24 collection.find(item => slugify(item.name) === slug);
25
26
27export const renderRemoteIndex = async (ctx) => {
28 const indexHtmlUrl = 'https://raw.githubusercontent.com/Lissy93/awesome-privacy/main/api/public/index.html';
29 const response = await fetch(indexHtmlUrl);
30 if (response.ok) {
31 const htmlContent = await response.text();
32 return ctx.html(htmlContent);
33 } else {
34 return ctx.text('Unable to fetch the page', 502);
35 }
36};