mirror of
https://github.com/Nezumi-2711/9router-config-generate.git
synced 2026-09-22 13:38:32 +00:00
feat: add fetch model function
This commit is contained in:
+55
-1
@@ -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 }))
|
||||
}
|
||||
})
|
||||
})
|
||||
},
|
||||
},
|
||||
],
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user