Group.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. const { pool } = require('../config/database');
  2. // 创建群组表
  3. const createGroupTable = async () => {
  4. try {
  5. await pool.query(`
  6. CREATE TABLE IF NOT EXISTS groups (
  7. id INT AUTO_INCREMENT PRIMARY KEY,
  8. group_id VARCHAR(50) NOT NULL UNIQUE,
  9. group_name VARCHAR(100) NOT NULL,
  10. creator_id VARCHAR(50) NOT NULL,
  11. is_active BOOLEAN DEFAULT TRUE,
  12. created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
  13. )
  14. `);
  15. } catch (error) {
  16. console.error('创建群组表失败:', error);
  17. }
  18. };
  19. // 初始化表
  20. createGroupTable();
  21. // 群组相关方法
  22. const Group = {
  23. // 获取所有群组
  24. findAll: async () => {
  25. const [rows] = await pool.query(
  26. 'SELECT * FROM groups ORDER BY created_at DESC'
  27. );
  28. return rows;
  29. },
  30. // 根据ID查找群组
  31. findById: async (id) => {
  32. const [rows] = await pool.query(
  33. 'SELECT * FROM groups WHERE id = ?',
  34. [id]
  35. );
  36. return rows[0];
  37. },
  38. // 根据群组ID查找群组
  39. findByGroupId: async (groupId) => {
  40. const [rows] = await pool.query(
  41. 'SELECT * FROM groups WHERE group_id = ?',
  42. [groupId]
  43. );
  44. return rows[0];
  45. },
  46. // 创建群组
  47. create: async (groupData) => {
  48. const [result] = await pool.query(
  49. 'INSERT INTO groups (group_id, group_name, creator_id) VALUES (?, ?, ?)',
  50. [groupData.groupId, groupData.groupName, groupData.creatorId]
  51. );
  52. return result.insertId;
  53. },
  54. // 更新群组
  55. update: async (id, groupData) => {
  56. await pool.query(
  57. 'UPDATE groups SET group_name = ?, is_active = ? WHERE id = ?',
  58. [groupData.groupName, groupData.isActive, id]
  59. );
  60. },
  61. // 删除群组
  62. delete: async (id) => {
  63. await pool.query('DELETE FROM groups WHERE id = ?', [id]);
  64. }
  65. };
  66. module.exports = Group;