route.ts 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. import { NextResponse } from 'next/server';
  2. import mysql from 'mysql2/promise';
  3. // 创建全局的 MySQL 连接池
  4. const pool = mysql.createPool({
  5. connectionLimit: 100,
  6. host: '60.204.184.98', // 服务器地址
  7. port: 33308,
  8. user: 'chat',
  9. password: 'DZzx6ACMhinTtTtS', // 密码
  10. database: 'chat',
  11. })
  12. interface Request {
  13. id: string;
  14. messages: {
  15. id: string;
  16. date: string;
  17. role: "system" | "user" | "assistant";
  18. content: string;
  19. }[];
  20. }
  21. // 插入数据
  22. export async function POST(req: any) {
  23. try {
  24. // 从连接池中获取连接
  25. const connection = await pool.getConnection()
  26. const data: Request = await req.json();
  27. const id = data.id;
  28. const messages = data.messages;
  29. const [rows, fields] = await connection.query('SELECT * FROM dialog where id = ?', [id]);
  30. if ((rows as any).length === 0) {
  31. // 执行 MySQL 添加头表
  32. await connection.execute('INSERT INTO dialog (id, create_time) VALUES (?,?)', [id, new Date])
  33. }
  34. messages.forEach(async function (message) {
  35. const detailId = message.id;
  36. const role = message.role;
  37. const createDate = message.date;
  38. const content = message.content;
  39. const [detailRows, fields] = await connection.query('SELECT * FROM dialog_detail where id = ?', [detailId]);
  40. if ((detailRows as any).length === 0) {
  41. // 执行 MySQL 添加明细表
  42. await connection.execute('INSERT INTO dialog_detail (id,dialog_id,type,content,create_by, create_time) VALUES (?, ?, ?,?,?,?)', [detailId, id, role, content, role, createDate])
  43. }
  44. });
  45. // 释放连接回连接池
  46. connection.release()
  47. return NextResponse.json({ message: 'success', data: {} }, { status: 200 })
  48. } catch (e) {
  49. console.error('Error:', e)
  50. return NextResponse.json({ message: 'error' }, { status: 500 })
  51. }
  52. }
  53. // 查询数据
  54. export async function GET() {
  55. try {
  56. // 从连接池中获取连接
  57. const connection = await pool.getConnection()
  58. // 执行 MySQL 查询
  59. const [rows, fields] = await connection.query('SELECT he.id,he.dialog_name,de.id did,de.dialog_id,de.type,de.content,de.create_time ' +
  60. 'FROM dialog he left join dialog_detail de on he.id = de.dialog_id order by he.create_time desc, he.id , de.create_time, type desc')
  61. // 释放连接回连接池
  62. connection.release()
  63. return NextResponse.json({ message: 'success', data: rows }, { status: 200 })
  64. } catch (e) {
  65. console.error('Error:', e)
  66. return NextResponse.json({ message: 'error' }, { status: 500 })
  67. }
  68. }