api/src/routes/private/website.ts
51 lines · 1662 bytes
1// APIVoid website report passthrough
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, Ok, WebsiteReportSchema } from '@/schemas'
8
9const app = newApp()
10
11const FRESH_TTL = freshSeconds('website')
12
13interface ApiVoidResp {
14 data?: { report?: unknown }
15}
16
17const route = createRoute({
18 method: 'get',
19 path: '/enrich/website',
20 tags: ['Enrichment'],
21 summary: 'Website info',
22 request: { query: z.object({ url: z.string().url() }) },
23 responses: {
24 200: Ok(WebsiteReportSchema),
25 400: ErrorResponse,
26 401: ErrorResponse,
27 500: ErrorResponse,
28 502: ErrorResponse,
29 },
30})
31
32// Cache key is the host so different paths on the same domain share results
33app.openapi(route, async (c) => {
34 const { url: target } = c.req.valid('query')
35 const host = new URL(target).hostname
36 const key = c.env.APIVOID_API_KEY
37 if (!key) throw new ApiError('INTERNAL', 'APIVOID_API_KEY not configured', 500)
38 const upstream =
39 'https://endpoint.apivoid.com/urlrep/v1/pay-as-you-go/' +
40 `?key=${key}&url=${encodeURIComponent(target)}`
41 const data = await c.var.storage.fetch(`website:${host}`, FRESH_TTL, async () => {
42 const result = await fetchJson<ApiVoidResp>(upstream, { timeoutMs: 15000 })
43 if (!result?.data?.report) {
44 throw new ApiError('UPSTREAM_ERROR', 'APIVoid did not return a report', 502)
45 }
46 return result.data.report as Record<string, unknown>
47 })
48 return c.json(data as Record<string, unknown>, 200)
49})
50
51export default app