65 lines
1.4 KiB
Go
65 lines
1.4 KiB
Go
package repository
|
|
|
|
import (
|
|
"context"
|
|
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
|
|
"shop/internal/models"
|
|
)
|
|
|
|
type ProductRepository struct {
|
|
pool *pgxpool.Pool
|
|
}
|
|
|
|
func NewProductRepository(pool *pgxpool.Pool) *ProductRepository {
|
|
return &ProductRepository{pool: pool}
|
|
}
|
|
|
|
func (r *ProductRepository) Featured(ctx context.Context, limit int) ([]models.Product, error) {
|
|
rows, err := r.pool.Query(ctx, `
|
|
SELECT id, name, description, price, image_url, category, created_at
|
|
FROM products
|
|
ORDER BY created_at DESC
|
|
LIMIT $1
|
|
`, limit)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
|
|
var products []models.Product
|
|
for rows.Next() {
|
|
var p models.Product
|
|
if err := rows.Scan(&p.ID, &p.Name, &p.Description, &p.Price, &p.ImageURL, &p.Category, &p.CreatedAt); err != nil {
|
|
return nil, err
|
|
}
|
|
products = append(products, p)
|
|
}
|
|
return products, rows.Err()
|
|
}
|
|
|
|
func (r *ProductRepository) Categories(ctx context.Context) ([]models.Category, error) {
|
|
rows, err := r.pool.Query(ctx, `
|
|
SELECT category, COUNT(*) AS cnt
|
|
FROM products
|
|
GROUP BY category
|
|
ORDER BY cnt DESC
|
|
`)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
|
|
var categories []models.Category
|
|
for rows.Next() {
|
|
var c models.Category
|
|
if err := rows.Scan(&c.Name, &c.Count); err != nil {
|
|
return nil, err
|
|
}
|
|
c.Slug = c.Name
|
|
categories = append(categories, c)
|
|
}
|
|
return categories, rows.Err()
|
|
}
|