route.ts 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. import { NextResponse } from 'next/server';
  2. import mysql from 'mysql2/promise';
  3. // 创建全局的 MySQL 连接池
  4. const pool = mysql.createPool({
  5. connectionLimit: 10,
  6. host: 'xia0miduo.gicp.net', // 服务器地址
  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) {
  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 NextResponse.json({ message: 'ok' }, { status: 200 })
  46. } catch (error) {
  47. console.error('Error:', error)
  48. return NextResponse.json({ error: 'Internal Server Error' }, { status: 500 })
  49. }
  50. }
  51. export async function getAllData() {
  52. try {
  53. // 从连接池中获取连接
  54. const connection = await pool.getConnection()
  55. // 执行 MySQL 查询
  56. 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')
  57. // 释放连接回连接池
  58. connection.release()
  59. return NextResponse.json({ data: rows }, { status: 200 })
  60. } catch (error) {
  61. console.error('Error:', error)
  62. return NextResponse.json({ error: 'Internal Server Error' }, { status: 500 })
  63. }
  64. }