package server import ( "fmt" "time" "git.riou.xyz/jriou/coller/internal" "gorm.io/gorm" ) const ID_MAX_RETRIES = 10 var idLength = 5 type Note struct { ID string `json:"id" gorm:"primaryKey"` Content []byte `json:"content" gorm:"not null"` Encrypted bool `json:"encrypted"` ExpiresAt time.Time `json:"expires_at" gorm:"index"` DeleteAfterRead bool `json:"delete_after_read"` } // Generate ID and compress content before saving to the database func (n *Note) BeforeCreate(trx *gorm.DB) (err error) { for i := 0; i < ID_MAX_RETRIES; i++ { if n.ID != "" { continue } id := internal.GenerateChars(idLength) var note Note trx.Where("id = ?", id).Find(¬e) if note.ID == "" { n.ID = id continue } } if n.ID == "" { return fmt.Errorf("could not find unique id before creating the note") } n.Content = Compress(n.Content) return nil } // Decompress content from the database func (n *Note) AfterFind(tx *gorm.DB) (err error) { n.Content, err = Decompress(n.Content) if err != nil { return err } return nil }