-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
232 lines (196 loc) · 6.64 KB
/
main.go
File metadata and controls
232 lines (196 loc) · 6.64 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
package main
import (
"context"
"encoding/json"
"fmt"
"net/http"
"strconv"
"time"
"github.com/aws/aws-lambda-go/events"
"github.com/aws/aws-lambda-go/lambda"
)
// Define the base URL as a constant
const baseURL = "https://api.mfapi.in/mf/"
// Define a Fund struct to match the API response structure
type Fund struct {
Meta struct {
FundHouse string `json:"fund_house"`
SchemeType string `json:"scheme_type"`
SchemeCategory string `json:"scheme_category"`
SchemeCode int `json:"scheme_code"`
SchemeName string `json:"scheme_name"`
} `json:"meta"`
Data []struct {
Date string `json:"date"`
Nav string `json:"nav"`
} `json:"data"`
}
// Define a Response struct for the API response
type Response struct {
Meta struct {
FundHouse string `json:"fund_house"`
SchemeType string `json:"scheme_type"`
SchemeCategory string `json:"scheme_category"`
SchemeCode int `json:"scheme_code"`
SchemeName string `json:"scheme_name"`
} `json:"meta"`
Period string `json:"period,omitempty"`
Data []DataPoint `json:"data"`
}
// Define a DataPoint struct for individual data points
type DataPoint struct {
Date string `json:"date"`
Nav string `json:"nav"`
}
// Handler function to process the API Gateway request
func Handler(ctx context.Context, request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
// Fetch query parameters
mutualFundID := request.QueryStringParameters["mutualFundID"]
startDate := request.QueryStringParameters["start"]
endDate := request.QueryStringParameters["end"]
// Check if mutualFundID is provided and is a valid integer
if mutualFundID == "" {
return createErrorResponse(400, "mutualFundID query parameter is required")
}
if !isValidInteger(mutualFundID) {
return createErrorResponse(400, "mutualFundID must be an integer")
}
// Validate and parse dates
start, end, err := validateAndParseDates(startDate, endDate)
if err != nil {
return createErrorResponse(400, err.Error())
}
// Fetch fund data from API
fund, err := fetchFundData(mutualFundID)
if err != nil {
return createErrorResponse(500, err.Error())
}
// Check if the meta field is empty, indicating an invalid mutualFundID
if fund.Meta == (struct {
FundHouse string `json:"fund_house"`
SchemeType string `json:"scheme_type"`
SchemeCategory string `json:"scheme_category"`
SchemeCode int `json:"scheme_code"`
SchemeName string `json:"scheme_name"`
}{}) {
return createErrorResponse(400, "Invalid mutualFundID")
}
// Filter data based on date range
filteredData := filterData(fund.Data, start, end)
// Create a success response
response := createSuccessResponse(fund.Meta, filteredData, start, end)
// Marshal the response to JSON
jsonResponse, err := json.Marshal(response)
if err != nil {
return createErrorResponse(500, "error creating JSON response")
}
return events.APIGatewayProxyResponse{
StatusCode: 200,
Body: string(jsonResponse),
Headers: map[string]string{
"Content-Type": "application/json",
},
}, nil
}
// isValidInteger checks if a string can be parsed as an integer.
func isValidInteger(value string) bool {
_, err := strconv.Atoi(value)
return err == nil
}
// fetchFundData fetches the fund data from the API using the mutualFundID.
func fetchFundData(mutualFundID string) (Fund, error) {
var fund Fund
url := fmt.Sprintf("%s%s", baseURL, mutualFundID)
resp, err := http.Get(url)
if err != nil {
return fund, fmt.Errorf("error fetching data from API: %w", err)
}
defer resp.Body.Close()
if err := json.NewDecoder(resp.Body).Decode(&fund); err != nil {
return fund, fmt.Errorf("error decoding API response: %w", err)
}
return fund, nil
}
// validateAndParseDates validates and parses the date strings from the query parameters.
func validateAndParseDates(startDate, endDate string) (time.Time, time.Time, error) {
var start, end time.Time
var err error
if startDate != "" && endDate != "" {
start, end, err = parseDates(startDate, endDate)
if err != nil {
return time.Time{}, time.Time{}, err
}
if end.After(time.Now()) {
return time.Time{}, time.Time{}, fmt.Errorf("end date cannot be in the future")
}
if start.After(end) {
return time.Time{}, time.Time{}, fmt.Errorf("start date cannot be after end date")
}
} else if startDate == "" && endDate == "" {
// No dates provided, return all data
start, end = time.Time{}, time.Time{}
} else {
// Only one of the dates provided
return time.Time{}, time.Time{}, fmt.Errorf("both start and end dates are required in the format dd-mm-yyyy")
}
return start, end, nil
}
// parseDates parses the start and end date strings into time.Time objects.
func parseDates(startDate, endDate string) (time.Time, time.Time, error) {
start, err := time.Parse("02-01-2006", startDate)
if err != nil {
return time.Time{}, time.Time{}, fmt.Errorf("invalid start date format. use dd-mm-yyyy")
}
end, err := time.Parse("02-01-2006", endDate)
if err != nil {
return time.Time{}, time.Time{}, fmt.Errorf("invalid end date format. use dd-mm-yyyy")
}
return start, end, nil
}
// filterData filters the data based on the provided date range.
func filterData(data []struct {
Date string `json:"date"`
Nav string `json:"nav"`
}, start, end time.Time) []DataPoint {
var filteredData []DataPoint
for _, item := range data {
date, err := time.Parse("02-01-2006", item.Date)
if err != nil {
continue
}
if (start.IsZero() && end.IsZero()) || (date.Equal(start) || date.After(start)) && (date.Equal(end) || date.Before(end)) {
filteredData = append(filteredData, DataPoint{Date: item.Date, Nav: item.Nav})
}
}
return filteredData
}
// createSuccessResponse creates a successful response with the given data and period.
func createSuccessResponse(meta struct {
FundHouse string `json:"fund_house"`
SchemeType string `json:"scheme_type"`
SchemeCategory string `json:"scheme_category"`
SchemeCode int `json:"scheme_code"`
SchemeName string `json:"scheme_name"`
}, data []DataPoint, start, end time.Time) Response {
response := Response{
Meta: meta,
Data: data,
}
if !start.IsZero() && !end.IsZero() {
response.Period = fmt.Sprintf("%s to %s", start.Format("02-01-2006"), end.Format("02-01-2006"))
}
return response
}
// createErrorResponse creates an error response with the given status code and message.
func createErrorResponse(statusCode int, message string) (events.APIGatewayProxyResponse, error) {
return events.APIGatewayProxyResponse{
StatusCode: statusCode,
Body: fmt.Sprintf(`{"error": "%s"}`, message),
Headers: map[string]string{
"Content-Type": "application/json",
},
}, nil
}
func main() {
lambda.Start(Handler)
}