api/src/lib/data.ts

85 lines · 2746 bytes

10 symbols in this file
 1/**
 2 * Loads the pre-build awesome-privacy JSON data
 3 * Exposes it as both flat and nested structure
 4 * Used by all public routes which use this data
 5 */
 6
 7import raw from '@/generated/data.json'
 8import type { AwesomePrivacy, Category, Section, Service, FlatService } from '@/types'
 9
10const data = raw as unknown as AwesomePrivacy
11
12// Turn any listing/section/category name into a URL-safe slug
13export const slugify = (input: string) =>
14  input
15    .toLowerCase()
16    .trim()
17    .replace(/[^a-z0-9]+/g, '-')
18    .replace(/^-|-$/g, '')
19
20// Returns a given listing by it's name
21export const findBySlug = <T extends { name: string }>(items: T[], slug: string) =>
22  items.find((item) => slugify(item.name) === slug)
23
24let flatCache: FlatService[] | null = null
25
26// Flatten every service with its parent category and section attached
27export const allServices = (): FlatService[] => {
28  if (flatCache) return flatCache
29  const out: FlatService[] = []
30  for (const category of data.categories) {
31    for (const section of category.sections) {
32      for (const service of section.services ?? []) {
33        out.push({
34          ...service,
35          slug: slugify(service.name),
36          category: category.name,
37          categorySlug: slugify(category.name),
38          section: section.name,
39          sectionSlug: slugify(section.name),
40        })
41      }
42    }
43  }
44  flatCache = out
45  return out
46}
47
48// Top-level list of categories from the source data
49export const categories = (): Category[] => data.categories
50
51// Resolve a category by its slug
52export const findCategory = (slug: string) => findBySlug(categories(), slug)
53
54interface SectionHit {
55  category: Category
56  section: Section
57}
58
59// Look up a section by slug across every category, returning its parent too
60export const findSection = (slug: string): SectionHit | null => {
61  for (const category of categories()) {
62    const section = findBySlug(category.sections, slug)
63    if (section) return { category, section }
64  }
65  return null
66}
67
68// Resolve a single service by its slug from the flat list
69export const findService = (slug: string): FlatService | undefined =>
70  allServices().find((service) => service.slug === slug)
71
72// Aggregate counts for all data, used for stats endpoint
73export const stats = () => {
74  const services = allServices()
75  return {
76    categories: categories().length,
77    sections: categories().reduce((total, cat) => total + cat.sections.length, 0),
78    services: services.length,
79    openSource: services.filter((service) => service.openSource).length,
80    securityAudited: services.filter((service) => service.securityAudited).length,
81    acceptsCrypto: services.filter((service) => service.acceptsCrypto).length,
82  }
83}
84
85export type { Service, Section, Category }