|
|
@@ -0,0 +1,58 @@
|
|
|
+import { NextResponse } from 'next/server'
|
|
|
+import mysql from 'mysql2/promise'
|
|
|
+
|
|
|
+// 创建全局的 MySQL 连接池
|
|
|
+const pool = mysql.createPool({
|
|
|
+ connectionLimit: 10,
|
|
|
+ host: '192.168.3.89', // 服务器地址
|
|
|
+ user: 'root',
|
|
|
+ password: '123456', // 密码
|
|
|
+ database: 'chat',
|
|
|
+})
|
|
|
+
|
|
|
+interface Request{
|
|
|
+ id: string;
|
|
|
+ messages: {
|
|
|
+ id: string;
|
|
|
+ date: string;
|
|
|
+ role: "system" | "user" | "assistant";
|
|
|
+ content: string;
|
|
|
+ }[];
|
|
|
+}
|
|
|
+
|
|
|
+export async function InsertData(req:Request,res:any) {
|
|
|
+ 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 res.status(201).json({ message: 'Data inserted successfully' });
|
|
|
+ } catch (error) {
|
|
|
+ console.error('Error:', error)
|
|
|
+ return res.status(500).json({ error: 'Internal Server Error' });
|
|
|
+ }
|
|
|
+}
|