Generete Module Handler

This commit is contained in:
2025-08-15 15:07:38 +07:00
parent a64cbf4438
commit 66f6d0a83b
24 changed files with 1977 additions and 2369 deletions

View File

@@ -0,0 +1,131 @@
package product
import (
"context"
"database/sql"
model "api-service/internal/models/product"
)
// Repository defines the interface for product data operations
type Repository interface {
Create(ctx context.Context, product *model.Product) error
GetByID(ctx context.Context, id string) (*model.Product, error)
GetAll(ctx context.Context) ([]*model.Product, error)
Update(ctx context.Context, product *model.Product) error
Delete(ctx context.Context, id string) error
}
// repository implements the Repository interface
type repository struct {
db *sql.DB
}
// NewRepository creates a new product repository
func NewRepository(db *sql.DB) Repository {
return &repository{db: db}
}
// Create adds a new product to the database
func (r *repository) Create(ctx context.Context, product *model.Product) error {
query := `
INSERT INTO products (id, name, description, price, created_at, updated_at)
VALUES (?, ?, ?, ?, ?, ?)
`
_, err := r.db.ExecContext(ctx, query,
product.ID,
product.Name,
product.Description,
product.Price,
product.CreatedAt,
product.UpdatedAt,
)
return err
}
// GetByID retrieves a product by its ID
func (r *repository) GetByID(ctx context.Context, id string) (*model.Product, error) {
query := `
SELECT id, name, description, price, created_at, updated_at
FROM products
WHERE id = ?
`
var product model.Product
err := r.db.QueryRowContext(ctx, query, id).Scan(
&product.ID,
&product.Name,
&product.Description,
&product.Price,
&product.CreatedAt,
&product.UpdatedAt,
)
if err != nil {
return nil, err
}
return &product, nil
}
// GetAll retrieves all products
func (r *repository) GetAll(ctx context.Context) ([]*model.Product, error) {
query := `
SELECT id, name, description, price, created_at, updated_at
FROM products
ORDER BY created_at DESC
`
rows, err := r.db.QueryContext(ctx, query)
if err != nil {
return nil, err
}
defer rows.Close()
var products []*model.Product
for rows.Next() {
var product model.Product
err := rows.Scan(
&product.ID,
&product.Name,
&product.Description,
&product.Price,
&product.CreatedAt,
&product.UpdatedAt,
)
if err != nil {
return nil, err
}
products = append(products, &product)
}
return products, nil
}
// Update updates an existing product
func (r *repository) Update(ctx context.Context, product *model.Product) error {
query := `
UPDATE products
SET name = ?, description = ?, price = ?, updated_at = ?
WHERE id = ?
`
_, err := r.db.ExecContext(ctx, query,
product.Name,
product.Description,
product.Price,
product.UpdatedAt,
product.ID,
)
return err
}
// Delete removes a product from the database
func (r *repository) Delete(ctx context.Context, id string) error {
query := `DELETE FROM products WHERE id = ?`
_, err := r.db.ExecContext(ctx, query, id)
return err
}