| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576 |
- import { NextResponse } from 'next/server';
- import mysql from 'mysql2/promise';
- // 创建全局的 MySQL 连接池
- const pool = mysql.createPool({
- connectionLimit: 100,
- host: 'xia0miduo.gicp.net', // 服务器地址
- port: 3306,
- user: 'root',
- password: '123456', // 密码
- database: 'chat',
- })
- interface Request {
- id: string;
- messages: {
- id: string;
- date: string;
- role: "system" | "user" | "assistant";
- content: string;
- }[];
- }
- export async function POST(req: Request) {
- try {
- // 从连接池中获取连接
- const connection = await pool.getConnection()
- const id = req.id;
- const messages = req.messages;
- const [rows, fields] = await connection.query('SELECT * FROM dialog where id = ?', [id]);
- if (!rows) {
- // 执行 MySQL 添加头表
- await connection.execute('INSERT INTO dialog (id, create_time) VALUES (?,?)', [req, new Date])
- }
- messages.forEach(async function (message) {
- const detailId = message.id;
- const role = message.role;
- const createDate = message.date;
- const content = message.content;
- console.log(message);
- const [detailRows, fields] = await connection.query('SELECT * FROM dialog_detail where id = ?', [detailId]);
- if (!detailRows) {
- // 执行 MySQL 添加头表
- await connection.execute('INSERT INTO dialog_detail (id,dialog_id,type,content,create_by, create_time) VALUES (?, ?, ?)', [detailId, id, role, content, role, createDate])
- }
- });
- // 释放连接回连接池
- connection.release()
- return NextResponse.json({ message: 'ok' }, { status: 200 })
- } catch (error) {
- console.error('Error:', error)
- return NextResponse.json({ error: 'Internal Server Error' }, { status: 500 })
- }
- }
- export async function GET() {
- try {
- // 从连接池中获取连接
- const connection = await pool.getConnection()
- // 执行 MySQL 查询
- const [rows, fields] = await connection.query('SELECT he.id,he.dialog_name,de.id did,de.dialog_id,de.type,de.content FROM dialog he left join dialog_detail de on he.id = de.dialog_id')
- // 释放连接回连接池
- connection.release()
- return NextResponse.json({ data: rows }, { status: 200 })
- } catch (error) {
- console.error('Error:', error)
- return NextResponse.json({ error: 'Internal Server Error' }, { status: 500 })
- }
- }
|