51 lines
1018 B
Go
51 lines
1018 B
Go
|
|
package repository
|
||
|
|
|
||
|
|
import (
|
||
|
|
"context"
|
||
|
|
"database/sql"
|
||
|
|
"fmt"
|
||
|
|
"strings"
|
||
|
|
|
||
|
|
"github.com/luxsin/app-api/internal/model"
|
||
|
|
)
|
||
|
|
|
||
|
|
type BrandRepository struct {
|
||
|
|
db *sql.DB
|
||
|
|
}
|
||
|
|
|
||
|
|
func NewBrandRepository(db *sql.DB) *BrandRepository {
|
||
|
|
return &BrandRepository{db: db}
|
||
|
|
}
|
||
|
|
|
||
|
|
func (r *BrandRepository) List(ctx context.Context, brandName string) ([]model.Brand, error) {
|
||
|
|
query := "SELECT id, name FROM brand"
|
||
|
|
args := []any{}
|
||
|
|
|
||
|
|
if strings.TrimSpace(brandName) != "" {
|
||
|
|
query += " WHERE name LIKE ?"
|
||
|
|
args = append(args, "%"+brandName+"%")
|
||
|
|
}
|
||
|
|
|
||
|
|
query += " ORDER BY name ASC"
|
||
|
|
|
||
|
|
rows, err := r.db.QueryContext(ctx, query, args...)
|
||
|
|
if err != nil {
|
||
|
|
return nil, fmt.Errorf("query brand: %w", err)
|
||
|
|
}
|
||
|
|
defer rows.Close()
|
||
|
|
|
||
|
|
list := make([]model.Brand, 0)
|
||
|
|
for rows.Next() {
|
||
|
|
var b model.Brand
|
||
|
|
if err := rows.Scan(&b.ID, &b.Name); err != nil {
|
||
|
|
return nil, fmt.Errorf("scan brand: %w", err)
|
||
|
|
}
|
||
|
|
list = append(list, b)
|
||
|
|
}
|
||
|
|
if err := rows.Err(); err != nil {
|
||
|
|
return nil, fmt.Errorf("iterate brand: %w", err)
|
||
|
|
}
|
||
|
|
|
||
|
|
return list, nil
|
||
|
|
}
|