route.ts 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import { NextResponse } from 'next/server'
  2. import mysql from 'mysql2/promise'
  3. // 创建全局的 MySQL 连接池
  4. const pool = mysql.createPool({
  5. connectionLimit: 10,
  6. host: '192.168.3.89', // 服务器地址
  7. user: 'root',
  8. password: '123456', // 密码
  9. database: 'chat',
  10. })
  11. interface Request{
  12. id: string;
  13. messages: {
  14. id: string;
  15. date: string;
  16. role: "system" | "user" | "assistant";
  17. content: string;
  18. }[];
  19. }
  20. export async function InsertData(req:Request,res:any) {
  21. try {
  22. // 从连接池中获取连接
  23. const connection = await pool.getConnection()
  24. const id = req.id;
  25. const messages = req.messages;
  26. const [rows, fields] = await connection.query('SELECT * FROM dialog where id = ?',[id]);
  27. if(!rows) {
  28. // 执行 MySQL 添加头表
  29. await connection.execute('INSERT INTO dialog (id, create_time) VALUES (?,?)',[req, new Date])
  30. }
  31. messages.forEach(async function(message) {
  32. const detailId = message.id;
  33. const role = message.role;
  34. const createDate = message.date;
  35. const content = message.content;
  36. console.log(message);
  37. const [detailRows, fields] = await connection.query('SELECT * FROM dialog_detail where id = ?',[detailId]);
  38. if(!detailRows) {
  39. // 执行 MySQL 添加头表
  40. await connection.execute('INSERT INTO dialog_detail (id,dialog_id,type,content,create_by, create_time) VALUES (?, ?, ?)',[detailId,id,role,content,role,createDate])
  41. }
  42. });
  43. // 释放连接回连接池
  44. connection.release()
  45. return res.status(201).json({ message: 'Data inserted successfully' });
  46. } catch (error) {
  47. console.error('Error:', error)
  48. return res.status(500).json({ error: 'Internal Server Error' });
  49. }
  50. }