route.ts 2.4 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: '127.0.0.1', // 服务器地址
  7. port: 3306,
  8. user: 'root',
  9. password: '123456', // 密码
  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) {
  30. // 执行 MySQL 添加头表
  31. await connection.execute('INSERT INTO dialog (id, create_time) VALUES (?,?)', [data, 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. console.log(message);
  39. const [detailRows, fields] = await connection.query('SELECT * FROM dialog_detail where id = ?', [detailId]);
  40. if (!detailRows) {
  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: 'ok', data: rows }, { status: 200 })
  48. } catch (error) {
  49. console.error('Error:', error)
  50. return NextResponse.json({ error: 'Internal Server Error' }, { status: 500 })
  51. }
  52. }
  53. export async function GET() {
  54. try {
  55. // 从连接池中获取连接
  56. const connection = await pool.getConnection()
  57. // 执行 MySQL 查询
  58. 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')
  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. }