feat: add fetch model function

This commit is contained in:
2026-08-15 10:35:55 +07:00
parent 570512549d
commit 4bcf5eb132
5 changed files with 340 additions and 31 deletions
+55 -1
View File
@@ -2,12 +2,66 @@ import { defineConfig } from 'vite'
import react, { reactCompilerPreset } from '@vitejs/plugin-react'
import babel from '@rolldown/plugin-babel'
import tailwindcss from '@tailwindcss/vite'
import type { IncomingMessage, ServerResponse } from 'node:http'
// https://vite.dev/config/
export default defineConfig({
plugins: [
tailwindcss(),
react(),
babel({ presets: [reactCompilerPreset()] })
babel({ presets: [reactCompilerPreset()] }),
{
name: 'router-proxy-middleware',
configureServer(server) {
server.middlewares.use('/api/fetch-models', async (req: IncomingMessage, res: ServerResponse) => {
if (req.method !== 'POST') {
res.statusCode = 405
res.end(JSON.stringify({ error: 'Method not allowed' }))
return
}
let body = ''
req.on('data', (chunk: Buffer) => {
body += chunk.toString()
})
req.on('end', async () => {
try {
const { baseUrl, apiKey } = JSON.parse(body || '{}')
if (!baseUrl) {
res.statusCode = 400
res.setHeader('Content-Type', 'application/json')
res.end(JSON.stringify({ error: 'baseUrl is required' }))
return
}
const targetUrl = `${baseUrl.replace(/\/+$/, '')}/models`
const headers: Record<string, string> = {
'Accept': 'application/json',
}
if (apiKey) {
headers['Authorization'] = `Bearer ${apiKey.trim()}`
}
const remoteRes = await fetch(targetUrl, {
method: 'GET',
headers,
})
const remoteData = await remoteRes.json().catch(() => null)
res.statusCode = remoteRes.status
res.setHeader('Content-Type', 'application/json')
res.end(JSON.stringify(remoteData || {}))
} catch (err: unknown) {
res.statusCode = 500
res.setHeader('Content-Type', 'application/json')
const msg = err instanceof Error ? err.message : 'Internal error'
res.end(JSON.stringify({ error: msg }))
}
})
})
},
},
],
})