package Database import ( "database/sql" "time" "github.com/gofrs/uuid" "gorm.io/gorm" "gorm.io/gorm/clause" ) // Message holds data pertaining to each users' message type Message struct { Base MessageDataID uuid.UUID ` json:"message_data_id"` MessageData MessageData ` json:"message_data"` SymmetricKey string `gorm:"not null" json:"symmetric_key"` // Stored encrypted AssociationKey string `gorm:"not null" json:"association_key"` // Stored encrypted ExpiryRaw string ` json:"expiry"` Expiry sql.NullTime ` json:"-"` CreatedAt time.Time `gorm:"not null" json:"created_at"` } type MessageList []Message // GetMessageByID gets a message func GetMessageByID(id string) (Message, error) { var ( message Message err error ) err = DB.Preload(clause.Associations). First(&message, "id = ?", id). Error return message, err } // GetMessagesByAssociationKey for getting whole thread func GetMessagesByAssociationKey(associationKey string, page int) ([]Message, error) { var ( messages []Message offset int err error ) offset = page * PageSize err = DB.Preload("MessageData"). Preload("MessageData.Attachment"). Offset(offset). Limit(PageSize). Order("created_at DESC"). Find(&messages, "association_key = ?", associationKey). Error return messages, err } // CreateMessage creates a message record func (message *Message) CreateMessage() error { var err error err = DB.Session(&gorm.Session{FullSaveAssociations: true}). Create(message). Error return err } // CreateMessages creates multiple records func (messages *MessageList) CreateMessages() error { var err error err = DB.Session(&gorm.Session{FullSaveAssociations: true}). Create(messages). Error return err } // DeleteMessage deletes a message func (message *Message) DeleteMessage() error { return DB.Session(&gorm.Session{FullSaveAssociations: true}). Delete(message). Error }