import type { NextApiRequest, NextApiResponse } from 'next' import { URL } from 'url' import type { ProxyQueryParams } from './types' import { parseFileFromMultipartRequest, safeUnlink } from './multipart' import { makeRequestWithRedirects } from './proxyRequest' import { handleProxyError } from './requestErrorResponse' import { handleProxyResponse } from './responseFormatting' export async function nip95UploadHandler(req: NextApiRequest, res: NextApiResponse): Promise { if (req.method !== 'POST') { res.status(405).json({ error: 'Method not allowed' }) return } const { targetEndpoint, authToken } = readProxyQueryParams(req) const currentUrl = new URL(targetEndpoint) const fileField = await parseFileFromMultipartRequest(req) if (!fileField) { res.status(400).json({ error: 'No file provided' }) return } try { const response = await makeRequestWithRedirects({ targetEndpoint, url: currentUrl, file: fileField, authToken, redirectCount: 0, maxRedirects: 5 }) handleProxyResponse({ res, response, targetEndpoint }) } catch (error) { handleProxyError({ res, error, targetEndpoint, hostname: currentUrl.hostname, file: fileField }) } finally { safeUnlink(fileField.filepath) } } function readProxyQueryParams(req: NextApiRequest): ProxyQueryParams { return { targetEndpoint: (req.query.endpoint as string) ?? 'https://void.cat/upload', authToken: req.query.auth as string | undefined } }