generated from tsivinsky/go-template
64 lines
1.3 KiB
Go
64 lines
1.3 KiB
Go
package model
|
|
|
|
import (
|
|
"fmt"
|
|
"time"
|
|
|
|
"github.com/google/uuid"
|
|
"github.com/jmoiron/sqlx"
|
|
)
|
|
|
|
type Image struct {
|
|
// uuid
|
|
ID string `json:"id" db:"id"`
|
|
Data []byte `json:"-" db:"data"`
|
|
ContentType string `json:"contentType" db:"content_type"`
|
|
UserID int64 `json:"userId" db:"user_id"`
|
|
CreatedAt time.Time `json:"createdAt" db:"created_at"`
|
|
UpdatedAt time.Time `json:"updatedAt" db:"updated_at"`
|
|
}
|
|
|
|
func (img *Image) Create(db *sqlx.DB) error {
|
|
if img.ID == "" {
|
|
uid, err := uuid.NewV7()
|
|
if err != nil {
|
|
return fmt.Errorf("failed to generate uuid: %v", err)
|
|
}
|
|
img.ID = uid.String()
|
|
}
|
|
|
|
_, err := db.NamedExec("INSERT INTO images (id, data, user_id, content_type) VALUES (:id, :data, :user_id, :content_type)", map[string]any{
|
|
"id": img.ID,
|
|
"data": img.Data,
|
|
"user_id": img.UserID,
|
|
"content_type": img.ContentType,
|
|
})
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func (img *Image) FindByID(db *sqlx.DB) error {
|
|
row := db.QueryRowx("SELECT * FROM images WHERE id = ?", img.ID)
|
|
if row.Err() != nil {
|
|
return row.Err()
|
|
}
|
|
|
|
if err := row.StructScan(img); err != nil {
|
|
return err
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func (img *Image) DeleteByID(db *sqlx.DB) error {
|
|
_, err := db.Exec("DELETE FROM images WHERE id = ?", img.ID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
return nil
|
|
}
|