"time"
"jsdaj.tq/pf/pkg/core"
+ "jsdaj.tq/pf/pkg/util"
)
func (p *InmemoryPersistence) IngredientCreate(in core.Ingredient) (core.Ingredient, error) {
}
func (p *InmemoryPersistence) IngredientDeactivate(id int) error {
+ if id < 1 || id > len(p.ingredients) {
+ return nil
+ }
+
+ now := time.Now()
+ p.ingredients[id-1].DeletedAt = &now
+
return nil
}
if id < 1 || id > len(p.ingredients) {
return nil, nil
}
- return &p.ingredients[id-1], nil
+
+ ingredient := p.ingredients[id-1]
+ if ingredient.DeletedAt != nil {
+ return nil, nil
+ }
+
+ return &ingredient, nil
}
func (p *InmemoryPersistence) IngredientGetByName(name string) (*core.Ingredient, error) {
for _, in := range p.ingredients {
- if in.Name == name {
+ if in.Name == name && in.DeletedAt == nil {
return &in, nil
}
}
}
func (p *InmemoryPersistence) IngredientList() ([]core.Ingredient, error) {
- return p.ingredients, nil
+ filtered := util.Filter(p.ingredients, func(i core.Ingredient) bool { return i.DeletedAt == nil })
+
+ return filtered, nil
}
Name string `json:"name"`
Quantity int `json:"quantity"`
Description string `json:"description"`
- CreatedAt *time.Time `json:"createdAt,omitempty"`
+ CreatedAt *time.Time `json:"-"`
+ DeletedAt *time.Time `json:"-"`
}
func (ingredient Ingredient) IsValid() error {
util.ParseAndWriteResponse(w, ingredient, shttp.StatusOK)
}
-func (s *Server) ingredientHandleDelete(w shttp.ResponseWriter, r *shttp.Request) {}
+func (s *Server) ingredientHandleDelete(w shttp.ResponseWriter, r *shttp.Request) {
+ id, err := strconv.Atoi(r.PathValue("id"))
+ if err != nil {
+ util.HandleServiceError(w, errors.MapError(serrors.New("bad_id")))
+ return
+ }
+
+ err = s.ingredients.Delete(id)
+ if err != nil {
+ util.HandleServiceError(w, err)
+ return
+ }
+
+ util.ParseAndWriteResponse(w, struct{}{}, shttp.StatusNoContent)
+}
func (s *Server) ingredientHandleGet(w shttp.ResponseWriter, r *shttp.Request) {}
func (s *Ingredient) List() ([]core.Ingredient, error) {
ingredients, err := s.repository.IngredientList()
if err != nil {
- return []core.Ingredient{}, err
+ return []core.Ingredient{}, errors.MapError(err)
}
return ingredients, nil
}
+func (s *Ingredient) Delete(id int) error {
+ in, err := s.repository.IngredientGet(id)
+ if err != nil {
+ return errors.MapError(err)
+ }
+
+ if in == nil {
+ return errors.Error{Code: errors.NotFoundError, Message: "not_found"}
+ }
+
+ err = s.repository.IngredientDeactivate(id)
+ return err
+}
+
func InitIngredientService(repository persistence.IngredientRepository) Ingredient {
return Ingredient{
repository,
--- /dev/null
+package util
+
+type FilterFunc[T any] func(T) bool
+
+func Filter[T any](slic []T, f FilterFunc[T]) []T {
+ result := []T{}
+
+ for _, s := range slic {
+ if f(s) {
+ result = append(result, s)
+ }
+ }
+
+ return result
+}