api/src/routes/private/reddit.ts
104 lines · 2847 bytes
1// Subreddit info and top monthly posts
2import { createRoute, z } from '@hono/zod-openapi'
3import { fetchJson } from '@/lib/fetch'
4import { freshSeconds } from '@/lib/cache/freshness'
5import { newApp } from '@/lib/openapi'
6import { ErrorResponse, Ok, SubredditSchema } from '@/schemas'
7
8const app = newApp()
9
10const FRESH_TTL = freshSeconds('reddit')
11
12interface AboutData {
13 data?: {
14 display_name_prefixed?: string
15 title?: string
16 public_description?: string
17 description?: string
18 community_icon?: string
19 banner_background_image?: string
20 primary_color?: string
21 subscribers?: number
22 accounts_active?: number
23 created?: number
24 description_html?: string
25 }
26}
27
28interface RedditPost {
29 data: {
30 title: string
31 selftext: string
32 ups: number
33 downs: number
34 created: number
35 url: string
36 }
37}
38
39interface PostListing {
40 data?: { children?: RedditPost[] }
41}
42
43// Reddit blocks generic UAs, it wants a descriptive one with a contact handle
44const headers = { 'User-Agent': 'awesome-privacy-api/1.0 by /u/Lissy93' }
45
46const stripQuery = (raw?: string) => raw?.split('?')[0] ?? null
47
48const mapInfo = (about: AboutData) => {
49 const d = about.data ?? {}
50 return {
51 name: d.display_name_prefixed ?? null,
52 title: d.title ?? null,
53 description: d.public_description ?? null,
54 longDescription: d.description ?? null,
55 icon: stripQuery(d.community_icon),
56 banner: stripQuery(d.banner_background_image),
57 color: d.primary_color ?? null,
58 subscribers: d.subscribers ?? null,
59 activeSubscribers: d.accounts_active ?? null,
60 dateCreated: d.created ?? null,
61 descriptionHtml: d.description_html ?? null,
62 }
63}
64
65const mapPosts = (top: PostListing) =>
66 (top.data?.children ?? []).map(({ data }) => ({
67 title: data.title,
68 body: data.selftext,
69 upVotes: data.ups,
70 downVotes: data.downs,
71 date: data.created,
72 url: data.url,
73 }))
74
75const route = createRoute({
76 method: 'get',
77 path: '/enrich/reddit/{sub}',
78 tags: ['Enrichment'],
79 summary: 'Subreddit info',
80 request: { params: z.object({ sub: z.string() }) },
81 responses: {
82 200: Ok(SubredditSchema),
83 401: ErrorResponse,
84 500: ErrorResponse,
85 502: ErrorResponse,
86 },
87})
88
89// Two Reddit reads in parallel, cached as one object
90app.openapi(route, async (c) => {
91 const { sub } = c.req.valid('param')
92 const aboutUrl = `https://www.reddit.com/r/${sub}/about.json`
93 const topUrl = `https://www.reddit.com/r/${sub}/top.json?t=month&limit=10`
94 const data = await c.var.storage.fetch(`reddit:${sub}`, FRESH_TTL, async () => {
95 const [about, top] = await Promise.all([
96 fetchJson<AboutData>(aboutUrl, { headers }),
97 fetchJson<PostListing>(topUrl, { headers }),
98 ])
99 return { info: mapInfo(about), posts: mapPosts(top) }
100 })
101 return c.json(data, 200)
102})
103
104export default app