package models import ( "bytes" "encoding/gob" "fmt" "git.capotej.com/capotej/communique/config" "github.com/dgraph-io/badger/v3" ) type Avatar struct { Handler config.Handler ContentType string Bytes []byte } // used for lookup purposes (count, collect, find) func NewAvatar(h config.Handler) *Avatar { aso := &Avatar{Handler: h} return aso } func CreateAvatar(h config.Handler, contentType string, bytes []byte) (*Avatar, error) { aso := &Avatar{ Handler: h, ContentType: contentType, Bytes: bytes, } return aso, nil } func (a *Avatar) Name() string { return "Avatar" } func (a *Avatar) Key() string { keyBase := fmt.Sprintf("avatars:%s", a.Handler.Name) return keyBase } func (a *Avatar) DedupKey() string { return a.Key() } func (a *Avatar) Keybase() string { return a.Key() } func (a *Avatar) SaveDedup(txn *badger.Txn) error { txn.Discard() // nothing to do here return nil } func (a *Avatar) Save(txn *badger.Txn) error { if a.Bytes == nil { return fmt.Errorf("bytes not set") } if a.ContentType == "" { return fmt.Errorf("content type not set") } var network bytes.Buffer enc := gob.NewEncoder(&network) err := enc.Encode(a) if err != nil { return fmt.Errorf("could not encode Avatar: %w", err) } e := badger.NewEntry([]byte(a.Key()), network.Bytes()) return txn.SetEntry(e) }