add create waste route
continuous-integration/drone/push Build is passing

This commit is contained in:
2024-11-25 16:38:03 +07:00
parent 675c2884b7
commit 26ca649e8e
7 changed files with 112 additions and 8 deletions
@@ -41,3 +41,25 @@ func (s *CategoryService) AddCategory(ctx context.Context, category *CategoryEnt
}
return category, nil
}
func (s *CategoryService) GetCategory(ctx context.Context, categoryId int) (*CategoryEntity, error) {
query := `SELECT id, name, budget_id, favorite, monthly_limit FROM categories WHERE id = @id`
args := pgx.NamedArgs{
"id": categoryId,
}
rows, err := s.db.Query(ctx, query, args)
if err != nil {
return nil, err
}
categories := []*CategoryEntity{}
defer rows.Close()
for rows.Next() {
category := &CategoryEntity{}
err = rows.Scan(&category.Id, &category.Name, &category.BudgetId, &category.Favorite, &category.MonthlyLimit)
if err != nil {
return nil, err
}
categories = append(categories, category)
}
return categories[0], nil
}
File diff suppressed because one or more lines are too long
+54
View File
@@ -0,0 +1,54 @@
package waste
import (
"context"
"fmt"
"git.3crabs.ru/save_my_money/smm_core/internal/services/category"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
)
type WasteEntity struct {
Id int
Name string
Price int
Amount float32
BudgetId int
CategoryId int
}
type WasteService struct {
db *pgxpool.Pool
categoryService *category.CategoryService
}
func NewWasteService(
db *pgxpool.Pool,
categoryService *category.CategoryService,
) *WasteService {
return &WasteService{
db: db,
categoryService: categoryService,
}
}
func (s *WasteService) AddWaste(ctx context.Context, waste *WasteEntity) (*WasteEntity, error) {
category, err := s.categoryService.GetCategory(ctx, waste.CategoryId)
if err != nil {
return nil, err
}
query := `INSERT INTO wastes (name, price, amount, budget_id, category_id) VALUES (@name, @price, @amount, @budget_id, @category_id) RETURNING id`
args := pgx.NamedArgs{
"name": waste.Name,
"price": waste.Price,
"amount": waste.Amount,
"budget_id": category.BudgetId,
"category_id": waste.CategoryId,
}
if err := s.db.QueryRow(ctx, query, args).Scan(&waste.Id); err != nil {
return nil, fmt.Errorf("unable to insert row: %w", err)
}
return waste, nil
}