coller/src/server/note.go
Julien Riou ef9aca1f3b
Initial commit
Signed-off-by: Julien Riou <julien@riou.xyz>
2025-08-21 16:22:03 +02:00

56 lines
1.2 KiB
Go

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(tx *gorm.DB) (err error) {
for i := 0; i < ID_MAX_RETRIES; i++ {
if n.ID != "" {
continue
}
id := internal.GenerateChars(idLength)
var note *Note
tx.Where("id = ?", id).Scan(&note)
// TODO: time=2025-08-21T09:20:31.342+02:00 level=ERROR msg="could not create note" error="UNIQUE constraint failed: notes.id"
if note == nil {
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
}