123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112 |
- const Router = require('@koa/router');
- const ai = require('../controller/ai.controller');
- const router = new Router({ prefix: '/api/ai' });
- const request = require('../utils/request');
- const util = require('../utils/util');
- const qs = require('qs');
- const bodyParser = require('koa-bodyparser');
- const { chatStream } = require('../controller/ai.controller');
- router.post('/stream', bodyParser(), chatStream);
- router.post('/lib/chat', ai.codeGenerate);
- router.get('/proxy', async (ctx) => handleProxy(ctx, 'get'));
- router.post('/proxy', async (ctx) => handleProxy(ctx, 'post'));
- router.put('/proxy', async (ctx) => handleProxy(ctx, 'put'));
- router.patch('/proxy', async (ctx) => handleProxy(ctx, 'patch'));
- router.delete('/proxy', async (ctx) => handleProxy(ctx, 'delete'));
- const handleProxy = async (ctx, method) => {
- try {
- const {
- query,
- body,
- headers: { host, origin, proxyapi, ...headers },
- } = ctx.request;
- if (!proxyapi) {
- return util.fail(ctx, '接口请求地址不存在', 404);
- }
- let params = method === 'get' || method === 'delete' ? query : body;
- if (headers['content-type'] === 'application/x-www-form-urlencoded') {
- params = qs.stringify(params);
- } else {
- params = method === 'get' || method === 'delete' ? query : JSON.stringify(params || {});
- }
- let response = null;
- if (method === 'get' || method === 'delete') {
- response = await request[method](proxyapi, {
- params,
- headers,
- });
- } else {
- response = await request[method](proxyapi, params, {
- headers,
- });
- }
- const { status, statusText, data } = response;
- for (let key in response.headers) {
- ctx.set(key, response.headers[key]);
- }
- if (status === 200) {
- ctx.body = data;
- } else {
- if (status === 401 || status === 405) {
- return util.fail(ctx, '接口请求方法错误', status);
- }
- if (status === 404) {
- return util.fail(ctx, '接口请求地址不存在', status);
- }
- util.fail(ctx, data || statusText, 500);
- }
- } catch (error) {
-
- if (error.code === 'ECONNREFUSED' || error.code === 'ENOTFOUND') {
-
- ctx.status = 502;
- ctx.body = {
- message: '服务不可用或地址不存在',
- error: error.message,
- };
- } else if (error.response) {
-
- const { status, data } = error.response;
- ctx.status = status;
- ctx.body = data;
- } else if (error.request) {
-
- ctx.status = 504;
- ctx.body = {
- message: '请求超时,未收到响应',
- error: error.message,
- };
- } else {
-
- ctx.status = 500;
- ctx.body = {
- message: '服务器内部错误',
- error: error.message,
- };
- }
- }
- };
- module.exports = router;
|