coller/src/server/note.go
Julien Riou 7d7614637b
All checks were successful
/ pre-commit (push) Successful in 1m8s
Several fixes and features
- Commit database transactions
- Listen to all interfaces by default
- Use logger in collerd
- Add docker-compose file with PostgreSQL

Signed-off-by: Julien Riou <julien@riou.xyz>
2025-08-26 12:30:41 +02:00

55 lines
1.1 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(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(&note)
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
}