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