api/src/routes/private/ios.ts

56 lines · 1773 bytes

 1// iTunes app lookup, accepts numeric id or bundle id, optional country
 2import { createRoute, z } from '@hono/zod-openapi'
 3import { fetchJson } from '@/lib/fetch'
 4import { ApiError } from '@/lib/errors'
 5import { freshSeconds } from '@/lib/cache/freshness'
 6import { newApp } from '@/lib/openapi'
 7import { ErrorResponse, ItunesAppSchema, Ok } from '@/schemas'
 8
 9const app = newApp()
10
11const FRESH_TTL = freshSeconds('ios')
12
13interface ItunesResult {
14  resultCount: number
15  results: Record<string, unknown>[]
16}
17
18// iTunes accepts numeric ids prefixed with "id", strip that off
19const normalize = (raw: string) => (raw.startsWith('id') ? raw.slice(2) : raw)
20
21const route = createRoute({
22  method: 'get',
23  path: '/enrich/ios/{bundleId}',
24  tags: ['Enrichment'],
25  summary: 'iOS app info',
26  request: {
27    params: z.object({ bundleId: z.string() }),
28    query: z.object({ country: z.string().length(2).optional() }),
29  },
30  responses: {
31    200: Ok(ItunesAppSchema),
32    401: ErrorResponse,
33    404: ErrorResponse,
34    500: ErrorResponse,
35    502: ErrorResponse,
36  },
37})
38
39app.openapi(route, async (c) => {
40  const { bundleId } = c.req.valid('param')
41  const { country = 'us' } = c.req.valid('query')
42  const id = normalize(bundleId)
43  const idParam = /^\d+$/.test(id) ? `id=${id}` : `bundleId=${encodeURIComponent(id)}`
44  const upstream = `https://itunes.apple.com/lookup?${idParam}&country=${country}`
45  const data = await c.var.storage.fetch(`ios:${country}:${id}`, FRESH_TTL, async () => {
46    const result = await fetchJson<ItunesResult>(upstream)
47    const first = result.results?.[0]
48    if (!result.resultCount || !first) {
49      throw new ApiError('NOT_FOUND', `No app found for '${id}'`, 404)
50    }
51    return first
52  })
53  return c.json(data, 200)
54})
55
56export default app