1+ /*
2+ * Copyright (c) 2024. Devtron Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+
117package utils
218
319import (
@@ -6,9 +22,9 @@ import (
622)
723
824type TimeRangeRequest struct {
9- From * time.Time `json:"from"`
10- To * time.Time `json:"to"`
11- TimeWindow * TimeWindows `json:"timeWindow" validate:"oneof=today yesterday week month quarter lastWeek lastMonth"`
25+ From * time.Time `json:"from" schema:"from" `
26+ To * time.Time `json:"to" schema:"to" `
27+ TimeWindow * TimeWindows `json:"timeWindow" schema:"timeWindow" validate:"omitempty, oneof=today yesterday week month quarter lastWeek lastMonth"`
1228}
1329
1430func NewTimeRangeRequest (from * time.Time , to * time.Time ) * TimeRangeRequest {
@@ -42,9 +58,11 @@ const (
4258 LastMonth TimeWindows = "lastMonth"
4359)
4460
45- func (timeRange * TimeRangeRequest ) ParseTimeRange () (* TimeRangeRequest , error ) {
61+ func (timeRange * TimeRangeRequest ) ParseAndValidateTimeRange () (* TimeRangeRequest , error ) {
62+ if timeRange == nil {
63+ return NewTimeRangeRequest (& time.Time {}, & time.Time {}), fmt .Errorf ("invalid time range request. either from/to or timeWindow must be provided" )
64+ }
4665 now := time .Now ()
47-
4866 // If timeWindow is provided, it takes preference over from/to
4967 if timeRange .TimeWindow != nil {
5068 switch * timeRange .TimeWindow {
@@ -91,7 +109,7 @@ func (timeRange *TimeRangeRequest) ParseTimeRange() (*TimeRangeRequest, error) {
91109 }
92110
93111 // Use from/to dates if provided
94- if timeRange .From != nil && NewTimeRangeRequest ( & time. Time {}, & time. Time {}) != nil {
112+ if timeRange .From != nil && timeRange . To != nil {
95113 if timeRange .From .After (* timeRange .To ) {
96114 return NewTimeRangeRequest (& time.Time {}, & time.Time {}), fmt .Errorf ("from date cannot be after to date" )
97115 }
0 commit comments