81 lines
1.8 KiB
Go
81 lines
1.8 KiB
Go
package registry
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
|
|
"reanimator/internal/domain"
|
|
"reanimator/internal/idgen"
|
|
)
|
|
|
|
type CustomerRepository struct {
|
|
db *sql.DB
|
|
idgen *idgen.Generator
|
|
}
|
|
|
|
func NewCustomerRepository(db *sql.DB) *CustomerRepository {
|
|
return &CustomerRepository{
|
|
db: db,
|
|
idgen: idgen.NewGenerator(db),
|
|
}
|
|
}
|
|
|
|
func (r *CustomerRepository) Create(ctx context.Context, name string) (domain.Customer, error) {
|
|
// Generate string ID
|
|
id, err := r.idgen.Generate(ctx, idgen.Customer)
|
|
if err != nil {
|
|
return domain.Customer{}, err
|
|
}
|
|
|
|
_, err = r.db.ExecContext(ctx,
|
|
`INSERT INTO customers (id, name) VALUES (?, ?)`,
|
|
id, name,
|
|
)
|
|
if err != nil {
|
|
return domain.Customer{}, classifyError(err)
|
|
}
|
|
|
|
return r.Get(ctx, id)
|
|
}
|
|
|
|
func (r *CustomerRepository) Get(ctx context.Context, id string) (domain.Customer, error) {
|
|
var customer domain.Customer
|
|
|
|
row := r.db.QueryRowContext(ctx,
|
|
`SELECT id, name, created_at, updated_at FROM customers WHERE id = ?`,
|
|
id,
|
|
)
|
|
if err := row.Scan(&customer.ID, &customer.Name, &customer.CreatedAt, &customer.UpdatedAt); err != nil {
|
|
if err == sql.ErrNoRows {
|
|
return domain.Customer{}, ErrNotFound
|
|
}
|
|
return domain.Customer{}, err
|
|
}
|
|
|
|
return customer, nil
|
|
}
|
|
|
|
func (r *CustomerRepository) List(ctx context.Context) ([]domain.Customer, error) {
|
|
rows, err := r.db.QueryContext(ctx,
|
|
`SELECT id, name, created_at, updated_at FROM customers ORDER BY created_at DESC`,
|
|
)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
|
|
customers := make([]domain.Customer, 0)
|
|
for rows.Next() {
|
|
var customer domain.Customer
|
|
if err := rows.Scan(&customer.ID, &customer.Name, &customer.CreatedAt, &customer.UpdatedAt); err != nil {
|
|
return nil, err
|
|
}
|
|
customers = append(customers, customer)
|
|
}
|
|
if err := rows.Err(); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return customers, nil
|
|
}
|