owl-blogs/infra/binary_file_repository.go

53 lines
1.2 KiB
Go
Raw Normal View History

2023-07-08 09:08:55 +00:00
package infra
import (
2023-07-08 10:03:10 +00:00
"owl-blogs/app/repository"
2023-07-08 09:08:55 +00:00
"owl-blogs/domain/model"
"github.com/google/uuid"
"github.com/jmoiron/sqlx"
)
type sqlBinaryFile struct {
Id string `db:"id"`
Name string `db:"name"`
Data []byte `db:"data"`
}
type DefaultBinaryFileRepo struct {
db *sqlx.DB
}
2023-07-08 10:03:10 +00:00
func NewBinaryFileRepo(db Database) repository.BinaryRepository {
2023-07-08 09:08:55 +00:00
sqlxdb := db.Get()
// Create table if not exists
sqlxdb.MustExec(`
CREATE TABLE IF NOT EXISTS binary_files (
id VARCHAR(255) PRIMARY KEY,
name VARCHAR(255) NOT NULL,
data BLOB NOT NULL
);
`)
return &DefaultBinaryFileRepo{db: sqlxdb}
}
func (repo *DefaultBinaryFileRepo) Create(name string, data []byte) (*model.BinaryFile, error) {
id := uuid.New().String()
_, err := repo.db.Exec("INSERT INTO binary_files (id, name, data) VALUES (?, ?, ?)", id, name, data)
if err != nil {
return nil, err
}
return &model.BinaryFile{Id: id, Name: name, Data: data}, nil
}
func (repo *DefaultBinaryFileRepo) FindById(id string) (*model.BinaryFile, error) {
var sqlFile sqlBinaryFile
err := repo.db.Get(&sqlFile, "SELECT * FROM binary_files WHERE id = ?", id)
if err != nil {
return nil, err
}
return &model.BinaryFile{Id: sqlFile.Id, Name: sqlFile.Name, Data: sqlFile.Data}, nil
}