forked from jriou/coller
Initial commit
Signed-off-by: Julien Riou <julien@riou.xyz>
This commit is contained in:
commit
ef9aca1f3b
26 changed files with 1668 additions and 0 deletions
56
src/server/note.go
Normal file
56
src/server/note.go
Normal file
|
@ -0,0 +1,56 @@
|
|||
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(¬e)
|
||||
|
||||
// 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
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue