route.ts 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. export async function POST(req: any) {
  22. try {
  23. // 从连接池中获取连接
  24. const connection = await pool.getConnection()
  25. const data: Request = await req.json();
  26. const id = data.id;
  27. const messages = data.messages;
  28. const [rows, fields] = await connection.query('SELECT * FROM dialog where id = ?', [id]);
  29. if ((rows as any).length === 0) {
  30. // 执行 MySQL 添加头表
  31. await connection.execute('INSERT INTO dialog (id, create_time) VALUES (?,?)', [id, new Date])
  32. }
  33. messages.forEach(async function (message) {
  34. const detailId = message.id;
  35. const role = message.role;
  36. const createDate = message.date;
  37. const content = message.content;
  38. const [detailRows, fields] = await connection.query('SELECT * FROM dialog_detail where id = ?', [detailId]);
  39. if ((detailRows as any).length === 0) {
  40. // 执行 MySQL 添加明细表
  41. await connection.execute('INSERT INTO dialog_detail (id,dialog_id,type,content,create_by, create_time) VALUES (?, ?, ?,?,?,?)', [detailId, id, role, content, role, createDate])
  42. }
  43. });
  44. // 释放连接回连接池
  45. connection.release()
  46. return NextResponse.json({ message: 'ok', data: (rows as any).length }, { status: 200 })
  47. } catch (error) {
  48. console.error('Error:', error)
  49. return NextResponse.json({ error: 'Internal Server Error' }, { status: 500 })
  50. }
  51. }
  52. export async function GET() {
  53. try {
  54. // 从连接池中获取连接
  55. const connection = await pool.getConnection()
  56. // 执行 MySQL 查询
  57. 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 ' +
  58. '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')
  59. // 释放连接回连接池
  60. connection.release()
  61. return NextResponse.json({ data: rows }, { status: 200 })
  62. } catch (error) {
  63. console.error('Error:', error)
  64. return NextResponse.json({ error: 'Internal Server Error' }, { status: 500 })
  65. }
  66. }