chat.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. package db
  2. import (
  3. "errors"
  4. "fmt"
  5. "strings"
  6. "gorm.io/gorm"
  7. )
  8. type ChatType uint
  9. const Q ChatType = 1
  10. const A ChatType = 2
  11. type Chat struct {
  12. gorm.Model
  13. Username string `gorm:"type:varchar(50);not null;comment:'用户名'" json:"username"` // 用户名
  14. Source string `gorm:"type:varchar(50);comment:'用户来源:群聊名字,私聊'" json:"source"` // 对话来源
  15. ChatType ChatType `gorm:"type:tinyint(1);default:1;comment:'类型:1问, 2答'" json:"chat_type"` // 状态
  16. ParentContent uint `gorm:"default:0;comment:'父消息编号(编号为0时表示为首条)'" json:"parent_content"`
  17. Content string `gorm:"type:varchar(128);comment:'内容'" json:"content"` // 问题或回答的内容
  18. }
  19. // 需要考虑下如何处理一个完整对话的问题
  20. // 如果是单聊,那么就记录上下两句就好了
  21. // 如果是串聊,则需要知道哪条是第一条,并依次往下记录
  22. // Add 添加资源
  23. func (c Chat) Add() (uint, error) {
  24. err := DB.Create(&c).Error
  25. return c.ID, err
  26. }
  27. // Find 获取单个资源
  28. func (c Chat) Find(filter map[string]interface{}, data *Chat) error {
  29. return DB.Where(filter).First(&data).Error
  30. }
  31. type ChatListReq struct {
  32. Username string `json:"username" form:"username"`
  33. Source string `json:"source" form:"source"`
  34. }
  35. // List 获取数据列表
  36. func (c Chat) List(req ChatListReq) ([]*Chat, error) {
  37. var list []*Chat
  38. db := DB.Model(&Chat{}).Order("created_at ASC")
  39. userName := strings.TrimSpace(req.Username)
  40. if userName != "" {
  41. db = db.Where("username = ?", fmt.Sprintf("%%%s%%", userName))
  42. }
  43. source := strings.TrimSpace(req.Source)
  44. if source != "" {
  45. db = db.Where("source = ?", fmt.Sprintf("%%%s%%", source))
  46. }
  47. err := db.Find(&list).Error
  48. return list, err
  49. }
  50. // Exist 判断资源是否存在
  51. func (c Chat) Exist(filter map[string]interface{}) bool {
  52. var dataObj Chat
  53. err := DB.Where(filter).First(&dataObj).Error
  54. return !errors.Is(err, gorm.ErrRecordNotFound)
  55. }