@@ -16,10 +16,16 @@ import cors from 'cors'
1616import { authenticateToken } from './middlewares'
1717import { getLogger } from '../utils'
1818import path from 'path'
19+ import fs from 'node:fs'
1920import type { Server } from 'node:http'
2021import { __dirname } from '../__dirname'
2122
22- export function createApp ( configure ?: ( app : Application ) => void ) : Application {
23+ export interface ApiServerOptions {
24+ /** Directory containing the built management panel (index.html + assets). */
25+ frontendDir ?: string
26+ }
27+
28+ export function createApp ( configure ?: ( app : Application ) => void , options : ApiServerOptions = { } ) : Application {
2329 const app = express ( )
2430 app . use ( express . json ( ) )
2531 app . use ( cors ( ) )
@@ -37,15 +43,27 @@ export function createApp (configure?: (app: Application) => void): Application
3743 app . use ( '/api/logs' , authenticateToken , LogsRouter )
3844 app . use ( '/v1' , authenticateToken , OpenAIRouter )
3945 configure ?.( app )
40- app . use ( express . static ( path . join ( __dirname , '../frontend/build' ) ) )
41- app . get ( '*' , ( _req , res ) => {
42- res . sendFile ( path . join ( __dirname , '../frontend/build/index.html' ) )
43- } )
46+ const frontendDir = options . frontendDir
47+ ? path . resolve ( options . frontendDir )
48+ : path . join ( __dirname , '../frontend/build' )
49+ const frontendEntry = path . join ( frontendDir , 'index.html' )
50+ if ( fs . existsSync ( frontendEntry ) ) {
51+ app . use ( express . static ( frontendDir ) )
52+ app . get ( '*' , ( _req , res ) => {
53+ res . sendFile ( frontendEntry )
54+ } )
55+ }
56+ else {
57+ getLogger ( ) . warn ( `Chaite management panel not found at ${ frontendDir } ` )
58+ app . get ( '*' , ( _req , res ) => {
59+ res . status ( 404 ) . json ( { code : - 1 , data : null , message : 'Management panel is not installed' } )
60+ } )
61+ }
4462 return app
4563}
4664
47- export function runServer ( host : string , port : number , configure ?: ( app : Application ) => void ) : { app : Application , server : Server } {
48- const app = createApp ( configure )
65+ export function runServer ( host : string , port : number , configure ?: ( app : Application ) => void , options : ApiServerOptions = { } ) : { app : Application , server : Server } {
66+ const app = createApp ( configure , options )
4967 const server = app . listen ( port , host , ( ) => {
5068 getLogger ( ) . info ( `Chaite server is running at http://${ host } :${ port } ` )
5169 } )
0 commit comments