github.com/shoshinnikita/budget-manager@v0.7.1-0.20220131195411-8c46ff1c6778/internal/web/api/month.go (about) 1 package api 2 3 import ( 4 "context" 5 "errors" 6 "net/http" 7 "time" 8 9 "github.com/ShoshinNikita/budget-manager/internal/db" 10 "github.com/ShoshinNikita/budget-manager/internal/logger" 11 "github.com/ShoshinNikita/budget-manager/internal/pkg/reqid" 12 "github.com/ShoshinNikita/budget-manager/internal/web/api/models" 13 "github.com/ShoshinNikita/budget-manager/internal/web/utils" 14 ) 15 16 type MonthsHandlers struct { 17 db MonthsDB 18 log logger.Logger 19 } 20 21 type MonthsDB interface { 22 GetMonthByDate(ctx context.Context, year int, month time.Month) (db.Month, error) 23 } 24 25 // @Summary Get Month by date 26 // @Tags Months 27 // @Router /api/months/date [get] 28 // @Param params query models.GetMonthByDateReq true "Date" 29 // @Produce json 30 // @Success 200 {object} models.GetMonthResp 31 // @Failure 400 {object} models.Response "Invalid request" 32 // @Failure 404 {object} models.Response "Month doesn't exist" 33 // @Failure 500 {object} models.Response "Internal error" 34 // 35 func (h MonthsHandlers) GetMonthByDate(w http.ResponseWriter, r *http.Request) { 36 ctx := r.Context() 37 log := reqid.FromContextToLogger(ctx, h.log) 38 39 // Decode 40 req := &models.GetMonthByDateReq{} 41 if ok := utils.DecodeRequest(w, r, log, req); !ok { 42 return 43 } 44 log = log.WithRequest(req) 45 46 // Process 47 month, err := h.db.GetMonthByDate(ctx, req.Year, req.Month) 48 if err != nil { 49 switch { 50 case errors.Is(err, db.ErrMonthNotExist): 51 utils.EncodeError(ctx, w, log, err, http.StatusNotFound) 52 default: 53 utils.EncodeInternalError(ctx, w, log, "couldn't get Month for passed year and month", err) 54 } 55 return 56 } 57 58 resp := &models.GetMonthResp{ 59 Month: month, 60 } 61 utils.Encode(ctx, w, log, utils.EncodeResponse(resp)) 62 }