api/src/routes/private/docker.ts
88 lines · 2784 bytes
1// Docker image info from Portainer templates plus Docker Hub metrics
2import { createRoute, z } from '@hono/zod-openapi'
3import { ApiError } from '@/lib/errors'
4import { fetchJson } from '@/lib/fetch'
5import { freshSeconds } from '@/lib/cache/freshness'
6import { newApp } from '@/lib/openapi'
7import { composeFile, normalize, runCommand, type Template } from '@/lib/docker'
8import { DockerInfoSchema, ErrorResponse, Ok } from '@/schemas'
9
10const app = newApp()
11
12const FRESH_TTL = freshSeconds('docker')
13
14const TEMPLATES_URL =
15 'https://raw.githubusercontent.com/Lissy93/portainer-templates/main/templates.json'
16
17interface TemplateList {
18 templates?: Template[]
19}
20
21// Templates whose title or name loosely matches, preferring runnable (image-bearing) ones
22const matchTemplate = (templates: Template[], query: string) => {
23 const matches = templates.filter(
24 (t) =>
25 normalize(t.title ?? '').includes(query) || normalize(t.name ?? '').includes(query),
26 )
27 return matches.find((t) => t.image) ?? matches[0]
28}
29
30// Docker Hub repo metrics for an image, null when missing or unavailable
31const getHubData = async (image: string, token?: string) => {
32 const [name] = image.split(':')
33 const [namespace, repo] = name.includes('/') ? name.split('/') : ['library', name]
34 const headers: Record<string, string> = {}
35 if (token) headers.Authorization = `Bearer ${token}`
36 try {
37 return await fetchJson(
38 `https://hub.docker.com/v2/repositories/${namespace}/${repo}/`,
39 { headers },
40 )
41 } catch {
42 return null
43 }
44}
45
46const route = createRoute({
47 method: 'get',
48 path: '/enrich/docker/{name}',
49 tags: ['Enrichment'],
50 summary: 'Docker image info',
51 request: { params: z.object({ name: z.string().min(1) }) },
52 responses: {
53 200: Ok(DockerInfoSchema),
54 400: ErrorResponse,
55 401: ErrorResponse,
56 404: ErrorResponse,
57 500: ErrorResponse,
58 },
59})
60
61app.openapi(route, async (c) => {
62 const { name } = c.req.valid('param')
63 const query = normalize(name)
64 if (!query) throw new ApiError('BAD_REQUEST', 'Invalid image name', 400)
65 const data = await c.var.storage.fetch(`docker:${query}`, FRESH_TTL, async () => {
66 const list = await fetchJson<TemplateList>(TEMPLATES_URL)
67 const template = matchTemplate(list.templates ?? [], query)
68 if (!template) {
69 throw new ApiError('NOT_FOUND', `'${name}' not found in Portainer templates`, 404)
70 }
71 const dockerHubData = template.image
72 ? await getHubData(template.image, c.env.DOCKERHUB_TOKEN)
73 : null
74 return {
75 found: true,
76 error: null,
77 template,
78 dockerHubData,
79 usage: {
80 dockerRunCommand: runCommand(template),
81 dockerComposeFile: composeFile(template),
82 },
83 }
84 })
85 return c.json(data, 200)
86})
87
88export default app