api/src/api.ts

81 lines · 2750 bytes

 1import { Hono } from 'hono';
 2import Fuse from 'fuse.js';
 3
 4import {
 5  fetchAllServices,
 6  fetchAwesomePrivacyData,
 7  findBySlug,
 8  slugify,
 9  renderRemoteIndex,
10} from './utils';
11
12import index from '../public/index.html'
13
14/* Create new Hono app */
15const app = new Hono({ strict: false });
16
17/* Serve the index page (which contains the Swagger Docs) */
18app.get("/", async (ctx) => {
19  if (index) {
20    return ctx.html(index)
21  } else {
22    return renderRemoteIndex(ctx);
23  }
24});
25
26/* Returns an array all service objects */
27app.get('/services', async (c) => {
28  return c.json(await fetchAllServices());
29});
30
31/* Returns an array of all categories IDs */
32app.get('/categories', async (c) => {
33  const { categories } = await fetchAwesomePrivacyData();
34  return c.json(categories.map(({ name }) => slugify(name)));
35});
36
37app.get('/search', async (c) => {
38  return c.json({ error: 'Search term not specified' }, 404)
39});
40
41/* Search results, returns an array of listing which match a given search term  */
42app.get('/search/:searchTerm', async (c) => {
43  const services = await fetchAllServices();
44  const options = {
45    includeScore: true,
46    keys: ['name', 'description', 'followWith']
47  };
48  const fuse = new Fuse(services, options);
49  const searchTerm = c.req.param('searchTerm');
50  const result = fuse.search(searchTerm);
51  const mappedResults = result.map(({ item, score }) => ({ ...item, score }));
52  return c.json(mappedResults);
53});
54
55
56/* Returns an array of all section IDs within a given category */
57app.get('/:category', async (c) => {
58  const { categories } = await fetchAwesomePrivacyData();
59  const category = findBySlug(categories, c.req.param('category'));
60  return category ? c.json(category.sections.map(({ name }) => slugify(name)))
61    : c.json({ error: 'Category not found' }, 404);
62});
63
64/* Returns an array of all service objects within a given section */
65app.get('/:category/:section', async (c) => {
66  const { categories } = await fetchAwesomePrivacyData();
67  const category = findBySlug(categories, c.req.param('category'));
68  const section = findBySlug(category?.sections || [], c.req.param('section'));
69  return section ? c.json(section.services || []) : c.json({ error: 'Section not found' }, 404);
70});
71
72/* Returns a single service object, for a given category, section and service */
73app.get('/:category/:section/:service', async (c) => {
74  const { categories } = await fetchAwesomePrivacyData();
75  const category = findBySlug(categories, c.req.param('category'));
76  const section = findBySlug(category?.sections || [], c.req.param('section'));
77  const service = findBySlug(section?.services || [], c.req.param('service'));
78  return service ? c.json(service) : c.json({ error: 'Service not found' }, 404);
79});
80
81export default app;