|
import Koa from 'koa';
|
|
import Router from '@koa/router';
|
|
import cors from '@koa/cors';
|
|
import { bodyParser } from '@koa/bodyparser';
|
|
import serve from 'koa-static';
|
|
import path from 'path';
|
|
import { whiteListMiddleware } from './middlewares';
|
|
import history from 'koa2-connect-history-api-fallback';
|
|
import { chatStreamController, localChatStreamController, localModelsController, modelsController, searchController, sogouSearchController } from './controllers';
|
|
import { initializeModels } from './constant';
|
|
|
|
|
|
|
|
import dotenvx from '@dotenvx/dotenvx';
|
|
dotenvx.config();
|
|
|
|
const app = new Koa();
|
|
const router = new Router();
|
|
|
|
const port = process.env.PORT || 3000;
|
|
|
|
app.use(history({
|
|
index: '/index.html',
|
|
whiteList: ['/api']
|
|
}));
|
|
|
|
|
|
const staticPath = path.join(__dirname, '../web/build');
|
|
app.use(serve(staticPath, {
|
|
gzip: true,
|
|
index: 'index.html'
|
|
}));
|
|
|
|
app.use(cors({
|
|
origin: '*'
|
|
}));
|
|
|
|
app.use(bodyParser());
|
|
|
|
|
|
app.use(async (ctx, next) => {
|
|
try {
|
|
await next();
|
|
} catch(err) {
|
|
console.error('[server error]', err);
|
|
ctx.res.statusCode = 422;
|
|
ctx.body = err;
|
|
}
|
|
});
|
|
|
|
|
|
app.use(router.routes()).use(router.allowedMethods());
|
|
|
|
|
|
router.post('/api/search', whiteListMiddleware(), searchController);
|
|
router.post('/api/sogou/search', sogouSearchController);
|
|
router.post('/api/chat', chatStreamController);
|
|
router.get('/api/models', modelsController);
|
|
|
|
|
|
router.get('/api/local/models', localModelsController);
|
|
router.post('/api/local/chat', localChatStreamController);
|
|
|
|
|
|
async function startApp() {
|
|
try {
|
|
|
|
await initializeModels();
|
|
console.log('Models initialized successfully');
|
|
|
|
|
|
app.listen(port, () => {
|
|
console.log(`Server is running on port ${port}`);
|
|
});
|
|
} catch (error) {
|
|
console.error('Failed to start the application:', error);
|
|
process.exit(1);
|
|
}
|
|
}
|
|
|
|
|
|
startApp();
|
|
|