From 9c874ea675b50d258567c804effb1badf6580203 Mon Sep 17 00:00:00 2001 From: murtaza896 Date: Sat, 23 Apr 2022 20:25:36 +0530 Subject: [PATCH 01/15] | First Commit | --- gateway/app/app.go | 28 +++++++++++++++++ gateway/app/router.go | 24 +++++++++++++++ gateway/app/userHandler.go | 62 ++++++++++++++++++++++++++++++++++++++ gateway/go.mod | 25 +++++++++++++++ gateway/go.sum | 55 +++++++++++++++++++++++++++++++++ gateway/main.go | 7 +++++ 6 files changed, 201 insertions(+) create mode 100644 gateway/app/app.go create mode 100644 gateway/app/router.go create mode 100644 gateway/app/userHandler.go create mode 100644 gateway/go.mod create mode 100644 gateway/go.sum create mode 100644 gateway/main.go diff --git a/gateway/app/app.go b/gateway/app/app.go new file mode 100644 index 0000000..e27c6ef --- /dev/null +++ b/gateway/app/app.go @@ -0,0 +1,28 @@ +package app + +import "github.com/joho/godotenv" + +import ( + "fmt" + "log" + "os" +) + +func Start() { + RegisterUserRoutes() + err := godotenv.Load(".env") + if err != nil { + log.Fatal(err) + return + } + + if err != nil { + log.Fatalf("Error loading .env file") + } + PORT := os.Getenv("PORT") + + err = Router.Run(fmt.Sprintf(":%s", PORT)) + if err != nil { + return + } +} diff --git a/gateway/app/router.go b/gateway/app/router.go new file mode 100644 index 0000000..cead140 --- /dev/null +++ b/gateway/app/router.go @@ -0,0 +1,24 @@ +package app + +import ( + "github.com/gin-gonic/gin" + //swaggerFiles "github.com/swaggo/files" + //ginSwagger "github.com/swaggo/gin-swagger" + //"github.com/swiggy-2022-bootcamp/cdp-team4/gateway/docs" +) + +var v1 *gin.RouterGroup +var Router *gin.Engine + +func init() { + Router = gin.Default() + api := Router.Group("/api") + v1 = api.Group("/v1") + + //docs.SwaggerInfo.BasePath = "/api/v1" + //Router.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler)) +} + +func RegisterUserRoutes() { + v1.GET("/users") +} diff --git a/gateway/app/userHandler.go b/gateway/app/userHandler.go new file mode 100644 index 0000000..5998b67 --- /dev/null +++ b/gateway/app/userHandler.go @@ -0,0 +1,62 @@ +package app + +import ( + "context" + "encoding/json" + "github.com/gin-gonic/gin" + "log" + "net/http" + "time" +) + +type userHandler struct { +} + +type ResponseDTO struct { + Data interface{} +} + +type authModel struct { + UserId string + Role int +} + +func ValidateToken(authorizationHeader string) authModel { + authServiceUri := "localhost:8881/api/v1/validate" + req, err := http.NewRequest("GET", authServiceUri, nil) + if err != nil { + log.Fatalf("%v", err) + } + + ctx, cancel := context.WithTimeout(req.Context(), 1*time.Millisecond) + defer cancel() + + req = req.WithContext(ctx) + req.Header.Set("Authorization", authorizationHeader) + client := http.DefaultClient + res, err := client.Do(req) + if err != nil { + log.Fatalf("%v", err) + } + + var resDTO ResponseDTO + err = json.NewDecoder(res.Body).Decode(&resDTO) + + if err != nil { + + } + + model := resDTO.Data.(authModel) + + return authModel{ + UserId: model.UserId, + Role: model.Role, + } +} + +func (h userHandler) ValidateAuthToken() gin.HandlerFunc { + return func(c *gin.Context) { + res := ValidateToken(c.Request.Header.Get("Authorization")) + c.JSON(http.StatusOK, res) + } +} diff --git a/gateway/go.mod b/gateway/go.mod new file mode 100644 index 0000000..b93f33a --- /dev/null +++ b/gateway/go.mod @@ -0,0 +1,25 @@ +module github.com/swiggy-2022-bootcamp/cdp-team4/gateway + +go 1.18 + +require ( + github.com/gin-gonic/gin v1.7.7 + github.com/joho/godotenv v1.4.0 +) + +require ( + github.com/gin-contrib/sse v0.1.0 // indirect + github.com/go-playground/locales v0.13.0 // indirect + github.com/go-playground/universal-translator v0.17.0 // indirect + github.com/go-playground/validator/v10 v10.4.1 // indirect + github.com/golang/protobuf v1.3.3 // indirect + github.com/json-iterator/go v1.1.9 // indirect + github.com/leodido/go-urn v1.2.0 // indirect + github.com/mattn/go-isatty v0.0.12 // indirect + github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 // indirect + github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742 // indirect + github.com/ugorji/go/codec v1.1.7 // indirect + golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9 // indirect + golang.org/x/sys v0.0.0-20200116001909-b77594299b42 // indirect + gopkg.in/yaml.v2 v2.2.8 // indirect +) diff --git a/gateway/go.sum b/gateway/go.sum new file mode 100644 index 0000000..1a91c66 --- /dev/null +++ b/gateway/go.sum @@ -0,0 +1,55 @@ +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE= +github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI= +github.com/gin-gonic/gin v1.7.7 h1:3DoBmSbJbZAWqXJC3SLjAPfutPJJRN1U5pALB7EeTTs= +github.com/gin-gonic/gin v1.7.7/go.mod h1:axIBovoeJpVj8S3BwE0uPMTeReE4+AfFtqpqaZ1qq1U= +github.com/go-playground/assert/v2 v2.0.1 h1:MsBgLAaY856+nPRTKrp3/OZK38U/wa0CcBYNjji3q3A= +github.com/go-playground/assert/v2 v2.0.1/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= +github.com/go-playground/locales v0.13.0 h1:HyWk6mgj5qFqCT5fjGBuRArbVDfE4hi8+e8ceBS/t7Q= +github.com/go-playground/locales v0.13.0/go.mod h1:taPMhCMXrRLJO55olJkUXHZBHCxTMfnGwq/HNwmWNS8= +github.com/go-playground/universal-translator v0.17.0 h1:icxd5fm+REJzpZx7ZfpaD876Lmtgy7VtROAbHHXk8no= +github.com/go-playground/universal-translator v0.17.0/go.mod h1:UkSxE5sNxxRwHyU+Scu5vgOQjsIJAF8j9muTVoKLVtA= +github.com/go-playground/validator/v10 v10.4.1 h1:pH2c5ADXtd66mxoE0Zm9SUhxE20r7aM3F26W0hOn+GE= +github.com/go-playground/validator/v10 v10.4.1/go.mod h1:nlOn6nFhuKACm19sB/8EGNn9GlaMV7XkbRSipzJ0Ii4= +github.com/golang/protobuf v1.3.3 h1:gyjaxf+svBWX08ZjK86iN9geUJF0H6gp2IRKX6Nf6/I= +github.com/golang/protobuf v1.3.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw= +github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/joho/godotenv v1.4.0 h1:3l4+N6zfMWnkbPEXKng2o2/MR5mSwTrBih4ZEkkz1lg= +github.com/joho/godotenv v1.4.0/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4= +github.com/json-iterator/go v1.1.9 h1:9yzud/Ht36ygwatGx56VwCZtlI/2AD15T1X2sjSuGns= +github.com/json-iterator/go v1.1.9/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= +github.com/leodido/go-urn v1.2.0 h1:hpXL4XnriNwQ/ABnpepYM/1vCLWNDfUNts8dX3xTG6Y= +github.com/leodido/go-urn v1.2.0/go.mod h1:+8+nEpDfqqsY+g338gtMEUOtuK+4dEMhiQEgxpxOKII= +github.com/mattn/go-isatty v0.0.12 h1:wuysRhFDzyxgEmMf5xjvJ2M9dZoWAXNNr5LSBS7uHXY= +github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU= +github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 h1:ZqeYNhU3OHLH3mGKHDcjJRFFRrJa6eAM5H+CtDdOsPc= +github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742 h1:Esafd1046DLDQ0W1YjYsBW+p8U2u7vzgW2SQVmlNazg= +github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.4.0 h1:2E4SXV/wtOkTonXsotYi4li6zVWxYlZuYNCXe9XRJyk= +github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= +github.com/ugorji/go v1.1.7/go.mod h1:kZn38zHttfInRq0xu/PH0az30d+z6vm202qpg1oXVMw= +github.com/ugorji/go/codec v1.1.7 h1:2SvQaVZ1ouYrrKKwoSk2pzd4A9evlKJb9oTL+OaLUSs= +github.com/ugorji/go/codec v1.1.7/go.mod h1:Ax+UKWsSmolVDwsd+7N3ZtXu+yMGCf907BLYF3GoBXY= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9 h1:psW17arqaxU48Z5kZ0CQnkZWQJsqcURM6tKiBApRjXI= +golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200116001909-b77594299b42 h1:vEOn+mP2zCOVzKckCZy6YsCtDblrpj/w7B9nxGNELpg= +golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.8 h1:obN1ZagJSUGI0Ek/LBmuj4SNLPfIny3KsKFopxRdj10= +gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= diff --git a/gateway/main.go b/gateway/main.go new file mode 100644 index 0000000..cc1f694 --- /dev/null +++ b/gateway/main.go @@ -0,0 +1,7 @@ +package main + +import "github.com/swiggy-2022-bootcamp/cdp-team4/gateway/app" + +func main() { + app.Start() +} From c6d389ccf3675126ebc87e2442c64e92ac324c27 Mon Sep 17 00:00:00 2001 From: murtaza896 Date: Sat, 23 Apr 2022 20:40:37 +0530 Subject: [PATCH 02/15] | Second Commit | --- gateway/.env | 1 + gateway/app/router.go | 3 ++- gateway/app/userHandler.go | 4 ++-- 3 files changed, 5 insertions(+), 3 deletions(-) create mode 100644 gateway/.env diff --git a/gateway/.env b/gateway/.env new file mode 100644 index 0000000..84e2cd8 --- /dev/null +++ b/gateway/.env @@ -0,0 +1 @@ +PORT=8882 \ No newline at end of file diff --git a/gateway/app/router.go b/gateway/app/router.go index cead140..087d1ba 100644 --- a/gateway/app/router.go +++ b/gateway/app/router.go @@ -20,5 +20,6 @@ func init() { } func RegisterUserRoutes() { - v1.GET("/users") + handler := userHandler{} + v1.GET("/users", handler.ValidateAuthToken()) } diff --git a/gateway/app/userHandler.go b/gateway/app/userHandler.go index 5998b67..36adec0 100644 --- a/gateway/app/userHandler.go +++ b/gateway/app/userHandler.go @@ -22,13 +22,13 @@ type authModel struct { } func ValidateToken(authorizationHeader string) authModel { - authServiceUri := "localhost:8881/api/v1/validate" + authServiceUri := "http://localhost:8881/api/v1/validate" req, err := http.NewRequest("GET", authServiceUri, nil) if err != nil { log.Fatalf("%v", err) } - ctx, cancel := context.WithTimeout(req.Context(), 1*time.Millisecond) + ctx, cancel := context.WithTimeout(req.Context(), 1*time.Minute) defer cancel() req = req.WithContext(ctx) From 134468995d93539441c08a8cb595f27e770a15dc Mon Sep 17 00:00:00 2001 From: Swastik Sahoo 8082 Date: Sun, 24 Apr 2022 00:10:06 +0530 Subject: [PATCH 03/15] | Add validate function | --- README.md | 2 - checkout/.gitignore | 17 - checkout/Dockerfile | 17 - checkout/README.md | 1 - checkout/app/app.go | 51 --- checkout/app/healthHandler.go | 21 -- checkout/app/routes.go | 9 - checkout/docs/docs.go | 72 ---- checkout/docs/swagger.json | 48 --- checkout/docs/swagger.yaml | 33 -- checkout/domain/checkout.go | 33 -- checkout/domain/checkout.pb.go | 343 ------------------ checkout/domain/checkout.proto | 26 -- checkout/domain/checkout_grpc.pb.go | 105 ------ checkout/go.mod | 42 --- checkout/go.sum | 245 ------------- checkout/infra/checkoutModel.go | 1 - checkout/infra/logger/logger.go | 43 --- checkout/main.go | 20 - gateway/app/userHandler.go | 17 +- payment/.gitignore | 18 - payment/Dockerfile | 17 - payment/README.md | 3 - payment/app/app.go | 54 --- payment/app/app_test.go | 15 - payment/app/healthHandler.go | 21 -- payment/app/healthHandler_test.go | 20 - payment/app/payHandler.go | 197 ---------- payment/app/payHandler_test.go | 44 --- payment/app/routes.go | 23 -- payment/docs/docs.go | 72 ---- payment/docs/swagger.json | 51 --- payment/docs/swagger.yaml | 35 -- payment/domain/payment.go | 32 -- payment/domain/paymentService.go | 169 --------- payment/domain/paymentService_test.go | 132 ------- payment/go.mod | 53 --- payment/go.sum | 201 ---------- payment/infra/dynamoDB.go | 296 --------------- payment/infra/gokafka/producer.go | 57 --- payment/infra/logger/logger.go | 44 --- payment/infra/paymentModel.go | 29 -- payment/main.go | 20 - .../mocks/domain/PaymentDynamoRepository.go | 187 ---------- payment/mocks/domain/PaymentService.go | 166 --------- user/.gitignore | 17 - user/Dockerfile | 17 - user/app/app.go | 59 --- user/app/healthHandler.go | 21 -- user/app/routes.go | 17 - user/app/userHandler.go | 182 ---------- user/docs/docs.go | 299 --------------- user/docs/swagger.json | 275 -------------- user/docs/swagger.yaml | 181 --------- user/domain/user.go | 78 ---- user/domain/userService.go | 93 ----- user/domain/userService_test.go | 93 ----- user/domain/user_test.go | 212 ----------- user/go.mod | 49 --- user/go.sum | 187 ---------- user/infra/dynamodbRepo.go | 240 ------------ user/infra/dynamodbRepo_test.go | 116 ------ user/infra/userModel.go | 20 - user/main.go | 20 - user/mockRequest/mockRequest.http | 37 -- user/mocks/UserDynamoDBRepository.go | 122 ------- user/utils/errs/errors.go | 63 ---- 67 files changed, 13 insertions(+), 5487 deletions(-) delete mode 100644 README.md delete mode 100644 checkout/.gitignore delete mode 100644 checkout/Dockerfile delete mode 100644 checkout/README.md delete mode 100644 checkout/app/app.go delete mode 100644 checkout/app/healthHandler.go delete mode 100644 checkout/app/routes.go delete mode 100644 checkout/docs/docs.go delete mode 100644 checkout/docs/swagger.json delete mode 100644 checkout/docs/swagger.yaml delete mode 100644 checkout/domain/checkout.go delete mode 100644 checkout/domain/checkout.pb.go delete mode 100644 checkout/domain/checkout.proto delete mode 100644 checkout/domain/checkout_grpc.pb.go delete mode 100644 checkout/go.mod delete mode 100644 checkout/go.sum delete mode 100644 checkout/infra/checkoutModel.go delete mode 100644 checkout/infra/logger/logger.go delete mode 100644 checkout/main.go delete mode 100644 payment/.gitignore delete mode 100644 payment/Dockerfile delete mode 100644 payment/README.md delete mode 100644 payment/app/app.go delete mode 100644 payment/app/app_test.go delete mode 100644 payment/app/healthHandler.go delete mode 100644 payment/app/healthHandler_test.go delete mode 100644 payment/app/payHandler.go delete mode 100644 payment/app/payHandler_test.go delete mode 100644 payment/app/routes.go delete mode 100644 payment/docs/docs.go delete mode 100644 payment/docs/swagger.json delete mode 100644 payment/docs/swagger.yaml delete mode 100644 payment/domain/payment.go delete mode 100644 payment/domain/paymentService.go delete mode 100644 payment/domain/paymentService_test.go delete mode 100644 payment/go.mod delete mode 100644 payment/go.sum delete mode 100644 payment/infra/dynamoDB.go delete mode 100644 payment/infra/gokafka/producer.go delete mode 100644 payment/infra/logger/logger.go delete mode 100644 payment/infra/paymentModel.go delete mode 100644 payment/main.go delete mode 100644 payment/mocks/domain/PaymentDynamoRepository.go delete mode 100644 payment/mocks/domain/PaymentService.go delete mode 100644 user/.gitignore delete mode 100644 user/Dockerfile delete mode 100644 user/app/app.go delete mode 100644 user/app/healthHandler.go delete mode 100644 user/app/routes.go delete mode 100644 user/app/userHandler.go delete mode 100644 user/docs/docs.go delete mode 100644 user/docs/swagger.json delete mode 100644 user/docs/swagger.yaml delete mode 100644 user/domain/user.go delete mode 100644 user/domain/userService.go delete mode 100644 user/domain/userService_test.go delete mode 100644 user/domain/user_test.go delete mode 100644 user/go.mod delete mode 100644 user/go.sum delete mode 100644 user/infra/dynamodbRepo.go delete mode 100644 user/infra/dynamodbRepo_test.go delete mode 100644 user/infra/userModel.go delete mode 100644 user/main.go delete mode 100644 user/mockRequest/mockRequest.http delete mode 100644 user/mocks/UserDynamoDBRepository.go delete mode 100644 user/utils/errs/errors.go diff --git a/README.md b/README.md deleted file mode 100644 index c554844..0000000 --- a/README.md +++ /dev/null @@ -1,2 +0,0 @@ -# cdp-team4 -2022-Capability Dev Program-Team4 diff --git a/checkout/.gitignore b/checkout/.gitignore deleted file mode 100644 index 4bf8519..0000000 --- a/checkout/.gitignore +++ /dev/null @@ -1,17 +0,0 @@ -# Binaries for programs and plugins -*.exe -*.exe~ -*.dll -*.so -*.dylib - -# Test binary, built with `go test -c` -*.test - -# Output of the go coverage tool, specifically when used with LiteIDE -*.out - -# Dependency directories (remove the comment below to include it) -# vendor/ - -.env \ No newline at end of file diff --git a/checkout/Dockerfile b/checkout/Dockerfile deleted file mode 100644 index d9cefd5..0000000 --- a/checkout/Dockerfile +++ /dev/null @@ -1,17 +0,0 @@ -FROM golang:1.17-alpine - -RUN apk update && apk add --no-cache git build-base - -WORKDIR /go/github.com/swiggy-2022-bootcamp/cdp-team4/Checkout - -COPY . /go/github.com/swiggy-2022-bootcamp/cdp-team4/Checkout - -# get all the dependencies -RUN go get ./... - -# build -RUN go build -o /CheckoutService - -EXPOSE 8081 - -CMD [ "/CheckoutService" ] diff --git a/checkout/README.md b/checkout/README.md deleted file mode 100644 index b55864f..0000000 --- a/checkout/README.md +++ /dev/null @@ -1 +0,0 @@ -# Checkout Service diff --git a/checkout/app/app.go b/checkout/app/app.go deleted file mode 100644 index af53e95..0000000 --- a/checkout/app/app.go +++ /dev/null @@ -1,51 +0,0 @@ -package app - -import ( - "fmt" - "net" - "os" - - "google.golang.org/grpc" - "google.golang.org/grpc/reflection" - - "github.com/joho/godotenv" - "github.com/sirupsen/logrus" - "github.com/swiggy-2022-bootcamp/cdp-team4/checkout/domain" - "github.com/swiggy-2022-bootcamp/cdp-team4/checkout/infra/logger" - // gin-swagger middleware -) - -var log logrus.Logger = *logger.GetLogger() - -func setupServer() *grpc.Server { - gs := grpc.NewServer() - cs := domain.NewCheckout() - - domain.RegisterCheckoutServer(gs, cs) - log.Debug("gRPC server registered!") - - reflection.Register(gs) - return gs -} - -// func configureSwaggerDoc() { -// docs.SwaggerInfo.Title = "Swagger Checkout API" -// } - -func Start() { - err := godotenv.Load(".env") - if err != nil { - log.Fatal(err) - return - } - PORT := os.Getenv("PORT") - - gServer := setupServer() - l, err := net.Listen("tcp", ":"+PORT) - if err != nil { - fmt.Print(err) - os.Exit(1) - } - - gServer.Serve(l) -} diff --git a/checkout/app/healthHandler.go b/checkout/app/healthHandler.go deleted file mode 100644 index 01a838a..0000000 --- a/checkout/app/healthHandler.go +++ /dev/null @@ -1,21 +0,0 @@ -package app - -import ( - "net/http" - - "github.com/gin-gonic/gin" -) - -// Health Check -// @Summary Health of checkout service -// @Description use to check whether checkout service is up and running or not -// @Tags Health -// @Produce json -// @Success 200 {object} map[string]interface{} -// @Failure 400 {number} http.StatusBadRequest -// @Router / [get] -func HealthCheck() gin.HandlerFunc { - return func(c *gin.Context) { - c.JSON(http.StatusOK, gin.H{"message": "Service is running"}) - } -} diff --git a/checkout/app/routes.go b/checkout/app/routes.go deleted file mode 100644 index 7e76c74..0000000 --- a/checkout/app/routes.go +++ /dev/null @@ -1,9 +0,0 @@ -package app - -import ( - "github.com/gin-gonic/gin" -) - -func HealthCheckRouter(gin *gin.Engine) { - gin.GET("/", HealthCheck()) -} diff --git a/checkout/docs/docs.go b/checkout/docs/docs.go deleted file mode 100644 index 68bfee2..0000000 --- a/checkout/docs/docs.go +++ /dev/null @@ -1,72 +0,0 @@ -// Package docs GENERATED BY THE COMMAND ABOVE; DO NOT EDIT -// This file was generated by swaggo/swag -package docs - -import "github.com/swaggo/swag" - -const docTemplate = `{ - "schemes": {{ marshal .Schemes }}, - "swagger": "2.0", - "info": { - "description": "{{escape .Description}}", - "title": "{{.Title}}", - "termsOfService": "http://swagger.io/terms/", - "contact": { - "name": "API Support", - "url": "http://www.swagger.io/support", - "email": "support@swagger.io" - }, - "license": { - "name": "Apache 2.0", - "url": "http://www.apache.org/licenses/LICENSE-2.0.html" - }, - "version": "{{.Version}}" - }, - "host": "{{.Host}}", - "basePath": "{{.BasePath}}", - "paths": { - "/": { - "get": { - "description": "use to check whether checkout service is up and running or not", - "produces": [ - "application/json" - ], - "tags": [ - "Health" - ], - "summary": "Health of checkout service", - "responses": { - "200": { - "description": "OK", - "schema": { - "type": "object", - "additionalProperties": true - } - }, - "400": { - "description": "Bad Request", - "schema": { - "type": "number" - } - } - } - } - } - } -}` - -// SwaggerInfo holds exported Swagger Info so clients can modify it -var SwaggerInfo = &swag.Spec{ - Version: "1.0", - Host: "", - BasePath: "/", - Schemes: []string{}, - Title: "Checkout API", - Description: "Checkout Service.", - InfoInstanceName: "swagger", - SwaggerTemplate: docTemplate, -} - -func init() { - swag.Register(SwaggerInfo.InstanceName(), SwaggerInfo) -} diff --git a/checkout/docs/swagger.json b/checkout/docs/swagger.json deleted file mode 100644 index 1d0d012..0000000 --- a/checkout/docs/swagger.json +++ /dev/null @@ -1,48 +0,0 @@ -{ - "swagger": "2.0", - "info": { - "description": "Checkout Service.", - "title": "Checkout API", - "termsOfService": "http://swagger.io/terms/", - "contact": { - "name": "API Support", - "url": "http://www.swagger.io/support", - "email": "support@swagger.io" - }, - "license": { - "name": "Apache 2.0", - "url": "http://www.apache.org/licenses/LICENSE-2.0.html" - }, - "version": "1.0" - }, - "basePath": "/", - "paths": { - "/": { - "get": { - "description": "use to check whether checkout service is up and running or not", - "produces": [ - "application/json" - ], - "tags": [ - "Health" - ], - "summary": "Health of checkout service", - "responses": { - "200": { - "description": "OK", - "schema": { - "type": "object", - "additionalProperties": true - } - }, - "400": { - "description": "Bad Request", - "schema": { - "type": "number" - } - } - } - } - } - } -} \ No newline at end of file diff --git a/checkout/docs/swagger.yaml b/checkout/docs/swagger.yaml deleted file mode 100644 index 5018257..0000000 --- a/checkout/docs/swagger.yaml +++ /dev/null @@ -1,33 +0,0 @@ -basePath: / -info: - contact: - email: support@swagger.io - name: API Support - url: http://www.swagger.io/support - description: Checkout Service. - license: - name: Apache 2.0 - url: http://www.apache.org/licenses/LICENSE-2.0.html - termsOfService: http://swagger.io/terms/ - title: Checkout API - version: "1.0" -paths: - /: - get: - description: use to check whether checkout service is up and running or not - produces: - - application/json - responses: - "200": - description: OK - schema: - additionalProperties: true - type: object - "400": - description: Bad Request - schema: - type: number - summary: Health of checkout service - tags: - - Health -swagger: "2.0" diff --git a/checkout/domain/checkout.go b/checkout/domain/checkout.go deleted file mode 100644 index cf5aaa1..0000000 --- a/checkout/domain/checkout.go +++ /dev/null @@ -1,33 +0,0 @@ -package domain - -import ( - context "context" -) - -type Checkout struct { -} - -func NewCheckout() *Checkout { - return &Checkout{} -} - -func (ch *Checkout) OrderOverview( - ctx context.Context, - rq *OverviewRequest, -) (*OverviewResponse, error) { - // Get the User Cart details by ID [grpc call to Cart service] - // Get the Reward points details by ID [grpc call to Reward service] - // Get the Shipping details by ID [grpc call to Shipping service] - - return &OverviewResponse{ - UserID: rq.GetUserID(), - TotalPrice: 15, - ShippingPrice: 5, - RewardPointsConsumed: 2, - Item: []*OverviewResponse_Item{ - {Name: "item1", Id: "item1", Price: 5, Qty: "3"}, - }, - }, nil -} - -func (ch *Checkout) mustEmbedUnimplementedCheckoutServer() {} diff --git a/checkout/domain/checkout.pb.go b/checkout/domain/checkout.pb.go deleted file mode 100644 index 004d2cd..0000000 --- a/checkout/domain/checkout.pb.go +++ /dev/null @@ -1,343 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// versions: -// protoc-gen-go v1.28.0 -// protoc v3.6.1 -// source: checkout.proto - -package domain - -import ( - protoreflect "google.golang.org/protobuf/reflect/protoreflect" - protoimpl "google.golang.org/protobuf/runtime/protoimpl" - reflect "reflect" - sync "sync" -) - -const ( - // Verify that this generated code is sufficiently up-to-date. - _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) - // Verify that runtime/protoimpl is sufficiently up-to-date. - _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) -) - -type OverviewResponse struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - - UserID string `protobuf:"bytes,1,opt,name=UserID,proto3" json:"UserID,omitempty"` - Item []*OverviewResponse_Item `protobuf:"bytes,2,rep,name=item,proto3" json:"item,omitempty"` - TotalPrice int32 `protobuf:"varint,3,opt,name=totalPrice,proto3" json:"totalPrice,omitempty"` - ShippingPrice int32 `protobuf:"varint,4,opt,name=shippingPrice,proto3" json:"shippingPrice,omitempty"` - RewardPointsConsumed int32 `protobuf:"varint,5,opt,name=rewardPointsConsumed,proto3" json:"rewardPointsConsumed,omitempty"` -} - -func (x *OverviewResponse) Reset() { - *x = OverviewResponse{} - if protoimpl.UnsafeEnabled { - mi := &file_checkout_proto_msgTypes[0] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } -} - -func (x *OverviewResponse) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*OverviewResponse) ProtoMessage() {} - -func (x *OverviewResponse) ProtoReflect() protoreflect.Message { - mi := &file_checkout_proto_msgTypes[0] - if protoimpl.UnsafeEnabled && x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use OverviewResponse.ProtoReflect.Descriptor instead. -func (*OverviewResponse) Descriptor() ([]byte, []int) { - return file_checkout_proto_rawDescGZIP(), []int{0} -} - -func (x *OverviewResponse) GetUserID() string { - if x != nil { - return x.UserID - } - return "" -} - -func (x *OverviewResponse) GetItem() []*OverviewResponse_Item { - if x != nil { - return x.Item - } - return nil -} - -func (x *OverviewResponse) GetTotalPrice() int32 { - if x != nil { - return x.TotalPrice - } - return 0 -} - -func (x *OverviewResponse) GetShippingPrice() int32 { - if x != nil { - return x.ShippingPrice - } - return 0 -} - -func (x *OverviewResponse) GetRewardPointsConsumed() int32 { - if x != nil { - return x.RewardPointsConsumed - } - return 0 -} - -type OverviewRequest struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - - UserID string `protobuf:"bytes,1,opt,name=UserID,proto3" json:"UserID,omitempty"` -} - -func (x *OverviewRequest) Reset() { - *x = OverviewRequest{} - if protoimpl.UnsafeEnabled { - mi := &file_checkout_proto_msgTypes[1] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } -} - -func (x *OverviewRequest) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*OverviewRequest) ProtoMessage() {} - -func (x *OverviewRequest) ProtoReflect() protoreflect.Message { - mi := &file_checkout_proto_msgTypes[1] - if protoimpl.UnsafeEnabled && x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use OverviewRequest.ProtoReflect.Descriptor instead. -func (*OverviewRequest) Descriptor() ([]byte, []int) { - return file_checkout_proto_rawDescGZIP(), []int{1} -} - -func (x *OverviewRequest) GetUserID() string { - if x != nil { - return x.UserID - } - return "" -} - -type OverviewResponse_Item struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - - Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` - Id string `protobuf:"bytes,2,opt,name=id,proto3" json:"id,omitempty"` - Qty string `protobuf:"bytes,3,opt,name=qty,proto3" json:"qty,omitempty"` - Price int32 `protobuf:"varint,4,opt,name=price,proto3" json:"price,omitempty"` -} - -func (x *OverviewResponse_Item) Reset() { - *x = OverviewResponse_Item{} - if protoimpl.UnsafeEnabled { - mi := &file_checkout_proto_msgTypes[2] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } -} - -func (x *OverviewResponse_Item) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*OverviewResponse_Item) ProtoMessage() {} - -func (x *OverviewResponse_Item) ProtoReflect() protoreflect.Message { - mi := &file_checkout_proto_msgTypes[2] - if protoimpl.UnsafeEnabled && x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use OverviewResponse_Item.ProtoReflect.Descriptor instead. -func (*OverviewResponse_Item) Descriptor() ([]byte, []int) { - return file_checkout_proto_rawDescGZIP(), []int{0, 0} -} - -func (x *OverviewResponse_Item) GetName() string { - if x != nil { - return x.Name - } - return "" -} - -func (x *OverviewResponse_Item) GetId() string { - if x != nil { - return x.Id - } - return "" -} - -func (x *OverviewResponse_Item) GetQty() string { - if x != nil { - return x.Qty - } - return "" -} - -func (x *OverviewResponse_Item) GetPrice() int32 { - if x != nil { - return x.Price - } - return 0 -} - -var File_checkout_proto protoreflect.FileDescriptor - -var file_checkout_proto_rawDesc = []byte{ - 0x0a, 0x0e, 0x63, 0x68, 0x65, 0x63, 0x6b, 0x6f, 0x75, 0x74, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, - 0x22, 0xa4, 0x02, 0x0a, 0x10, 0x4f, 0x76, 0x65, 0x72, 0x76, 0x69, 0x65, 0x77, 0x52, 0x65, 0x73, - 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x16, 0x0a, 0x06, 0x55, 0x73, 0x65, 0x72, 0x49, 0x44, 0x18, - 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, 0x55, 0x73, 0x65, 0x72, 0x49, 0x44, 0x12, 0x2a, 0x0a, - 0x04, 0x69, 0x74, 0x65, 0x6d, 0x18, 0x02, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x16, 0x2e, 0x4f, 0x76, - 0x65, 0x72, 0x76, 0x69, 0x65, 0x77, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x2e, 0x49, - 0x74, 0x65, 0x6d, 0x52, 0x04, 0x69, 0x74, 0x65, 0x6d, 0x12, 0x1e, 0x0a, 0x0a, 0x74, 0x6f, 0x74, - 0x61, 0x6c, 0x50, 0x72, 0x69, 0x63, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x05, 0x52, 0x0a, 0x74, - 0x6f, 0x74, 0x61, 0x6c, 0x50, 0x72, 0x69, 0x63, 0x65, 0x12, 0x24, 0x0a, 0x0d, 0x73, 0x68, 0x69, - 0x70, 0x70, 0x69, 0x6e, 0x67, 0x50, 0x72, 0x69, 0x63, 0x65, 0x18, 0x04, 0x20, 0x01, 0x28, 0x05, - 0x52, 0x0d, 0x73, 0x68, 0x69, 0x70, 0x70, 0x69, 0x6e, 0x67, 0x50, 0x72, 0x69, 0x63, 0x65, 0x12, - 0x32, 0x0a, 0x14, 0x72, 0x65, 0x77, 0x61, 0x72, 0x64, 0x50, 0x6f, 0x69, 0x6e, 0x74, 0x73, 0x43, - 0x6f, 0x6e, 0x73, 0x75, 0x6d, 0x65, 0x64, 0x18, 0x05, 0x20, 0x01, 0x28, 0x05, 0x52, 0x14, 0x72, - 0x65, 0x77, 0x61, 0x72, 0x64, 0x50, 0x6f, 0x69, 0x6e, 0x74, 0x73, 0x43, 0x6f, 0x6e, 0x73, 0x75, - 0x6d, 0x65, 0x64, 0x1a, 0x52, 0x0a, 0x04, 0x49, 0x74, 0x65, 0x6d, 0x12, 0x12, 0x0a, 0x04, 0x6e, - 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x12, - 0x0e, 0x0a, 0x02, 0x69, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x02, 0x69, 0x64, 0x12, - 0x10, 0x0a, 0x03, 0x71, 0x74, 0x79, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x71, 0x74, - 0x79, 0x12, 0x14, 0x0a, 0x05, 0x70, 0x72, 0x69, 0x63, 0x65, 0x18, 0x04, 0x20, 0x01, 0x28, 0x05, - 0x52, 0x05, 0x70, 0x72, 0x69, 0x63, 0x65, 0x22, 0x29, 0x0a, 0x0f, 0x4f, 0x76, 0x65, 0x72, 0x76, - 0x69, 0x65, 0x77, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x16, 0x0a, 0x06, 0x55, 0x73, - 0x65, 0x72, 0x49, 0x44, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, 0x55, 0x73, 0x65, 0x72, - 0x49, 0x44, 0x32, 0x40, 0x0a, 0x08, 0x43, 0x68, 0x65, 0x63, 0x6b, 0x6f, 0x75, 0x74, 0x12, 0x34, - 0x0a, 0x0d, 0x4f, 0x72, 0x64, 0x65, 0x72, 0x4f, 0x76, 0x65, 0x72, 0x76, 0x69, 0x65, 0x77, 0x12, - 0x10, 0x2e, 0x4f, 0x76, 0x65, 0x72, 0x76, 0x69, 0x65, 0x77, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, - 0x74, 0x1a, 0x11, 0x2e, 0x4f, 0x76, 0x65, 0x72, 0x76, 0x69, 0x65, 0x77, 0x52, 0x65, 0x73, 0x70, - 0x6f, 0x6e, 0x73, 0x65, 0x42, 0x03, 0x5a, 0x01, 0x2e, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, - 0x33, -} - -var ( - file_checkout_proto_rawDescOnce sync.Once - file_checkout_proto_rawDescData = file_checkout_proto_rawDesc -) - -func file_checkout_proto_rawDescGZIP() []byte { - file_checkout_proto_rawDescOnce.Do(func() { - file_checkout_proto_rawDescData = protoimpl.X.CompressGZIP(file_checkout_proto_rawDescData) - }) - return file_checkout_proto_rawDescData -} - -var file_checkout_proto_msgTypes = make([]protoimpl.MessageInfo, 3) -var file_checkout_proto_goTypes = []interface{}{ - (*OverviewResponse)(nil), // 0: OverviewResponse - (*OverviewRequest)(nil), // 1: OverviewRequest - (*OverviewResponse_Item)(nil), // 2: OverviewResponse.Item -} -var file_checkout_proto_depIdxs = []int32{ - 2, // 0: OverviewResponse.item:type_name -> OverviewResponse.Item - 1, // 1: Checkout.OrderOverview:input_type -> OverviewRequest - 0, // 2: Checkout.OrderOverview:output_type -> OverviewResponse - 2, // [2:3] is the sub-list for method output_type - 1, // [1:2] is the sub-list for method input_type - 1, // [1:1] is the sub-list for extension type_name - 1, // [1:1] is the sub-list for extension extendee - 0, // [0:1] is the sub-list for field type_name -} - -func init() { file_checkout_proto_init() } -func file_checkout_proto_init() { - if File_checkout_proto != nil { - return - } - if !protoimpl.UnsafeEnabled { - file_checkout_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*OverviewResponse); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_checkout_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*OverviewRequest); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_checkout_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*OverviewResponse_Item); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - } - type x struct{} - out := protoimpl.TypeBuilder{ - File: protoimpl.DescBuilder{ - GoPackagePath: reflect.TypeOf(x{}).PkgPath(), - RawDescriptor: file_checkout_proto_rawDesc, - NumEnums: 0, - NumMessages: 3, - NumExtensions: 0, - NumServices: 1, - }, - GoTypes: file_checkout_proto_goTypes, - DependencyIndexes: file_checkout_proto_depIdxs, - MessageInfos: file_checkout_proto_msgTypes, - }.Build() - File_checkout_proto = out.File - file_checkout_proto_rawDesc = nil - file_checkout_proto_goTypes = nil - file_checkout_proto_depIdxs = nil -} diff --git a/checkout/domain/checkout.proto b/checkout/domain/checkout.proto deleted file mode 100644 index 7270c20..0000000 --- a/checkout/domain/checkout.proto +++ /dev/null @@ -1,26 +0,0 @@ -syntax = "proto3"; - -option go_package ="."; - -message OverviewResponse { - string UserID = 1; - message Item { - string name = 1; - string id = 2; - string qty = 3; - int32 price = 4; - } - repeated Item item = 2; - - int32 totalPrice = 3; - int32 shippingPrice = 4; - int32 rewardPointsConsumed = 5; -} - -message OverviewRequest { - string UserID = 1; -} - -service Checkout{ - rpc OrderOverview (OverviewRequest) returns (OverviewResponse); -} diff --git a/checkout/domain/checkout_grpc.pb.go b/checkout/domain/checkout_grpc.pb.go deleted file mode 100644 index 9d2a485..0000000 --- a/checkout/domain/checkout_grpc.pb.go +++ /dev/null @@ -1,105 +0,0 @@ -// Code generated by protoc-gen-go-grpc. DO NOT EDIT. -// versions: -// - protoc-gen-go-grpc v1.2.0 -// - protoc v3.6.1 -// source: checkout.proto - -package domain - -import ( - context "context" - grpc "google.golang.org/grpc" - codes "google.golang.org/grpc/codes" - status "google.golang.org/grpc/status" -) - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -// Requires gRPC-Go v1.32.0 or later. -const _ = grpc.SupportPackageIsVersion7 - -// CheckoutClient is the client API for Checkout service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream. -type CheckoutClient interface { - OrderOverview(ctx context.Context, in *OverviewRequest, opts ...grpc.CallOption) (*OverviewResponse, error) -} - -type checkoutClient struct { - cc grpc.ClientConnInterface -} - -func NewCheckoutClient(cc grpc.ClientConnInterface) CheckoutClient { - return &checkoutClient{cc} -} - -func (c *checkoutClient) OrderOverview(ctx context.Context, in *OverviewRequest, opts ...grpc.CallOption) (*OverviewResponse, error) { - out := new(OverviewResponse) - err := c.cc.Invoke(ctx, "/Checkout/OrderOverview", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// CheckoutServer is the server API for Checkout service. -// All implementations must embed UnimplementedCheckoutServer -// for forward compatibility -type CheckoutServer interface { - OrderOverview(context.Context, *OverviewRequest) (*OverviewResponse, error) - mustEmbedUnimplementedCheckoutServer() -} - -// UnimplementedCheckoutServer must be embedded to have forward compatible implementations. -type UnimplementedCheckoutServer struct { -} - -func (UnimplementedCheckoutServer) OrderOverview(context.Context, *OverviewRequest) (*OverviewResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method OrderOverview not implemented") -} -func (UnimplementedCheckoutServer) mustEmbedUnimplementedCheckoutServer() {} - -// UnsafeCheckoutServer may be embedded to opt out of forward compatibility for this service. -// Use of this interface is not recommended, as added methods to CheckoutServer will -// result in compilation errors. -type UnsafeCheckoutServer interface { - mustEmbedUnimplementedCheckoutServer() -} - -func RegisterCheckoutServer(s grpc.ServiceRegistrar, srv CheckoutServer) { - s.RegisterService(&Checkout_ServiceDesc, srv) -} - -func _Checkout_OrderOverview_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(OverviewRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(CheckoutServer).OrderOverview(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/Checkout/OrderOverview", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(CheckoutServer).OrderOverview(ctx, req.(*OverviewRequest)) - } - return interceptor(ctx, in, info, handler) -} - -// Checkout_ServiceDesc is the grpc.ServiceDesc for Checkout service. -// It's only intended for direct use with grpc.RegisterService, -// and not to be introspected or modified (even as a copy) -var Checkout_ServiceDesc = grpc.ServiceDesc{ - ServiceName: "Checkout", - HandlerType: (*CheckoutServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "OrderOverview", - Handler: _Checkout_OrderOverview_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "checkout.proto", -} diff --git a/checkout/go.mod b/checkout/go.mod deleted file mode 100644 index 88f62ec..0000000 --- a/checkout/go.mod +++ /dev/null @@ -1,42 +0,0 @@ -module github.com/swiggy-2022-bootcamp/cdp-team4/checkout - -go 1.17 - -require ( - github.com/gin-gonic/gin v1.7.7 - github.com/joho/godotenv v1.4.0 - github.com/sirupsen/logrus v1.8.1 - github.com/swaggo/swag v1.8.1 - google.golang.org/grpc v1.45.0 - google.golang.org/protobuf v1.26.0 -) - -require ( - github.com/KyleBanks/depth v1.2.1 // indirect - github.com/PuerkitoBio/purell v1.1.1 // indirect - github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578 // indirect - github.com/gin-contrib/sse v0.1.0 // indirect - github.com/go-openapi/jsonpointer v0.19.5 // indirect - github.com/go-openapi/jsonreference v0.19.6 // indirect - github.com/go-openapi/spec v0.20.4 // indirect - github.com/go-openapi/swag v0.19.15 // indirect - github.com/go-playground/locales v0.13.0 // indirect - github.com/go-playground/universal-translator v0.17.0 // indirect - github.com/go-playground/validator/v10 v10.4.1 // indirect - github.com/golang/protobuf v1.5.2 // indirect - github.com/josharian/intern v1.0.0 // indirect - github.com/json-iterator/go v1.1.9 // indirect - github.com/leodido/go-urn v1.2.0 // indirect - github.com/mailru/easyjson v0.7.6 // indirect - github.com/mattn/go-isatty v0.0.12 // indirect - github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 // indirect - github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742 // indirect - github.com/ugorji/go/codec v1.1.7 // indirect - golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9 // indirect - golang.org/x/net v0.0.0-20220127200216-cd36cc0744dd // indirect - golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e // indirect - golang.org/x/text v0.3.7 // indirect - golang.org/x/tools v0.1.7 // indirect - google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013 // indirect - gopkg.in/yaml.v2 v2.4.0 // indirect -) diff --git a/checkout/go.sum b/checkout/go.sum deleted file mode 100644 index 02b8223..0000000 --- a/checkout/go.sum +++ /dev/null @@ -1,245 +0,0 @@ -cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= -cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= -github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= -github.com/KyleBanks/depth v1.2.1 h1:5h8fQADFrWtarTdtDudMmGsC7GPbOAu6RVB3ffsVFHc= -github.com/KyleBanks/depth v1.2.1/go.mod h1:jzSb9d0L43HxTQfT+oSA1EEp2q+ne2uh6XgeJcm8brE= -github.com/PuerkitoBio/purell v1.1.1 h1:WEQqlqaGbrPkxLJWfBwQmfEAE1Z7ONdDLqrN38tNFfI= -github.com/PuerkitoBio/purell v1.1.1/go.mod h1:c11w/QuzBsJSee3cPx9rAFu61PvFxuPbtSwDGJws/X0= -github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578 h1:d+Bc7a5rLufV/sSk/8dngufqelfh6jnri85riMAaF/M= -github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578/go.mod h1:uGdkoq3SwY9Y+13GIhn11/XLaGBb4BfwItxLd5jeuXE= -github.com/agiledragon/gomonkey/v2 v2.3.1 h1:k+UnUY0EMNYUFUAQVETGY9uUTxjMdnUkP0ARyJS1zzs= -github.com/agiledragon/gomonkey/v2 v2.3.1/go.mod h1:ap1AmDzcVOAz1YpeJ3TCzIgstoaWLA6jbbgxfB4w2iY= -github.com/antihax/optional v1.0.0/go.mod h1:uupD/76wgC+ih3iEmQUL+0Ugr19nfwCT1kdvxnR2qWY= -github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= -github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= -github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= -github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc= -github.com/cncf/udpa/go v0.0.0-20201120205902-5459f2c99403/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk= -github.com/cncf/udpa/go v0.0.0-20210930031921-04548b0d99d4/go.mod h1:6pvJx4me5XPnfI9Z40ddWsdw2W/uZgQLFXToKeRcDiI= -github.com/cncf/xds/go v0.0.0-20210805033703-aa0b78936158/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= -github.com/cncf/xds/go v0.0.0-20210922020428-25de7278fc84/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= -github.com/cncf/xds/go v0.0.0-20211011173535-cb28da3451f1/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= -github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU= -github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= -github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= -github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= -github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= -github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98= -github.com/envoyproxy/go-control-plane v0.9.9-0.20201210154907-fd9021fe5dad/go.mod h1:cXg6YxExXjJnVBQHBLXeUAgxn2UodCpnH306RInaBQk= -github.com/envoyproxy/go-control-plane v0.9.10-0.20210907150352-cf90f659a021/go.mod h1:AFq3mo9L8Lqqiid3OhADV3RfLJnjiw63cSpi+fDTRC0= -github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= -github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= -github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE= -github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI= -github.com/gin-gonic/gin v1.7.7 h1:3DoBmSbJbZAWqXJC3SLjAPfutPJJRN1U5pALB7EeTTs= -github.com/gin-gonic/gin v1.7.7/go.mod h1:axIBovoeJpVj8S3BwE0uPMTeReE4+AfFtqpqaZ1qq1U= -github.com/go-openapi/jsonpointer v0.19.3/go.mod h1:Pl9vOtqEWErmShwVjC8pYs9cog34VGT37dQOVbmoatg= -github.com/go-openapi/jsonpointer v0.19.5 h1:gZr+CIYByUqjcgeLXnQu2gHYQC9o73G2XUeOFYEICuY= -github.com/go-openapi/jsonpointer v0.19.5/go.mod h1:Pl9vOtqEWErmShwVjC8pYs9cog34VGT37dQOVbmoatg= -github.com/go-openapi/jsonreference v0.19.6 h1:UBIxjkht+AWIgYzCDSv2GN+E/togfwXUJFRTWhl2Jjs= -github.com/go-openapi/jsonreference v0.19.6/go.mod h1:diGHMEHg2IqXZGKxqyvWdfWU/aim5Dprw5bqpKkTvns= -github.com/go-openapi/spec v0.20.4 h1:O8hJrt0UMnhHcluhIdUgCLRWyM2x7QkBXRvOs7m+O1M= -github.com/go-openapi/spec v0.20.4/go.mod h1:faYFR1CvsJZ0mNsmsphTMSoRrNV3TEDoAM7FOEWeq8I= -github.com/go-openapi/swag v0.19.5/go.mod h1:POnQmlKehdgb5mhVOsnJFsivZCEZ/vjK9gh66Z9tfKk= -github.com/go-openapi/swag v0.19.15 h1:D2NRCBzS9/pEY3gP9Nl8aDqGUcPFrwG2p+CNFrLyrCM= -github.com/go-openapi/swag v0.19.15/go.mod h1:QYRuS/SOXUCsnplDa677K7+DxSOj6IPNl/eQntq43wQ= -github.com/go-playground/assert/v2 v2.0.1 h1:MsBgLAaY856+nPRTKrp3/OZK38U/wa0CcBYNjji3q3A= -github.com/go-playground/assert/v2 v2.0.1/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= -github.com/go-playground/locales v0.13.0 h1:HyWk6mgj5qFqCT5fjGBuRArbVDfE4hi8+e8ceBS/t7Q= -github.com/go-playground/locales v0.13.0/go.mod h1:taPMhCMXrRLJO55olJkUXHZBHCxTMfnGwq/HNwmWNS8= -github.com/go-playground/universal-translator v0.17.0 h1:icxd5fm+REJzpZx7ZfpaD876Lmtgy7VtROAbHHXk8no= -github.com/go-playground/universal-translator v0.17.0/go.mod h1:UkSxE5sNxxRwHyU+Scu5vgOQjsIJAF8j9muTVoKLVtA= -github.com/go-playground/validator/v10 v10.4.1 h1:pH2c5ADXtd66mxoE0Zm9SUhxE20r7aM3F26W0hOn+GE= -github.com/go-playground/validator/v10 v10.4.1/go.mod h1:nlOn6nFhuKACm19sB/8EGNn9GlaMV7XkbRSipzJ0Ii4= -github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= -github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= -github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= -github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= -github.com/golang/protobuf v1.3.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw= -github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8= -github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA= -github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs= -github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w= -github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0= -github.com/golang/protobuf v1.4.1/go.mod h1:U8fpvMrcmy5pZrNK1lt4xCsGvpyWQ/VVv6QDs8UjoX8= -github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= -github.com/golang/protobuf v1.4.3/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= -github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= -github.com/golang/protobuf v1.5.2 h1:ROPKBNFfQgOUMifHyP+KYbvpjbdoFNs+aK7DXlji0Tw= -github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= -github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= -github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= -github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= -github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU= -github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= -github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= -github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= -github.com/grpc-ecosystem/grpc-gateway v1.16.0/go.mod h1:BDjrQk3hbvj6Nolgz8mAMFbcEtjT1g+wF4CSlocrBnw= -github.com/joho/godotenv v1.4.0 h1:3l4+N6zfMWnkbPEXKng2o2/MR5mSwTrBih4ZEkkz1lg= -github.com/joho/godotenv v1.4.0/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4= -github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY= -github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y= -github.com/json-iterator/go v1.1.9 h1:9yzud/Ht36ygwatGx56VwCZtlI/2AD15T1X2sjSuGns= -github.com/json-iterator/go v1.1.9/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= -github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU= -github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= -github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= -github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= -github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= -github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= -github.com/leodido/go-urn v1.2.0 h1:hpXL4XnriNwQ/ABnpepYM/1vCLWNDfUNts8dX3xTG6Y= -github.com/leodido/go-urn v1.2.0/go.mod h1:+8+nEpDfqqsY+g338gtMEUOtuK+4dEMhiQEgxpxOKII= -github.com/mailru/easyjson v0.0.0-20190614124828-94de47d64c63/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc= -github.com/mailru/easyjson v0.0.0-20190626092158-b2ccc519800e/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc= -github.com/mailru/easyjson v0.7.6 h1:8yTIVnZgCoiM1TgqoeTl+LfU5Jg6/xL3QhGQnimLYnA= -github.com/mailru/easyjson v0.7.6/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc= -github.com/mattn/go-isatty v0.0.12 h1:wuysRhFDzyxgEmMf5xjvJ2M9dZoWAXNNr5LSBS7uHXY= -github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU= -github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 h1:ZqeYNhU3OHLH3mGKHDcjJRFFRrJa6eAM5H+CtDdOsPc= -github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= -github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742 h1:Esafd1046DLDQ0W1YjYsBW+p8U2u7vzgW2SQVmlNazg= -github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= -github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e h1:fD57ERR4JtEqsWbfPhv4DMiApHyliiK5xCTNVSPiaAs= -github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= -github.com/otiai10/copy v1.7.0 h1:hVoPiN+t+7d2nzzwMiDHPSOogsWAStewq3TwU05+clE= -github.com/otiai10/copy v1.7.0/go.mod h1:rmRl6QPdJj6EiUqXQ/4Nn2lLXoNQjFCQbbNrxgc/t3U= -github.com/otiai10/curr v0.0.0-20150429015615-9b4961190c95/go.mod h1:9qAhocn7zKJG+0mI8eUu6xqkFDYS2kb2saOteoSB3cE= -github.com/otiai10/curr v1.0.0/go.mod h1:LskTG5wDwr8Rs+nNQ+1LlxRjAtTZZjtJW4rMXl6j4vs= -github.com/otiai10/mint v1.3.0/go.mod h1:F5AjcsTsWUqX+Na9fpHb52P8pcRX2CI6A3ctIT91xUo= -github.com/otiai10/mint v1.3.3/go.mod h1:/yxELlJQ0ufhjUwhshSj+wFjZ78CnZ48/1wtmBH1OTc= -github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= -github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= -github.com/rogpeppe/fastuuid v1.2.0/go.mod h1:jVj6XXZzXRy/MSR5jhDC/2q6DgLz+nrA6LYCDYWNEvQ= -github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= -github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc= -github.com/sirupsen/logrus v1.8.1 h1:dJKuHgqk1NNQlqoA6BTlM1Wf9DOH3NBjQyu0h9+AZZE= -github.com/sirupsen/logrus v1.8.1/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0= -github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc= -github.com/smartystreets/goconvey v1.6.4/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA= -github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= -github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= -github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= -github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= -github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= -github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= -github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY= -github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= -github.com/swaggo/swag v1.8.1 h1:JuARzFX1Z1njbCGz+ZytBR15TFJwF2Q7fu8puJHhQYI= -github.com/swaggo/swag v1.8.1/go.mod h1:ugemnJsPZm/kRwFUnzBlbHRd0JY9zE1M4F+uy2pAaPQ= -github.com/ugorji/go v1.1.7 h1:/68gy2h+1mWMrwZFeD1kQialdSzAb432dtpeJ42ovdo= -github.com/ugorji/go v1.1.7/go.mod h1:kZn38zHttfInRq0xu/PH0az30d+z6vm202qpg1oXVMw= -github.com/ugorji/go/codec v1.1.7 h1:2SvQaVZ1ouYrrKKwoSk2pzd4A9evlKJb9oTL+OaLUSs= -github.com/ugorji/go/codec v1.1.7/go.mod h1:Ax+UKWsSmolVDwsd+7N3ZtXu+yMGCf907BLYF3GoBXY= -github.com/urfave/cli/v2 v2.3.0/go.mod h1:LJmUH05zAU44vOAcrfzZQKsZbVcdbOG8rtL3/XcUArI= -github.com/yuin/goldmark v1.4.0/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= -go.opentelemetry.io/proto/otlp v0.7.0/go.mod h1:PqfVotwruBrMGOCsRd/89rSnXhoiJIqeYNgFYFoEGnI= -golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= -golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= -golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9 h1:psW17arqaxU48Z5kZ0CQnkZWQJsqcURM6tKiBApRjXI= -golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= -golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= -golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= -golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= -golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= -golang.org/x/mod v0.4.2 h1:Gz96sIWK3OalVv/I/qNygP42zyoKp3xptRVCWRFEBvo= -golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= -golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= -golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= -golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20200822124328-c89045814202/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= -golang.org/x/net v0.0.0-20210421230115-4e50805a0758/go.mod h1:72T/g9IO56b78aLF+1Kcs5dz7/ng1VjMUvfKvpfy+jM= -golang.org/x/net v0.0.0-20210805182204-aaa1db679c0d/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= -golang.org/x/net v0.0.0-20220127200216-cd36cc0744dd h1:O7DYs+zxREGLKzKoMQrtrEacpb0ZVXA5rIwylE2Xchk= -golang.org/x/net v0.0.0-20220127200216-cd36cc0744dd/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= -golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= -golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= -golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210420072515-93ed5bcd2bfe/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e h1:fLOSk5Q00efkSvAm+4xcoXD+RRmLmmulPn5I3Y9F2EM= -golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= -golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= -golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= -golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= -golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= -golang.org/x/text v0.3.7 h1:olpwvP2KacW1ZWvsR7uQhoyTYvKAupfQrRGBFM352Gk= -golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= -golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= -golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= -golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= -golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= -golang.org/x/tools v0.0.0-20190328211700-ab21143f2384/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= -golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= -golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.1.7 h1:6j8CgantCy3yc8JGBqkDLMKWqZ0RDU2g1HVgacojGWQ= -golang.org/x/tools v0.1.7/go.mod h1:LGqMHiF4EqQNHR1JncWGqT5BVaXmza+X+BDGol+dOxo= -golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE= -golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= -google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= -google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= -google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= -google.golang.org/genproto v0.0.0-20200513103714-09dca8ec2884/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= -google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013 h1:+kGHl1aib/qcwaRi1CbqBZ1rk19r85MNUf8HaBghugY= -google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013/go.mod h1:NbSheEEYHJ7i3ixzK3sjbqSGDJWnxyFXZblF3eUsNvo= -google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= -google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= -google.golang.org/grpc v1.25.1/go.mod h1:c3i+UQWmh7LiEpx4sFZnkU36qjEYZ0imhYfXVyQciAY= -google.golang.org/grpc v1.27.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= -google.golang.org/grpc v1.33.1/go.mod h1:fr5YgcSWrqhRRxogOsw7RzIpsmvOZ6IcH4kBYTpR3n0= -google.golang.org/grpc v1.36.0/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAGRRjU= -google.golang.org/grpc v1.45.0 h1:NEpgUqV3Z+ZjkqMsxMg11IaDrXY4RY6CQukSGK0uI1M= -google.golang.org/grpc v1.45.0/go.mod h1:lN7owxKUQEqMfSyQikvvk5tf/6zMPsrK+ONuO11+0rQ= -google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= -google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= -google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= -google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE= -google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo= -google.golang.org/protobuf v1.22.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= -google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= -google.golang.org/protobuf v1.23.1-0.20200526195155-81db48ad09cc/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= -google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlbajtzgsN7c= -google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= -google.golang.org/protobuf v1.26.0 h1:bxAC2xTBsZGibn2RTntX0oH50xLsqy1OxA9tTL3p/lk= -google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= -gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f h1:BLraFXnmrev5lT+xlilqcH8XK9/i0At2xKjWk4p6zsU= -gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.2.3/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= -gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= -gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -gopkg.in/yaml.v3 v3.0.0-20200615113413-eeeca48fe776 h1:tQIYjPdBoyREyB9XMu+nnTclpTYkz2zFM+lzLJFO4gQ= -gopkg.in/yaml.v3 v3.0.0-20200615113413-eeeca48fe776/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= -honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= diff --git a/checkout/infra/checkoutModel.go b/checkout/infra/checkoutModel.go deleted file mode 100644 index 5372731..0000000 --- a/checkout/infra/checkoutModel.go +++ /dev/null @@ -1 +0,0 @@ -package infra diff --git a/checkout/infra/logger/logger.go b/checkout/infra/logger/logger.go deleted file mode 100644 index 95667c8..0000000 --- a/checkout/infra/logger/logger.go +++ /dev/null @@ -1,43 +0,0 @@ -package logger - -import ( - "fmt" - "io" - "os" - "sync" - - "github.com/joho/godotenv" - "github.com/sirupsen/logrus" -) - -var logger *logrus.Logger - -// Singleton Pattern -func GetLogger() *logrus.Logger { - - var once sync.Once - if logger == nil { - once.Do( - func() { - logger = logrus.New() - err := godotenv.Load(".env") - if err != nil { - return - } - LOG_FILE := os.Getenv("LOG_FILE") - src, err := os.OpenFile(LOG_FILE, os.O_APPEND|os.O_WRONLY, os.ModeAppend) - - if err != nil { - fmt.Print(err.Error()) - fmt.Print("unable to create user.log file") - } - - multiWriter := io.MultiWriter(os.Stdout, src) - - logger.SetFormatter(&logrus.JSONFormatter{}) - logger.SetOutput(multiWriter) - }) - } - - return logger -} diff --git a/checkout/main.go b/checkout/main.go deleted file mode 100644 index 9e691fc..0000000 --- a/checkout/main.go +++ /dev/null @@ -1,20 +0,0 @@ -package main - -import "github.com/swiggy-2022-bootcamp/cdp-team4/checkout/app" - -// @title Checkout API -// @version 1.0 -// @description Checkout Service. -// @termsOfService http://swagger.io/terms/ - -// @contact.name API Support -// @contact.url http://www.swagger.io/support -// @contact.email support@swagger.io - -// @license.name Apache 2.0 -// @license.url http://www.apache.org/licenses/LICENSE-2.0.html - -// @BasePath / -func main() { - app.Start() -} diff --git a/gateway/app/userHandler.go b/gateway/app/userHandler.go index 36adec0..58bc85e 100644 --- a/gateway/app/userHandler.go +++ b/gateway/app/userHandler.go @@ -21,6 +21,12 @@ type authModel struct { Role int } +type ValidationDTO struct { + UserId string `json:"user_id"` + Role int `json:"role"` +} + + func ValidateToken(authorizationHeader string) authModel { authServiceUri := "http://localhost:8881/api/v1/validate" req, err := http.NewRequest("GET", authServiceUri, nil) @@ -43,20 +49,23 @@ func ValidateToken(authorizationHeader string) authModel { err = json.NewDecoder(res.Body).Decode(&resDTO) if err != nil { - + log.Fatalf("unable to decode response %v", err) } - model := resDTO.Data.(authModel) + var valDTO ValidationDTO + jsonbytes, _ := json.Marshal(resDTO.Data) + json.Unmarshal(jsonbytes, &valDTO) return authModel{ - UserId: model.UserId, - Role: model.Role, + UserId: valDTO.UserId, + Role: valDTO.Role, } } func (h userHandler) ValidateAuthToken() gin.HandlerFunc { return func(c *gin.Context) { res := ValidateToken(c.Request.Header.Get("Authorization")) + c.JSON(http.StatusOK, res) } } diff --git a/payment/.gitignore b/payment/.gitignore deleted file mode 100644 index 73b101f..0000000 --- a/payment/.gitignore +++ /dev/null @@ -1,18 +0,0 @@ -# Binaries for programs and plugins -*.exe -*.exe~ -*.dll -*.so -*.dylib -*.cov -# Test binary, built with `go test -c` -*.test - -# Output of the go coverage tool, specifically when used with LiteIDE -*.out - -# Dependency directories (remove the comment below to include it) -# vendor/ - -.env -*.log \ No newline at end of file diff --git a/payment/Dockerfile b/payment/Dockerfile deleted file mode 100644 index 5811144..0000000 --- a/payment/Dockerfile +++ /dev/null @@ -1,17 +0,0 @@ -FROM golang:1.17-alpine - -RUN apk update && apk add --no-cache git build-base - -WORKDIR /go/github.com/swiggy-2022-bootcamp/cdp-team4/payment - -COPY . /go/github.com/swiggy-2022-bootcamp/cdp-team4/payment - -# get all the dependencies -RUN go get ./... - -# build -RUN go build -o /paymentService - -EXPOSE 8081 - -CMD [ "/paymentService" ] diff --git a/payment/README.md b/payment/README.md deleted file mode 100644 index 0857e2a..0000000 --- a/payment/README.md +++ /dev/null @@ -1,3 +0,0 @@ -# Payment Service - -PORT=8002 diff --git a/payment/app/app.go b/payment/app/app.go deleted file mode 100644 index ca8021b..0000000 --- a/payment/app/app.go +++ /dev/null @@ -1,54 +0,0 @@ -package app - -import ( - "os" - - "github.com/gin-gonic/gin" - "github.com/sirupsen/logrus" - - "github.com/joho/godotenv" - "github.com/swiggy-2022-bootcamp/cdp-team4/payment/docs" - "github.com/swiggy-2022-bootcamp/cdp-team4/payment/domain" - "github.com/swiggy-2022-bootcamp/cdp-team4/payment/infra" - "github.com/swiggy-2022-bootcamp/cdp-team4/payment/infra/logger" - - swaggerFiles "github.com/swaggo/files" - ginSwagger "github.com/swaggo/gin-swagger" // gin-swagger middleware -) - -var log logrus.Logger = *logger.GetLogger() -var paymentHandler PayHandler - -func setupRouter() *gin.Engine { - router := gin.Default() - // health check route - HealthCheckRouter(router) - // payment router - PayRouter(router) - - router.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler)) - return router -} - -func ConfigureSwaggerDoc() { - docs.SwaggerInfo.Title = "Swagger Payment API" -} - -func Start(testMode bool) { - dynamoRepository := infra.NewDynamoRepository() - paymentHandler = PayHandler{PaymentService: domain.NewPaymentService(dynamoRepository)} - - ConfigureSwaggerDoc() - router := setupRouter() - - err := godotenv.Load(".env") - if err != nil { - log.Fatal(err) - return - } - PORT := os.Getenv("PORT") - if !testMode { - log.WithFields(logrus.Fields{"PORT": PORT}).Info("Running on PORT") - router.Run(":" + PORT) - } -} diff --git a/payment/app/app_test.go b/payment/app/app_test.go deleted file mode 100644 index 37715b7..0000000 --- a/payment/app/app_test.go +++ /dev/null @@ -1,15 +0,0 @@ -package app_test - -import ( - "testing" - - "github.com/swiggy-2022-bootcamp/cdp-team4/payment/app" -) - -func TestConfigureSwaggerDoc(t *testing.T) { - app.ConfigureSwaggerDoc() -} - -func TestStart(t *testing.T) { - app.Start(true /*testMode*/) -} diff --git a/payment/app/healthHandler.go b/payment/app/healthHandler.go deleted file mode 100644 index 6fd63ee..0000000 --- a/payment/app/healthHandler.go +++ /dev/null @@ -1,21 +0,0 @@ -package app - -import ( - "net/http" - - "github.com/gin-gonic/gin" -) - -// Health Check -// @Summary Health of payment service -// @Description use tocheck whether payment service is up and running or not -// @Tags Health -// @Produce json -// @Success 200 {object} map[string]interface{} -// @Failure 400 {number} http.StatusBadRequest -// @Router / [get] -func HealthCheck() gin.HandlerFunc { - return func(c *gin.Context) { - c.JSON(http.StatusOK, gin.H{"message": "Service is running"}) - } -} diff --git a/payment/app/healthHandler_test.go b/payment/app/healthHandler_test.go deleted file mode 100644 index fd77f04..0000000 --- a/payment/app/healthHandler_test.go +++ /dev/null @@ -1,20 +0,0 @@ -package app - -import ( - "net/http" - "net/http/httptest" - "testing" - - "github.com/stretchr/testify/assert" -) - -func TestHeathCheck(t *testing.T) { - router := setupRouter() - - w := httptest.NewRecorder() - req, _ := http.NewRequest("GET", "/", nil) - router.ServeHTTP(w, req) - - assert.Equal(t, 200, w.Code) - assert.Equal(t, "{\"message\":\"Service is running\"}", w.Body.String()) -} diff --git a/payment/app/payHandler.go b/payment/app/payHandler.go deleted file mode 100644 index 89aa8de..0000000 --- a/payment/app/payHandler.go +++ /dev/null @@ -1,197 +0,0 @@ -package app - -import ( - "net/http" - "strings" - "time" - - "github.com/gin-gonic/gin" - "github.com/sirupsen/logrus" - "github.com/swiggy-2022-bootcamp/cdp-team4/payment/domain" - "github.com/swiggy-2022-bootcamp/cdp-team4/payment/infra/gokafka" -) - -type PayHandler struct { - PaymentService domain.PaymentService -} - -type PaymentRecordDTO struct { - Amount int16 - Currency string - Status string - OrderID string - UserID string - Method string - Description string - VPA string - Notes []string -} - -type PaymentMethodDTO struct { - Id string - Method string - Agree string - Comment string -} - -func simulatePaymentDone(data interface{}) { - time.Sleep(10 * time.Second) - ok, err := gokafka.WriteMsgToKafka("payment", data) - if !ok { - log.WithFields(logrus.Fields{"message": err.Error(), "status": http.StatusBadRequest}). - Error("unable to write message to kafka") - } - - log.Debug("write message to kafka") -} - -func (ph PayHandler) HandlePay() gin.HandlerFunc { - return func(ctx *gin.Context) { - var paymentDto PaymentRecordDTO - - if err := ctx.BindJSON(&paymentDto); err != nil { - ctx.JSON(http.StatusBadRequest, gin.H{"message": err.Error()}) - log.WithFields(logrus.Fields{"message": err.Error(), "status": http.StatusBadRequest}). - Error("bind json") - return - } - - data, err := ph.PaymentService.CreateDynamoPaymentRecord( - paymentDto.Amount, - paymentDto.Currency, - paymentDto.Status, - paymentDto.OrderID, - paymentDto.UserID, - paymentDto.Method, - paymentDto.Description, - paymentDto.VPA, - paymentDto.Notes, - ) - if err != nil { - ctx.JSON(http.StatusBadRequest, gin.H{"message": err.Error()}) - log.WithFields(logrus.Fields{"message": err.Error(), "status": http.StatusBadRequest}). - Error("create payment record") - return - } - if data == nil { - ctx.JSON(http.StatusBadRequest, gin.H{"message": "unable to create payment link"}) - log.WithFields(logrus.Fields{"message": err.Error(), "status": http.StatusBadRequest}). - Error("unable create payment link") - return - } - ctx.JSON(http.StatusOK, gin.H{"message": "payment record added", "data": data}) - log.WithFields(logrus.Fields{"data": data, "status": http.StatusOK}). - Info("payment record added") - - // simulatoin of successful payment - go simulatePaymentDone(data) - } -} - -func (ph PayHandler) HandleGetPayRecordByID() gin.HandlerFunc { - return func(ctx *gin.Context) { - id := ctx.Param("id") - record, err := ph.PaymentService.GetPaymentRecordById(id) - - if err != nil { - ctx.JSON(http.StatusBadRequest, gin.H{"message": err.Error()}) - log.WithFields(logrus.Fields{"message": err.Error(), "status": http.StatusBadRequest}). - Error("unable to fetch payment record") - return - } - ctx.JSON(http.StatusOK, gin.H{"record": record}) - log.WithFields(logrus.Fields{"record": record, "status": http.StatusOK}). - Info("payment record by id") - } -} - -func (ph PayHandler) handleGetPayRecordsByUserID() gin.HandlerFunc { - return func(ctx *gin.Context) { - // id := ctx.Param("user_id") - // record, err := ph.PaymentService.GetPaymentAllRecordsByUserId(id) - - // if err != nil { - // ctx.JSON(http.StatusBadRequest, gin.H{"message": err.Error()}) - // return - // } - // ctx.JSON(http.StatusAccepted, gin.H{"record": record}) - } -} - -func (ph PayHandler) handleUpdatePayStatus() gin.HandlerFunc { - return func(ctx *gin.Context) { - var requestDTO struct { - Id string - Status string - } - if err := ctx.BindJSON(&requestDTO); err != nil { - ctx.JSON(http.StatusBadRequest, gin.H{"message": err.Error()}) - log.WithFields(logrus.Fields{"message": err.Error(), "status": http.StatusBadRequest}). - Error("unable to json bind") - return - } - - ok, err := ph.PaymentService.UpdatePaymentStatus(requestDTO.Id, requestDTO.Status) - if !ok { - ctx.JSON(http.StatusBadRequest, gin.H{"message": err.Error()}) - log.WithFields(logrus.Fields{"message": err.Error(), "status": http.StatusBadRequest}). - Error("unable update payment status") - return - } - ctx.JSON(http.StatusOK, gin.H{"message": "payment record updated"}) - log.WithFields(logrus.Fields{"status": http.StatusOK}). - Info("payment record updated") - } -} - -func (ph PayHandler) handleAddPaymentMethods() gin.HandlerFunc { - return func(ctx *gin.Context) { - var paymentMethodDTO PaymentMethodDTO - if err := ctx.BindJSON(&paymentMethodDTO); err != nil { - ctx.JSON(http.StatusBadRequest, gin.H{"message": err.Error()}) - log.WithFields(logrus.Fields{"message": err.Error(), "status": http.StatusBadRequest}). - Error("unable to json bind") - return - } - - ok, err := ph.PaymentService.AddPaymentMethod( - paymentMethodDTO.Id, - paymentMethodDTO.Method, - paymentMethodDTO.Agree, - paymentMethodDTO.Comment, - ) - - if !ok { - if strings.Contains(err.Error(), "ConditionalCheckFailedException") { - ctx.JSON(http.StatusBadRequest, gin.H{"message": "method already exists"}) - log.WithFields(logrus.Fields{"message": err.Error(), "status": http.StatusBadRequest}). - Debug("method already exists") - return - } - ctx.JSON(http.StatusBadRequest, gin.H{"message": err.Error()}) - log.WithFields(logrus.Fields{"message": err.Error(), "status": http.StatusBadRequest}). - Error("unable to add payment method") - return - } - ctx.JSON(http.StatusOK, gin.H{"message": "payment method added"}) - log.WithFields(logrus.Fields{"status": http.StatusOK}). - Info("payment method added") - } -} - -func (ph PayHandler) handleGetPaymentMethods() gin.HandlerFunc { - return func(ctx *gin.Context) { - id := ctx.Param("id") - methods, err := ph.PaymentService.GetPaymentMethods(id) - - if err != nil { - ctx.JSON(http.StatusBadRequest, gin.H{"message": err.Error()}) - log.WithFields(logrus.Fields{"message": err.Error(), "status": http.StatusBadRequest}). - Error("unable to fetch payment methods") - return - } - ctx.JSON(http.StatusAccepted, gin.H{"methods": methods}) - log.WithFields(logrus.Fields{"methods": methods, "status": http.StatusOK}). - Info("fetch payment methods") - } -} diff --git a/payment/app/payHandler_test.go b/payment/app/payHandler_test.go deleted file mode 100644 index 52dd27d..0000000 --- a/payment/app/payHandler_test.go +++ /dev/null @@ -1,44 +0,0 @@ -package app - -import ( - "testing" -) - -func TestHandleGetPayRecordByID(t *testing.T) { - // router := setupRouter() - - // w := httptest.NewRecorder() - // req, _ := http.NewRequest("GET", "/pay/6257f46fb246e8ad600da634", nil) - // req.Header.Add("Content-Type", "application/json") - // req.Header.Add("Accept", "*/*") - - // router.ServeHTTP(w, req) - - // assert.Equal(t, 500, w.Code) -} - -func TestHandlePay(t *testing.T) { - // router := setupRouter() - - // w := httptest.NewRecorder() - // payment := &domain.Payment{ - // Amount: 4654, - // Currency: "INR", - // Status: "created", - // OrderID: "aksldfa", - // UserID: "ahdflka", - // Description: "dummy payment", - // VPA: "alkshdf", - // Notes: []string{"none"}, - // } - - // paymentJSON, _ := json.Marshal(payment) - - // req, _ := http.NewRequest("POST", "/pay/", bytes.NewBuffer(paymentJSON)) - // req.Header.Add("Content-Type", "application/json") - // req.Header.Add("Accept", "*/*") - - // router.ServeHTTP(w, req) - - // assert.Equal(t, 200, w.Code) -} diff --git a/payment/app/routes.go b/payment/app/routes.go deleted file mode 100644 index 75b0121..0000000 --- a/payment/app/routes.go +++ /dev/null @@ -1,23 +0,0 @@ -package app - -import ( - "github.com/gin-gonic/gin" -) - -func HealthCheckRouter(gin *gin.Engine) { - gin.GET("/", HealthCheck()) -} - -func PayRouter(gin *gin.Engine) { - p := gin.Group("/pay") - { - p.POST("/", paymentHandler.HandlePay()) - p.PUT("/", paymentHandler.handleUpdatePayStatus()) - - p.GET("/user/:user_id", paymentHandler.handleGetPayRecordsByUserID()) - p.GET("/:id", paymentHandler.HandleGetPayRecordByID()) - - p.POST("/paymentMethods", paymentHandler.handleAddPaymentMethods()) - p.GET("/paymentMethods/:id", paymentHandler.handleGetPaymentMethods()) - } -} diff --git a/payment/docs/docs.go b/payment/docs/docs.go deleted file mode 100644 index ec08b5a..0000000 --- a/payment/docs/docs.go +++ /dev/null @@ -1,72 +0,0 @@ -// Package docs GENERATED BY THE COMMAND ABOVE; DO NOT EDIT -// This file was generated by swaggo/swag -package docs - -import "github.com/swaggo/swag" - -const docTemplate = `{ - "schemes": {{ marshal .Schemes }}, - "swagger": "2.0", - "info": { - "description": "{{escape .Description}}", - "title": "{{.Title}}", - "termsOfService": "http://swagger.io/terms/", - "contact": { - "name": "API Support", - "url": "http://www.swagger.io/support", - "email": "support@swagger.io" - }, - "license": { - "name": "Apache 2.0", - "url": "http://www.apache.org/licenses/LICENSE-2.0.html" - }, - "version": "{{.Version}}" - }, - "host": "{{.Host}}", - "basePath": "{{.BasePath}}", - "paths": { - "/": { - "get": { - "description": "use tocheck whether payment service is up and running or not", - "produces": [ - "application/json" - ], - "tags": [ - "Health" - ], - "summary": "Health of payment service", - "responses": { - "200": { - "description": "OK", - "schema": { - "type": "object", - "additionalProperties": true - } - }, - "400": { - "description": "Bad Request", - "schema": { - "type": "number" - } - } - } - } - } - } -}` - -// SwaggerInfo holds exported Swagger Info so clients can modify it -var SwaggerInfo = &swag.Spec{ - Version: "1.0", - Host: "", - BasePath: "/", - Schemes: []string{"http"}, - Title: "Payment API", - Description: "Payment Service.", - InfoInstanceName: "swagger", - SwaggerTemplate: docTemplate, -} - -func init() { - swag.Register(SwaggerInfo.InstanceName(), SwaggerInfo) -} diff --git a/payment/docs/swagger.json b/payment/docs/swagger.json deleted file mode 100644 index 5edeb7a..0000000 --- a/payment/docs/swagger.json +++ /dev/null @@ -1,51 +0,0 @@ -{ - "schemes": [ - "http" - ], - "swagger": "2.0", - "info": { - "description": "Payment Service.", - "title": "Payment API", - "termsOfService": "http://swagger.io/terms/", - "contact": { - "name": "API Support", - "url": "http://www.swagger.io/support", - "email": "support@swagger.io" - }, - "license": { - "name": "Apache 2.0", - "url": "http://www.apache.org/licenses/LICENSE-2.0.html" - }, - "version": "1.0" - }, - "basePath": "/", - "paths": { - "/": { - "get": { - "description": "use tocheck whether payment service is up and running or not", - "produces": [ - "application/json" - ], - "tags": [ - "Health" - ], - "summary": "Health of payment service", - "responses": { - "200": { - "description": "OK", - "schema": { - "type": "object", - "additionalProperties": true - } - }, - "400": { - "description": "Bad Request", - "schema": { - "type": "number" - } - } - } - } - } - } -} \ No newline at end of file diff --git a/payment/docs/swagger.yaml b/payment/docs/swagger.yaml deleted file mode 100644 index d103a6c..0000000 --- a/payment/docs/swagger.yaml +++ /dev/null @@ -1,35 +0,0 @@ -basePath: / -info: - contact: - email: support@swagger.io - name: API Support - url: http://www.swagger.io/support - description: Payment Service. - license: - name: Apache 2.0 - url: http://www.apache.org/licenses/LICENSE-2.0.html - termsOfService: http://swagger.io/terms/ - title: Payment API - version: "1.0" -paths: - /: - get: - description: use tocheck whether payment service is up and running or not - produces: - - application/json - responses: - "200": - description: OK - schema: - additionalProperties: true - type: object - "400": - description: Bad Request - schema: - type: number - summary: Health of payment service - tags: - - Health -schemes: -- http -swagger: "2.0" diff --git a/payment/domain/payment.go b/payment/domain/payment.go deleted file mode 100644 index 21e8702..0000000 --- a/payment/domain/payment.go +++ /dev/null @@ -1,32 +0,0 @@ -package domain - -type Payment struct { - Id string - Amount int16 - Currency string - Status string - OrderID string - UserID string - Method string - Description string - VPA string - Notes []string -} - -type PaymentMethod struct { - Id string - Method []string - Agree string - Comment string -} - -type PaymentDynamoRepository interface { - InsertPaymentRecord(Payment) (bool, error) - FindPaymentRecordById(string) (*Payment, error) - FindPaymentRecordByUserID(string) ([]Payment, error) - UpdatePaymentRecord(string, string) (bool, error) - UpdatePaymentMethods(string, string) (bool, error) - DeletePaymentRecordByID(string) (bool, error) - InsertPaymentMethod(PaymentMethod) (bool, error) - GetPaymentMethods(string) ([]string, error) -} diff --git a/payment/domain/paymentService.go b/payment/domain/paymentService.go deleted file mode 100644 index 97a22d3..0000000 --- a/payment/domain/paymentService.go +++ /dev/null @@ -1,169 +0,0 @@ -package domain - -import ( - "fmt" - "os" - - "go.mongodb.org/mongo-driver/bson/primitive" - - "github.com/gin-gonic/gin" - "github.com/joho/godotenv" - razorpay "github.com/razorpay/razorpay-go" -) - -type PaymentService interface { - CreateDynamoPaymentRecord( - int16, - string, - string, - string, - string, - string, - string, - string, - []string, - ) (map[string]interface{}, error) - GetPaymentRecordById(string) (*Payment, error) - // GetPaymentAllRecordsByUserId(string) ([]Payment, error) - UpdatePaymentStatus(string, string) (bool, error) - // UpdatePaymentMethod(string, string) (bool, error) - GetPaymentMethods(string) ([]string, error) - AddPaymentMethod(string, string, string, string) (bool, error) -} - -type paymentService struct { - PaymentDynamoRepository PaymentDynamoRepository -} - -func GenerateUniqueId() string { - return primitive.NewObjectID().Hex() -} - -func GetRazorpayPaymentLink(p Payment) (map[string]interface{}, error) { - err := godotenv.Load(".env") - if err != nil { - return nil, err - } - - key_id := os.Getenv("RAZORPAY_KEY_ID") - key_secret := os.Getenv("RAZORPAY_KEY_SECRET") - fmt.Print("secret done") - client := razorpay.NewClient(key_id, key_secret) - fmt.Print("razorpay client done") - data := gin.H{ - "amount": p.Amount, - "currency": p.Currency, - "reference_id": GenerateUniqueId(), - // "customer": struct { - // userId string - // orderId string - // }{ - // userId: p.UserID, - // orderId: p.OrderID, - // }, - // "notes": p.Notes, - } - fmt.Print("razorpay data done") - - body, err := client.PaymentLink.Create(data, nil) - fmt.Printf("\n%+v \n", body) - fmt.Printf("%+v", err) - if err != nil { - return nil, err - } - return body, err -} - -func (service paymentService) CreateDynamoPaymentRecord( - amount int16, - currency, status, order_id, user_id, method, description, vpa string, - notes []string, -) (map[string]interface{}, error) { - id := GenerateUniqueId() - paymentRecord := Payment{ - Id: id, - Amount: amount, - Currency: currency, - Status: status, - OrderID: order_id, - UserID: user_id, - Method: method, - Description: description, - VPA: vpa, - Notes: notes, - } - - ok, err := service.PaymentDynamoRepository.InsertPaymentRecord(paymentRecord) - if !ok { - return nil, err - } - data, err := GetRazorpayPaymentLink(paymentRecord) - if err != nil { - return nil, err - } - return data, nil -} - -func (service paymentService) GetPaymentRecordById(id string) (*Payment, error) { - paymentRecord, err := service.PaymentDynamoRepository.FindPaymentRecordById(id) - if err != nil { - return nil, err - } - return paymentRecord, nil -} - -// func (service paymentService) GetPaymentAllRecordsByUserId(id string) ([]Payment, error) { -// return []Payment{}, nil -// } - -// func (service paymentService) UpdatePaymentMethod(id, method string) (bool, error) { -// return true, nil -// } - -func (service paymentService) GetPaymentMethods(id string) ([]string, error) { - methods, err := service.PaymentDynamoRepository.GetPaymentMethods(id) - if err != nil { - return nil, err - } - - return methods, nil -} - -func (service paymentService) UpdatePaymentStatus( - paymentID string, - paymentStatus string, -) (bool, error) { - return true, nil -} - -func (service paymentService) AddPaymentMethod(id, method, agree, comment string) (bool, error) { - var paymentRecord = PaymentMethod{ - Id: id, - Agree: agree, - Comment: comment, - Method: []string{method}, - } - _, err := service.PaymentDynamoRepository.GetPaymentMethods(id) - - fmt.Print(err) - if err != nil { - ok, err := service.PaymentDynamoRepository.InsertPaymentMethod(paymentRecord) - if !ok { - return false, err - } - return ok, nil - } - - ok, err := service.PaymentDynamoRepository.UpdatePaymentMethods(id, method) - if !ok { - return ok, err - } - - return true, nil -} - -func NewPaymentService(paymentDynamoRepository PaymentDynamoRepository) PaymentService { - return &paymentService{ - PaymentDynamoRepository: paymentDynamoRepository, - } -} diff --git a/payment/domain/paymentService_test.go b/payment/domain/paymentService_test.go deleted file mode 100644 index 367ea59..0000000 --- a/payment/domain/paymentService_test.go +++ /dev/null @@ -1,132 +0,0 @@ -package domain_test - -import ( - "fmt" - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/mock" - "github.com/swiggy-2022-bootcamp/cdp-team4/payment/domain" - mocks "github.com/swiggy-2022-bootcamp/cdp-team4/payment/mocks/domain" -) - -var mockDynamoRepo = mocks.PaymentDynamoRepository{} -var service = domain.NewPaymentService(&mockDynamoRepo) - -func TestGenerateUniqueId(t *testing.T) { - var id interface{} = domain.GenerateUniqueId() - _, ok := id.(string) - - assert.Equal(t, true, ok) -} - -func TestGetRazorpayPaymentLink(t *testing.T) { - response, err := domain.GetRazorpayPaymentLink(domain.Payment{ - Amount: 45, - Currency: "INR", - UserID: "adf", - OrderID: "asg", - Notes: []string{""}, - }) - - assert.Nil(t, nil, response) - assert.NotNil(t, err) -} - -func TestShouldReturnNewUserService(t *testing.T) { - userService := domain.NewPaymentService(nil) - assert.NotNil(t, userService) -} - -func TestCreateDynamoPaymentRecord(t *testing.T) { - payment := domain.Payment{ - Amount: 54, - Currency: "INR", - Status: "pending", - Method: "upi", - Description: "description", - VPA: "asdf", - UserID: "dfa", - OrderID: "isf", - Notes: []string{""}, - } - - mockDynamoRepo.On("InsertPaymentRecord", mock.Anything).Return(true, nil) - service.CreateDynamoPaymentRecord( - payment.Amount, - payment.Currency, - payment.Status, - payment.OrderID, - payment.UserID, - payment.Method, - payment.Description, - payment.VPA, - payment.Notes, - ) - mockDynamoRepo.AssertNumberOfCalls(t, "InsertPaymentRecord", 1) -} - -func TestGetPaymentRecordById(t *testing.T) { - payment := domain.Payment{ - Amount: 54, - Currency: "INR", - Status: "pending", - Method: "upi", - Description: "description", - VPA: "asdf", - UserID: "dfa", - OrderID: "isf", - Notes: []string{""}, - } - mockDynamoRepo.On("FindPaymentRecordById", "abc").Return(&payment, nil) - service.GetPaymentRecordById("abc") - - mockDynamoRepo.AssertNumberOfCalls(t, "FindPaymentRecordById", 1) -} - -func TestFailGetPaymentRecordById(t *testing.T) { - mockDynamoRepo.On("FindPaymentRecordById", "abcd"). - Return(nil, fmt.Errorf("element id not found")) - service.GetPaymentRecordById("abcd") - - mockDynamoRepo.AssertNumberOfCalls(t, "FindPaymentRecordById", 2) -} - -func TestGetPaymentMethods(t *testing.T) { - methodList := []string{"upi"} - mockDynamoRepo.On("GetPaymentMethods", "abd").Return(methodList, nil) - service.GetPaymentMethods("abd") - - mockDynamoRepo.AssertNumberOfCalls(t, "GetPaymentMethods", 1) -} - -func TestFailGetPaymentMethods(t *testing.T) { - mockDynamoRepo.On("GetPaymentMethods", "abdc").Return(nil, fmt.Errorf("element id not found")) - service.GetPaymentMethods("abdc") - - mockDynamoRepo.AssertNumberOfCalls(t, "GetPaymentMethods", 2) -} - -func TestUpdatePaymentStatus(t *testing.T) { - ok, _ := service.UpdatePaymentStatus("abc", "pending") - assert.Equal(t, true, ok) -} - -func TestAddPaymentMethod(t *testing.T) { - mockDynamoRepo.On("GetPaymentMethods", "abc").Return(nil, fmt.Errorf("element id not found")) - mockDynamoRepo.On("InsertPaymentMethod", mock.Anything).Return(true, nil) - mockDynamoRepo.On("UpdatePaymentMethods", "abc", "upi").Return(true, nil) - - service.AddPaymentMethod("abc", "upi", "1", "none") - // mockDynamoRepo.AssertNumberOfCalls(t, "UpdatePaymentMethods", 1) - mockDynamoRepo.AssertNumberOfCalls(t, "InsertPaymentMethod", 1) -} - -func TestAddNextPaymentMethod(t *testing.T) { - mockDynamoRepo.On("GetPaymentMethods", "xyz").Return(nil, nil) - mockDynamoRepo.On("InsertPaymentMethod", mock.Anything).Return(true, nil) - mockDynamoRepo.On("UpdatePaymentMethods", "xyz", "upi").Return(true, nil) - - service.AddPaymentMethod("xyz", "upi", "1", "none") - mockDynamoRepo.AssertNumberOfCalls(t, "UpdatePaymentMethods", 1) -} diff --git a/payment/go.mod b/payment/go.mod deleted file mode 100644 index 39d4f8d..0000000 --- a/payment/go.mod +++ /dev/null @@ -1,53 +0,0 @@ -module github.com/swiggy-2022-bootcamp/cdp-team4/payment - -go 1.17 - -require ( - github.com/aws/aws-sdk-go v1.43.38 - github.com/gin-gonic/gin v1.7.7 - github.com/joho/godotenv v1.4.0 - github.com/razorpay/razorpay-go v0.0.0-20220125080828-980e9c2fc0e4 - github.com/segmentio/kafka-go v0.4.31 - github.com/sirupsen/logrus v1.8.1 - github.com/stretchr/testify v1.7.1 - github.com/swaggo/files v0.0.0-20210815190702-a29dd2bc99b2 - github.com/swaggo/gin-swagger v1.4.1 - github.com/swaggo/swag v1.8.1 - go.mongodb.org/mongo-driver v1.9.0 -) - -require ( - github.com/KyleBanks/depth v1.2.1 // indirect - github.com/PuerkitoBio/purell v1.1.1 // indirect - github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578 // indirect - github.com/davecgh/go-spew v1.1.1 // indirect - github.com/gin-contrib/sse v0.1.0 // indirect - github.com/go-openapi/jsonpointer v0.19.5 // indirect - github.com/go-openapi/jsonreference v0.19.6 // indirect - github.com/go-openapi/spec v0.20.4 // indirect - github.com/go-openapi/swag v0.19.15 // indirect - github.com/go-playground/locales v0.13.0 // indirect - github.com/go-playground/universal-translator v0.17.0 // indirect - github.com/go-playground/validator/v10 v10.4.1 // indirect - github.com/golang/protobuf v1.3.3 // indirect - github.com/jmespath/go-jmespath v0.4.0 // indirect - github.com/josharian/intern v1.0.0 // indirect - github.com/json-iterator/go v1.1.9 // indirect - github.com/klauspost/compress v1.14.2 // indirect - github.com/leodido/go-urn v1.2.0 // indirect - github.com/mailru/easyjson v0.7.6 // indirect - github.com/mattn/go-isatty v0.0.12 // indirect - github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 // indirect - github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742 // indirect - github.com/pierrec/lz4/v4 v4.1.14 // indirect - github.com/pmezard/go-difflib v1.0.0 // indirect - github.com/stretchr/objx v0.1.0 // indirect - github.com/ugorji/go/codec v1.1.7 // indirect - golang.org/x/crypto v0.0.0-20201216223049-8b5274cf687f // indirect - golang.org/x/net v0.0.0-20220127200216-cd36cc0744dd // indirect - golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e // indirect - golang.org/x/text v0.3.7 // indirect - golang.org/x/tools v0.1.7 // indirect - gopkg.in/yaml.v2 v2.4.0 // indirect - gopkg.in/yaml.v3 v3.0.0-20200615113413-eeeca48fe776 // indirect -) diff --git a/payment/go.sum b/payment/go.sum deleted file mode 100644 index 82dd119..0000000 --- a/payment/go.sum +++ /dev/null @@ -1,201 +0,0 @@ -github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= -github.com/KyleBanks/depth v1.2.1 h1:5h8fQADFrWtarTdtDudMmGsC7GPbOAu6RVB3ffsVFHc= -github.com/KyleBanks/depth v1.2.1/go.mod h1:jzSb9d0L43HxTQfT+oSA1EEp2q+ne2uh6XgeJcm8brE= -github.com/PuerkitoBio/purell v1.1.1 h1:WEQqlqaGbrPkxLJWfBwQmfEAE1Z7ONdDLqrN38tNFfI= -github.com/PuerkitoBio/purell v1.1.1/go.mod h1:c11w/QuzBsJSee3cPx9rAFu61PvFxuPbtSwDGJws/X0= -github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578 h1:d+Bc7a5rLufV/sSk/8dngufqelfh6jnri85riMAaF/M= -github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578/go.mod h1:uGdkoq3SwY9Y+13GIhn11/XLaGBb4BfwItxLd5jeuXE= -github.com/agiledragon/gomonkey/v2 v2.3.1 h1:k+UnUY0EMNYUFUAQVETGY9uUTxjMdnUkP0ARyJS1zzs= -github.com/agiledragon/gomonkey/v2 v2.3.1/go.mod h1:ap1AmDzcVOAz1YpeJ3TCzIgstoaWLA6jbbgxfB4w2iY= -github.com/aws/aws-sdk-go v1.43.38 h1:TDRjsUIsx2aeSuKkyzbwgltIRTbIKH6YCZbZ27JYhPk= -github.com/aws/aws-sdk-go v1.43.38/go.mod h1:y4AeaBuwd2Lk+GepC1E9v0qOiTws0MIWAX4oIKwKHZo= -github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU= -github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= -github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= -github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= -github.com/gin-contrib/gzip v0.0.3 h1:etUaeesHhEORpZMp18zoOhepboiWnFtXrBZxszWUn4k= -github.com/gin-contrib/gzip v0.0.3/go.mod h1:YxxswVZIqOvcHEQpsSn+QF5guQtO1dCfy0shBPy4jFc= -github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE= -github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI= -github.com/gin-gonic/gin v1.6.3/go.mod h1:75u5sXoLsGZoRN5Sgbi1eraJ4GU3++wFwWzhwvtwp4M= -github.com/gin-gonic/gin v1.7.7 h1:3DoBmSbJbZAWqXJC3SLjAPfutPJJRN1U5pALB7EeTTs= -github.com/gin-gonic/gin v1.7.7/go.mod h1:axIBovoeJpVj8S3BwE0uPMTeReE4+AfFtqpqaZ1qq1U= -github.com/go-openapi/jsonpointer v0.19.3/go.mod h1:Pl9vOtqEWErmShwVjC8pYs9cog34VGT37dQOVbmoatg= -github.com/go-openapi/jsonpointer v0.19.5 h1:gZr+CIYByUqjcgeLXnQu2gHYQC9o73G2XUeOFYEICuY= -github.com/go-openapi/jsonpointer v0.19.5/go.mod h1:Pl9vOtqEWErmShwVjC8pYs9cog34VGT37dQOVbmoatg= -github.com/go-openapi/jsonreference v0.19.6 h1:UBIxjkht+AWIgYzCDSv2GN+E/togfwXUJFRTWhl2Jjs= -github.com/go-openapi/jsonreference v0.19.6/go.mod h1:diGHMEHg2IqXZGKxqyvWdfWU/aim5Dprw5bqpKkTvns= -github.com/go-openapi/spec v0.20.4 h1:O8hJrt0UMnhHcluhIdUgCLRWyM2x7QkBXRvOs7m+O1M= -github.com/go-openapi/spec v0.20.4/go.mod h1:faYFR1CvsJZ0mNsmsphTMSoRrNV3TEDoAM7FOEWeq8I= -github.com/go-openapi/swag v0.19.5/go.mod h1:POnQmlKehdgb5mhVOsnJFsivZCEZ/vjK9gh66Z9tfKk= -github.com/go-openapi/swag v0.19.15 h1:D2NRCBzS9/pEY3gP9Nl8aDqGUcPFrwG2p+CNFrLyrCM= -github.com/go-openapi/swag v0.19.15/go.mod h1:QYRuS/SOXUCsnplDa677K7+DxSOj6IPNl/eQntq43wQ= -github.com/go-playground/assert/v2 v2.0.1 h1:MsBgLAaY856+nPRTKrp3/OZK38U/wa0CcBYNjji3q3A= -github.com/go-playground/assert/v2 v2.0.1/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= -github.com/go-playground/locales v0.13.0 h1:HyWk6mgj5qFqCT5fjGBuRArbVDfE4hi8+e8ceBS/t7Q= -github.com/go-playground/locales v0.13.0/go.mod h1:taPMhCMXrRLJO55olJkUXHZBHCxTMfnGwq/HNwmWNS8= -github.com/go-playground/universal-translator v0.17.0 h1:icxd5fm+REJzpZx7ZfpaD876Lmtgy7VtROAbHHXk8no= -github.com/go-playground/universal-translator v0.17.0/go.mod h1:UkSxE5sNxxRwHyU+Scu5vgOQjsIJAF8j9muTVoKLVtA= -github.com/go-playground/validator/v10 v10.2.0/go.mod h1:uOYAAleCW8F/7oMFd6aG0GOhaH6EGOAJShg8Id5JGkI= -github.com/go-playground/validator/v10 v10.4.1 h1:pH2c5ADXtd66mxoE0Zm9SUhxE20r7aM3F26W0hOn+GE= -github.com/go-playground/validator/v10 v10.4.1/go.mod h1:nlOn6nFhuKACm19sB/8EGNn9GlaMV7XkbRSipzJ0Ii4= -github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= -github.com/golang/protobuf v1.3.3 h1:gyjaxf+svBWX08ZjK86iN9geUJF0H6gp2IRKX6Nf6/I= -github.com/golang/protobuf v1.3.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw= -github.com/golang/snappy v0.0.1/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= -github.com/google/go-cmp v0.5.2 h1:X2ev0eStA3AbceY54o37/0PQ/UWqKEiiO2dKL5OPaFM= -github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= -github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= -github.com/jmespath/go-jmespath v0.4.0 h1:BEgLn5cpjn8UN1mAw4NjwDrS35OdebyEtFe+9YPoQUg= -github.com/jmespath/go-jmespath v0.4.0/go.mod h1:T8mJZnbsbmF+m6zOOFylbeCJqk5+pHWvzYPziyZiYoo= -github.com/jmespath/go-jmespath/internal/testify v1.5.1 h1:shLQSRRSCCPj3f2gpwzGwWFoC7ycTf1rcQZHOlsJ6N8= -github.com/jmespath/go-jmespath/internal/testify v1.5.1/go.mod h1:L3OGu8Wl2/fWfCI6z80xFu9LTZmf1ZRjMHUOPmWr69U= -github.com/joho/godotenv v1.4.0 h1:3l4+N6zfMWnkbPEXKng2o2/MR5mSwTrBih4ZEkkz1lg= -github.com/joho/godotenv v1.4.0/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4= -github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY= -github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y= -github.com/json-iterator/go v1.1.9 h1:9yzud/Ht36ygwatGx56VwCZtlI/2AD15T1X2sjSuGns= -github.com/json-iterator/go v1.1.9/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= -github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU= -github.com/klauspost/compress v1.13.6/go.mod h1:/3/Vjq9QcHkK5uEr5lBEmyoZ1iFhe47etQ6QUkpK6sk= -github.com/klauspost/compress v1.14.2 h1:S0OHlFk/Gbon/yauFJ4FfJJF5V0fc5HbBTJazi28pRw= -github.com/klauspost/compress v1.14.2/go.mod h1:/3/Vjq9QcHkK5uEr5lBEmyoZ1iFhe47etQ6QUkpK6sk= -github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= -github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= -github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= -github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= -github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= -github.com/leodido/go-urn v1.2.0 h1:hpXL4XnriNwQ/ABnpepYM/1vCLWNDfUNts8dX3xTG6Y= -github.com/leodido/go-urn v1.2.0/go.mod h1:+8+nEpDfqqsY+g338gtMEUOtuK+4dEMhiQEgxpxOKII= -github.com/mailru/easyjson v0.0.0-20190614124828-94de47d64c63/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc= -github.com/mailru/easyjson v0.0.0-20190626092158-b2ccc519800e/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc= -github.com/mailru/easyjson v0.7.6 h1:8yTIVnZgCoiM1TgqoeTl+LfU5Jg6/xL3QhGQnimLYnA= -github.com/mailru/easyjson v0.7.6/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc= -github.com/mattn/go-isatty v0.0.12 h1:wuysRhFDzyxgEmMf5xjvJ2M9dZoWAXNNr5LSBS7uHXY= -github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU= -github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 h1:ZqeYNhU3OHLH3mGKHDcjJRFFRrJa6eAM5H+CtDdOsPc= -github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= -github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742 h1:Esafd1046DLDQ0W1YjYsBW+p8U2u7vzgW2SQVmlNazg= -github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= -github.com/montanaflynn/stats v0.0.0-20171201202039-1bf9dbcd8cbe/go.mod h1:wL8QJuTMNUDYhXwkmfOly8iTdp5TEcJFWZD2D7SIkUc= -github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e h1:fD57ERR4JtEqsWbfPhv4DMiApHyliiK5xCTNVSPiaAs= -github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= -github.com/otiai10/copy v1.7.0 h1:hVoPiN+t+7d2nzzwMiDHPSOogsWAStewq3TwU05+clE= -github.com/otiai10/copy v1.7.0/go.mod h1:rmRl6QPdJj6EiUqXQ/4Nn2lLXoNQjFCQbbNrxgc/t3U= -github.com/otiai10/curr v0.0.0-20150429015615-9b4961190c95/go.mod h1:9qAhocn7zKJG+0mI8eUu6xqkFDYS2kb2saOteoSB3cE= -github.com/otiai10/curr v1.0.0/go.mod h1:LskTG5wDwr8Rs+nNQ+1LlxRjAtTZZjtJW4rMXl6j4vs= -github.com/otiai10/mint v1.3.0/go.mod h1:F5AjcsTsWUqX+Na9fpHb52P8pcRX2CI6A3ctIT91xUo= -github.com/otiai10/mint v1.3.3/go.mod h1:/yxELlJQ0ufhjUwhshSj+wFjZ78CnZ48/1wtmBH1OTc= -github.com/pierrec/lz4/v4 v4.1.14 h1:+fL8AQEZtz/ijeNnpduH0bROTu0O3NZAlPjQxGn8LwE= -github.com/pierrec/lz4/v4 v4.1.14/go.mod h1:gZWDp/Ze/IJXGXf23ltt2EXimqmTUXEy0GFuRQyBid4= -github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= -github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= -github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/razorpay/razorpay-go v0.0.0-20220125080828-980e9c2fc0e4 h1:g8IvTN1ttQYCIU0MxEF3tmrUGThT1vGMX71YWfRNRfM= -github.com/razorpay/razorpay-go v0.0.0-20220125080828-980e9c2fc0e4/go.mod h1:VcljkUylUJAUEvFfGVv/d5ht1to1dUgF4H1+3nv7i+Q= -github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= -github.com/segmentio/kafka-go v0.4.31 h1:+ImsrkJRju9j1D9U44rvRGRlpsI9GnwD8s9WTFagNLQ= -github.com/segmentio/kafka-go v0.4.31/go.mod h1:m1lXeqJtIFYZayv0shM/tjrAFljvWLTprxBHd+3PnaU= -github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc= -github.com/sirupsen/logrus v1.8.1 h1:dJKuHgqk1NNQlqoA6BTlM1Wf9DOH3NBjQyu0h9+AZZE= -github.com/sirupsen/logrus v1.8.1/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0= -github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc= -github.com/smartystreets/goconvey v1.6.4/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA= -github.com/stretchr/objx v0.1.0 h1:4G4v2dO3VZwixGIRoQ5Lfboy6nUhCyYzaqnIAPPhYs4= -github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= -github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= -github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= -github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= -github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= -github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= -github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= -github.com/stretchr/testify v1.7.1 h1:5TQK59W5E3v0r2duFAb7P95B6hEeOyEnHRa8MjYSMTY= -github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= -github.com/swaggo/files v0.0.0-20210815190702-a29dd2bc99b2 h1:+iNTcqQJy0OZ5jk6a5NLib47eqXK8uYcPX+O4+cBpEM= -github.com/swaggo/files v0.0.0-20210815190702-a29dd2bc99b2/go.mod h1:lKJPbtWzJ9JhsTN1k1gZgleJWY/cqq0psdoMmaThG3w= -github.com/swaggo/gin-swagger v1.4.1 h1:F2vJndw+Q+ZBOlsC6CaodqXJV3ZOf6hpg/4Y6MEx5BM= -github.com/swaggo/gin-swagger v1.4.1/go.mod h1:hmJ1vPn+XjUvnbzjCdUAxVqgraxELxk8x5zAsjCE5mg= -github.com/swaggo/swag v1.7.9/go.mod h1:gZ+TJ2w/Ve1RwQsA2IRoSOTidHz6DX+PIG8GWvbnoLU= -github.com/swaggo/swag v1.8.1 h1:JuARzFX1Z1njbCGz+ZytBR15TFJwF2Q7fu8puJHhQYI= -github.com/swaggo/swag v1.8.1/go.mod h1:ugemnJsPZm/kRwFUnzBlbHRd0JY9zE1M4F+uy2pAaPQ= -github.com/tidwall/pretty v1.0.0/go.mod h1:XNkn88O1ChpSDQmQeStsy+sBenx6DDtFZJxhVysOjyk= -github.com/ugorji/go v1.1.7 h1:/68gy2h+1mWMrwZFeD1kQialdSzAb432dtpeJ42ovdo= -github.com/ugorji/go v1.1.7/go.mod h1:kZn38zHttfInRq0xu/PH0az30d+z6vm202qpg1oXVMw= -github.com/ugorji/go/codec v1.1.7 h1:2SvQaVZ1ouYrrKKwoSk2pzd4A9evlKJb9oTL+OaLUSs= -github.com/ugorji/go/codec v1.1.7/go.mod h1:Ax+UKWsSmolVDwsd+7N3ZtXu+yMGCf907BLYF3GoBXY= -github.com/urfave/cli/v2 v2.3.0/go.mod h1:LJmUH05zAU44vOAcrfzZQKsZbVcdbOG8rtL3/XcUArI= -github.com/xdg-go/pbkdf2 v1.0.0/go.mod h1:jrpuAogTd400dnrH08LKmI/xc1MbPOebTwRqcT5RDeI= -github.com/xdg-go/scram v1.0.2/go.mod h1:1WAq6h33pAW+iRreB34OORO2Nf7qel3VV3fjBj+hCSs= -github.com/xdg-go/stringprep v1.0.2/go.mod h1:8F9zXuvzgwmyT5DUm4GUfZGDdT3W+LCvS6+da4O5kxM= -github.com/xdg/scram v0.0.0-20180814205039-7eeb5667e42c h1:u40Z8hqBAAQyv+vATcGgV0YCnDjqSL7/q/JyPhhJSPk= -github.com/xdg/scram v0.0.0-20180814205039-7eeb5667e42c/go.mod h1:lB8K/P019DLNhemzwFU4jHLhdvlE6uDZjXFejJXr49I= -github.com/xdg/stringprep v1.0.0 h1:d9X0esnoa3dFsV0FG35rAT0RIhYFlPq7MiP+DW89La0= -github.com/xdg/stringprep v1.0.0/go.mod h1:Jhud4/sHMO4oL310DaZAKk9ZaJ08SJfe+sJh0HrGL1Y= -github.com/youmark/pkcs8 v0.0.0-20181117223130-1be2e3e5546d/go.mod h1:rHwXgn7JulP+udvsHwJoVG1YGAP6VLg4y9I5dyZdqmA= -github.com/yuin/goldmark v1.4.0/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= -go.mongodb.org/mongo-driver v1.9.0 h1:f3aLGJvQmBl8d9S40IL+jEyBC6hfLPbJjv9t5hEM9ck= -go.mongodb.org/mongo-driver v1.9.0/go.mod h1:0sQWfOeY63QTntERDJJ/0SuKK0T1uVSgKCuAROlKEPY= -golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= -golang.org/x/crypto v0.0.0-20190506204251-e1dfcc566284/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= -golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= -golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= -golang.org/x/crypto v0.0.0-20201216223049-8b5274cf687f h1:aZp0e2vLN4MToVqnjNEYEtrEA8RH8U8FN1CU7JgqsPU= -golang.org/x/crypto v0.0.0-20201216223049-8b5274cf687f/go.mod h1:jdWPYTVW3xRLrWPugEBEK3UY2ZEsg3UU495nc5E+M+I= -golang.org/x/mod v0.4.2 h1:Gz96sIWK3OalVv/I/qNygP42zyoKp3xptRVCWRFEBvo= -golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= -golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= -golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= -golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20210421230115-4e50805a0758/go.mod h1:72T/g9IO56b78aLF+1Kcs5dz7/ng1VjMUvfKvpfy+jM= -golang.org/x/net v0.0.0-20210805182204-aaa1db679c0d/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= -golang.org/x/net v0.0.0-20220127200216-cd36cc0744dd h1:O7DYs+zxREGLKzKoMQrtrEacpb0ZVXA5rIwylE2Xchk= -golang.org/x/net v0.0.0-20220127200216-cd36cc0744dd/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= -golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210420072515-93ed5bcd2bfe/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e h1:fLOSk5Q00efkSvAm+4xcoXD+RRmLmmulPn5I3Y9F2EM= -golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw= -golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= -golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= -golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= -golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= -golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= -golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= -golang.org/x/text v0.3.7 h1:olpwvP2KacW1ZWvsR7uQhoyTYvKAupfQrRGBFM352Gk= -golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= -golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= -golang.org/x/tools v0.0.0-20190328211700-ab21143f2384/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= -golang.org/x/tools v0.0.0-20190531172133-b3315ee88b7d/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= -golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.1.7 h1:6j8CgantCy3yc8JGBqkDLMKWqZ0RDU2g1HVgacojGWQ= -golang.org/x/tools v0.1.7/go.mod h1:LGqMHiF4EqQNHR1JncWGqT5BVaXmza+X+BDGol+dOxo= -golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE= -golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f h1:BLraFXnmrev5lT+xlilqcH8XK9/i0At2xKjWk4p6zsU= -gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.2.3/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= -gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= -gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -gopkg.in/yaml.v3 v3.0.0-20200615113413-eeeca48fe776 h1:tQIYjPdBoyREyB9XMu+nnTclpTYkz2zFM+lzLJFO4gQ= -gopkg.in/yaml.v3 v3.0.0-20200615113413-eeeca48fe776/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/payment/infra/dynamoDB.go b/payment/infra/dynamoDB.go deleted file mode 100644 index cd25567..0000000 --- a/payment/infra/dynamoDB.go +++ /dev/null @@ -1,296 +0,0 @@ -package infra - -import ( - "context" - "fmt" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/dynamodb" - "github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute" - "github.com/aws/aws-sdk-go/service/dynamodb/expression" - "github.com/swiggy-2022-bootcamp/cdp-team4/payment/domain" -) - -type PaymentDynamoRepository struct { - Session *dynamodb.DynamoDB -} - -func connect() *dynamodb.DynamoDB { - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - // create dynamo client - svc := dynamodb.New(sess) - - return svc -} - -func (pdr PaymentDynamoRepository) InsertPaymentRecord(p domain.Payment) (bool, error) { - ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) - defer cancel() - payRecord := _toDynamoPayModel(&p, "XYZ", "0") - - av, err := dynamodbattribute.MarshalMap(payRecord) - if err != nil { - return false, fmt.Errorf("unable to marshal - %s", err.Error()) - } - - input := &dynamodb.PutItemInput{ - Item: av, - TableName: aws.String("payment"), - } - - _, err = pdr.Session.PutItemWithContext(ctx, input) - - if err != nil { - return false, fmt.Errorf("unable to put the item - %s", err.Error()) - } - - return true, nil -} - -func (pdr PaymentDynamoRepository) FindPaymentRecordById( - paymentID string, -) (*domain.Payment, error) { - ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) - defer cancel() - - input := &dynamodb.GetItemInput{ - TableName: aws.String("payment"), - Key: map[string]*dynamodb.AttributeValue{ - "id": { - S: aws.String(paymentID), - }, - }, - } - - result, err := pdr.Session.GetItemWithContext(ctx, input) - if err != nil { - return nil, fmt.Errorf("unable to get the item - %s", err.Error()) - } - - if result.Item == nil { - return nil, fmt.Errorf("item not found") - } - - payModel := domain.Payment{} - err = dynamodbattribute.UnmarshalMap(result.Item, &payModel) - - if err != nil { - return nil, fmt.Errorf("unmarshal map - %s", err.Error()) - } - - return &payModel, nil -} - -func (pdr PaymentDynamoRepository) FindPaymentRecordByUserID( - userId string, -) ([]domain.Payment, error) { - ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) - defer cancel() - - filt := expression.Name("UserID").Equal(expression.Value(userId)) - - expr, err := expression.NewBuilder().WithFilter(filt).Build() - - if err != nil { - return nil, fmt.Errorf("expression new builder - %s", err.Error()) - } - - input := &dynamodb.ScanInput{ - ExpressionAttributeNames: expr.Names(), - FilterExpression: expr.Filter(), - ExpressionAttributeValues: expr.Values(), - TableName: aws.String("payment"), - } - - result, err := pdr.Session.ScanWithContext(ctx, input) - if err != nil { - return nil, fmt.Errorf("scan with filter - %s", err.Error()) - } - - paymentRecords := make([]domain.Payment, 1) - - for _, item := range result.Items { - record := domain.Payment{} - err := dynamodbattribute.UnmarshalMap(item, &record) - if err != nil { - return nil, fmt.Errorf("expression new builder - %s", err.Error()) - } - paymentRecords = append(paymentRecords, record) - } - - return paymentRecords, nil -} - -func (pdr PaymentDynamoRepository) UpdatePaymentRecord(id, attributeValue string) (bool, error) { - ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) - defer cancel() - input := &dynamodb.UpdateItemInput{ - ExpressionAttributeValues: map[string]*dynamodb.AttributeValue{ - ":s": { - N: aws.String(attributeValue), - }, - }, - Key: map[string]*dynamodb.AttributeValue{ - "id": { - S: aws.String(id), - }, - }, - ReturnValues: aws.String("UPDATED_NEW"), - UpdateExpression: aws.String("set Status = :s"), - TableName: aws.String("payment"), - } - - _, err := pdr.Session.UpdateItemWithContext(ctx, input) - if err != nil { - return false, fmt.Errorf("unable to update - %s", err.Error()) - } - return true, nil -} - -func (pdr PaymentDynamoRepository) DeletePaymentRecordByID(id string) (bool, error) { - ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) - defer cancel() - input := &dynamodb.DeleteItemInput{ - Key: map[string]*dynamodb.AttributeValue{ - "Id": { - N: aws.String(id), - }, - }, - TableName: aws.String("payment"), - } - - _, err := pdr.Session.DeleteItemWithContext(ctx, input) - if err != nil { - return false, fmt.Errorf("unable to delete - %s", err.Error()) - } - return true, nil -} - -func (pdr PaymentDynamoRepository) InsertPaymentMethod(pm domain.PaymentMethod) (bool, error) { - ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) - defer cancel() - payMethodModel := _toDynamoPayMethodModel(&pm) - av, err := dynamodbattribute.MarshalMap(payMethodModel) - if err != nil { - return false, fmt.Errorf("unable to marshal - %s", err.Error()) - } - - input := &dynamodb.PutItemInput{ - Item: av, - TableName: aws.String("paymentmethod"), - } - - _, err = pdr.Session.PutItemWithContext(ctx, input) - if err != nil { - return false, fmt.Errorf("unable to put the item - %s", err.Error()) - } - - return true, nil -} - -func (pdr PaymentDynamoRepository) GetPaymentMethods(id string) ([]string, error) { - ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) - defer cancel() - - input := &dynamodb.GetItemInput{ - TableName: aws.String("paymentmethod"), - Key: map[string]*dynamodb.AttributeValue{ - "id": { - S: aws.String(id), - }, - }, - } - - result, err := pdr.Session.GetItemWithContext(ctx, input) - if err != nil { - return nil, fmt.Errorf("unable to get the item - %s", err.Error()) - } - - if result.Item == nil { - return nil, fmt.Errorf("item not found") - } - - payMethodModel := PaymentMethodModel{} - err = dynamodbattribute.UnmarshalMap(result.Item, &payMethodModel) - - if err != nil { - return nil, fmt.Errorf("unmarshal map - %s", err.Error()) - } - - return payMethodModel.Methods, nil -} -func (pdr PaymentDynamoRepository) UpdatePaymentMethods(id, paymentMethod string) (bool, error) { - ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) - defer cancel() - - av := &dynamodb.AttributeValue{ - S: aws.String(paymentMethod), - } - - var methodList []*dynamodb.AttributeValue - methodList = append(methodList, av) - - input := &dynamodb.UpdateItemInput{ - ExpressionAttributeValues: map[string]*dynamodb.AttributeValue{ - ":method": { - L: methodList, - }, - ":methodStr": av, - }, - Key: map[string]*dynamodb.AttributeValue{ - "id": { - S: aws.String(id), - }, - }, - ReturnValues: aws.String("UPDATED_NEW"), - UpdateExpression: aws.String( - "set methods = list_append (methods, :method)", - ), - ConditionExpression: aws.String("not contains (methods, :methodStr)"), - TableName: aws.String("paymentmethod"), - } - - _, err := pdr.Session.UpdateItemWithContext(ctx, input) - if err != nil { - return false, fmt.Errorf("unable to update - %s", err.Error()) - } - return true, nil -} - -func NewDynamoRepository() PaymentDynamoRepository { - svc := connect() - return PaymentDynamoRepository{Session: svc} -} - -func _toDynamoPayModel(p *domain.Payment, bank, wallet string) PayModel { - return PayModel{ - Id: p.Id, - Amount: p.Amount, - Currency: p.Currency, - Status: p.Status, - OrderID: p.OrderID, - Method: p.Method, - Description: p.Description, - Bank: bank, - Wallet: wallet, - VPA: p.VPA, - UserID: p.UserID, - Notes: p.Notes, - CreatedAt: time.Now(), - UpdatedAt: time.Now(), - } -} - -func _toDynamoPayMethodModel(p *domain.PaymentMethod) PaymentMethodModel { - return PaymentMethodModel{ - Id: p.Id, - Methods: p.Method, - Agree: p.Agree, - Comment: p.Comment, - } -} diff --git a/payment/infra/gokafka/producer.go b/payment/infra/gokafka/producer.go deleted file mode 100644 index f56b163..0000000 --- a/payment/infra/gokafka/producer.go +++ /dev/null @@ -1,57 +0,0 @@ -package gokafka - -import ( - "context" - "encoding/json" - "math/rand" - "time" - - "github.com/swiggy-2022-bootcamp/cdp-team4/payment/infra/logger" - - kafka "github.com/segmentio/kafka-go" - "github.com/sirupsen/logrus" -) - -var brokers = []string{ - "localhost:9091", -} -var log logrus.Logger = *logger.GetLogger() - -func getRandomKey() []byte { - var src = rand.NewSource(time.Now().UnixNano()) - return []byte(string(src.Int63())) -} - -func getProducer(ctx context.Context, topic string, brokers []string) *kafka.Writer { - // intialize the writer with the broker addresses, and the topic - return kafka.NewWriter(kafka.WriterConfig{ - Brokers: brokers, - Topic: topic, - }) -} - -func WriteMsgToKafka(topic string, msg interface{}) (bool, error) { - ctx := context.Background() - jsonString, err := json.Marshal(msg) - msgString := string(jsonString) - - if err != nil { - return false, err - } - - writer := getProducer(ctx, topic, brokers) - defer writer.Close() - - err = writer.WriteMessages(ctx, kafka.Message{ - Key: getRandomKey(), - Value: []byte(msgString), - }) - - if err != nil { - log.WithFields(logrus.Fields{"error": err.Error(), "msg": msg}). - Error("could not write message ") - return false, err - } - - return true, nil -} diff --git a/payment/infra/logger/logger.go b/payment/infra/logger/logger.go deleted file mode 100644 index adef19d..0000000 --- a/payment/infra/logger/logger.go +++ /dev/null @@ -1,44 +0,0 @@ -package logger - -import ( - "fmt" - "io" - "os" - "sync" - - "github.com/joho/godotenv" - "github.com/sirupsen/logrus" -) - -var logger *logrus.Logger - -// Singleton Pattern -func GetLogger() *logrus.Logger { - - var once sync.Once - if logger == nil { - once.Do( - func() { - logger = logrus.New() - - err := godotenv.Load(".env") - if err != nil { - return - } - LOG_FILE := os.Getenv("LOG_FILE") - src, err := os.OpenFile(LOG_FILE, os.O_APPEND|os.O_WRONLY, os.ModeAppend) - - if err != nil { - fmt.Print(err.Error()) - fmt.Print("unable to create log file") - } - - multiWriter := io.MultiWriter(os.Stdout, src) - - logger.SetFormatter(&logrus.JSONFormatter{}) - logger.SetOutput(multiWriter) - }) - } - - return logger -} diff --git a/payment/infra/paymentModel.go b/payment/infra/paymentModel.go deleted file mode 100644 index 4bc7947..0000000 --- a/payment/infra/paymentModel.go +++ /dev/null @@ -1,29 +0,0 @@ -package infra - -import ( - "time" -) - -type PayModel struct { - Id string `json:"id"` - Amount int16 `json:"amount"` - Currency string `json:"currency"` - Status string `json:"status"` - OrderID string `json:"order_id"` - Method string `json:"method"` - Description string `json:"description"` - Bank string `json:"bank"` - Wallet string `json:"wallet"` - VPA string `json:"vpa"` - UserID string `json:"user_id"` - Notes []string `json:"notes"` - CreatedAt time.Time `json:"created_at"` - UpdatedAt time.Time `json:"updated_at"` -} - -type PaymentMethodModel struct { - Id string `json:"id"` - Methods []string `json:"methods"` - Agree string `json:"agree"` - Comment string `json:"comment"` -} diff --git a/payment/main.go b/payment/main.go deleted file mode 100644 index 4b52be6..0000000 --- a/payment/main.go +++ /dev/null @@ -1,20 +0,0 @@ -package main - -import "github.com/swiggy-2022-bootcamp/cdp-team4/payment/app" - -// @title Payment API -// @version 1.0 -// @description Payment Service. -// @termsOfService http://swagger.io/terms/ - -// @contact.name API Support -// @contact.url http://www.swagger.io/support -// @contact.email support@swagger.io - -// @license.name Apache 2.0 -// @license.url http://www.apache.org/licenses/LICENSE-2.0.html - -// @BasePath / -func main() { - app.Start(false /*testMode*/) -} diff --git a/payment/mocks/domain/PaymentDynamoRepository.go b/payment/mocks/domain/PaymentDynamoRepository.go deleted file mode 100644 index 12e29cb..0000000 --- a/payment/mocks/domain/PaymentDynamoRepository.go +++ /dev/null @@ -1,187 +0,0 @@ -// Code generated by mockery v2.10.6. DO NOT EDIT. - -package mocks - -import ( - mock "github.com/stretchr/testify/mock" - domain "github.com/swiggy-2022-bootcamp/cdp-team4/payment/domain" -) - -// PaymentDynamoRepository is an autogenerated mock type for the PaymentDynamoRepository type -type PaymentDynamoRepository struct { - mock.Mock -} - -// DeletePaymentRecordByID provides a mock function with given fields: _a0 -func (_m *PaymentDynamoRepository) DeletePaymentRecordByID(_a0 string) (bool, error) { - ret := _m.Called(_a0) - - var r0 bool - if rf, ok := ret.Get(0).(func(string) bool); ok { - r0 = rf(_a0) - } else { - r0 = ret.Get(0).(bool) - } - - var r1 error - if rf, ok := ret.Get(1).(func(string) error); ok { - r1 = rf(_a0) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// FindPaymentRecordById provides a mock function with given fields: _a0 -func (_m *PaymentDynamoRepository) FindPaymentRecordById(_a0 string) (*domain.Payment, error) { - ret := _m.Called(_a0) - - var r0 *domain.Payment - if rf, ok := ret.Get(0).(func(string) *domain.Payment); ok { - r0 = rf(_a0) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*domain.Payment) - } - } - - var r1 error - if rf, ok := ret.Get(1).(func(string) error); ok { - r1 = rf(_a0) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// FindPaymentRecordByUserID provides a mock function with given fields: _a0 -func (_m *PaymentDynamoRepository) FindPaymentRecordByUserID(_a0 string) ([]domain.Payment, error) { - ret := _m.Called(_a0) - - var r0 []domain.Payment - if rf, ok := ret.Get(0).(func(string) []domain.Payment); ok { - r0 = rf(_a0) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).([]domain.Payment) - } - } - - var r1 error - if rf, ok := ret.Get(1).(func(string) error); ok { - r1 = rf(_a0) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// GetPaymentMethods provides a mock function with given fields: _a0 -func (_m *PaymentDynamoRepository) GetPaymentMethods(_a0 string) ([]string, error) { - ret := _m.Called(_a0) - - var r0 []string - if rf, ok := ret.Get(0).(func(string) []string); ok { - r0 = rf(_a0) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).([]string) - } - } - - var r1 error - if rf, ok := ret.Get(1).(func(string) error); ok { - r1 = rf(_a0) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// InsertPaymentMethod provides a mock function with given fields: _a0 -func (_m *PaymentDynamoRepository) InsertPaymentMethod(_a0 domain.PaymentMethod) (bool, error) { - ret := _m.Called(_a0) - - var r0 bool - if rf, ok := ret.Get(0).(func(domain.PaymentMethod) bool); ok { - r0 = rf(_a0) - } else { - r0 = ret.Get(0).(bool) - } - - var r1 error - if rf, ok := ret.Get(1).(func(domain.PaymentMethod) error); ok { - r1 = rf(_a0) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// InsertPaymentRecord provides a mock function with given fields: _a0 -func (_m *PaymentDynamoRepository) InsertPaymentRecord(_a0 domain.Payment) (bool, error) { - ret := _m.Called(_a0) - - var r0 bool - if rf, ok := ret.Get(0).(func(domain.Payment) bool); ok { - r0 = rf(_a0) - } else { - r0 = ret.Get(0).(bool) - } - - var r1 error - if rf, ok := ret.Get(1).(func(domain.Payment) error); ok { - r1 = rf(_a0) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// UpdatePaymentMethods provides a mock function with given fields: _a0, _a1 -func (_m *PaymentDynamoRepository) UpdatePaymentMethods(_a0 string, _a1 string) (bool, error) { - ret := _m.Called(_a0, _a1) - - var r0 bool - if rf, ok := ret.Get(0).(func(string, string) bool); ok { - r0 = rf(_a0, _a1) - } else { - r0 = ret.Get(0).(bool) - } - - var r1 error - if rf, ok := ret.Get(1).(func(string, string) error); ok { - r1 = rf(_a0, _a1) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// UpdatePaymentRecord provides a mock function with given fields: _a0, _a1 -func (_m *PaymentDynamoRepository) UpdatePaymentRecord(_a0 string, _a1 string) (bool, error) { - ret := _m.Called(_a0, _a1) - - var r0 bool - if rf, ok := ret.Get(0).(func(string, string) bool); ok { - r0 = rf(_a0, _a1) - } else { - r0 = ret.Get(0).(bool) - } - - var r1 error - if rf, ok := ret.Get(1).(func(string, string) error); ok { - r1 = rf(_a0, _a1) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} diff --git a/payment/mocks/domain/PaymentService.go b/payment/mocks/domain/PaymentService.go deleted file mode 100644 index 300014c..0000000 --- a/payment/mocks/domain/PaymentService.go +++ /dev/null @@ -1,166 +0,0 @@ -// Code generated by mockery v2.10.6. DO NOT EDIT. - -package mocks - -import ( - mock "github.com/stretchr/testify/mock" - domain "github.com/swiggy-2022-bootcamp/cdp-team4/payment/domain" -) - -// PaymentService is an autogenerated mock type for the PaymentService type -type PaymentService struct { - mock.Mock -} - -// AddPaymentMethod provides a mock function with given fields: _a0, _a1, _a2, _a3 -func (_m *PaymentService) AddPaymentMethod(_a0 string, _a1 string, _a2 string, _a3 string) (bool, error) { - ret := _m.Called(_a0, _a1, _a2, _a3) - - var r0 bool - if rf, ok := ret.Get(0).(func(string, string, string, string) bool); ok { - r0 = rf(_a0, _a1, _a2, _a3) - } else { - r0 = ret.Get(0).(bool) - } - - var r1 error - if rf, ok := ret.Get(1).(func(string, string, string, string) error); ok { - r1 = rf(_a0, _a1, _a2, _a3) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// CreateDynamoPaymentRecord provides a mock function with given fields: _a0, _a1, _a2, _a3, _a4, _a5, _a6, _a7, _a8 -func (_m *PaymentService) CreateDynamoPaymentRecord(_a0 int16, _a1 string, _a2 string, _a3 string, _a4 string, _a5 string, _a6 string, _a7 string, _a8 []string) (bool, error) { - ret := _m.Called(_a0, _a1, _a2, _a3, _a4, _a5, _a6, _a7, _a8) - - var r0 bool - if rf, ok := ret.Get(0).(func(int16, string, string, string, string, string, string, string, []string) bool); ok { - r0 = rf(_a0, _a1, _a2, _a3, _a4, _a5, _a6, _a7, _a8) - } else { - r0 = ret.Get(0).(bool) - } - - var r1 error - if rf, ok := ret.Get(1).(func(int16, string, string, string, string, string, string, string, []string) error); ok { - r1 = rf(_a0, _a1, _a2, _a3, _a4, _a5, _a6, _a7, _a8) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// GetPaymentAllRecordsByUserId provides a mock function with given fields: _a0 -func (_m *PaymentService) GetPaymentAllRecordsByUserId(_a0 string) ([]domain.Payment, error) { - ret := _m.Called(_a0) - - var r0 []domain.Payment - if rf, ok := ret.Get(0).(func(string) []domain.Payment); ok { - r0 = rf(_a0) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).([]domain.Payment) - } - } - - var r1 error - if rf, ok := ret.Get(1).(func(string) error); ok { - r1 = rf(_a0) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// GetPaymentMethods provides a mock function with given fields: _a0 -func (_m *PaymentService) GetPaymentMethods(_a0 string) ([]string, error) { - ret := _m.Called(_a0) - - var r0 []string - if rf, ok := ret.Get(0).(func(string) []string); ok { - r0 = rf(_a0) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).([]string) - } - } - - var r1 error - if rf, ok := ret.Get(1).(func(string) error); ok { - r1 = rf(_a0) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// GetPaymentRecordById provides a mock function with given fields: _a0 -func (_m *PaymentService) GetPaymentRecordById(_a0 string) (*domain.Payment, error) { - ret := _m.Called(_a0) - - var r0 *domain.Payment - if rf, ok := ret.Get(0).(func(string) *domain.Payment); ok { - r0 = rf(_a0) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*domain.Payment) - } - } - - var r1 error - if rf, ok := ret.Get(1).(func(string) error); ok { - r1 = rf(_a0) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// UpdatePaymentMethod provides a mock function with given fields: _a0, _a1 -func (_m *PaymentService) UpdatePaymentMethod(_a0 string, _a1 string) (bool, error) { - ret := _m.Called(_a0, _a1) - - var r0 bool - if rf, ok := ret.Get(0).(func(string, string) bool); ok { - r0 = rf(_a0, _a1) - } else { - r0 = ret.Get(0).(bool) - } - - var r1 error - if rf, ok := ret.Get(1).(func(string, string) error); ok { - r1 = rf(_a0, _a1) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// UpdatePaymentStatus provides a mock function with given fields: _a0, _a1 -func (_m *PaymentService) UpdatePaymentStatus(_a0 string, _a1 string) (bool, error) { - ret := _m.Called(_a0, _a1) - - var r0 bool - if rf, ok := ret.Get(0).(func(string, string) bool); ok { - r0 = rf(_a0, _a1) - } else { - r0 = ret.Get(0).(bool) - } - - var r1 error - if rf, ok := ret.Get(1).(func(string, string) error); ok { - r1 = rf(_a0, _a1) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} diff --git a/user/.gitignore b/user/.gitignore deleted file mode 100644 index 4bf8519..0000000 --- a/user/.gitignore +++ /dev/null @@ -1,17 +0,0 @@ -# Binaries for programs and plugins -*.exe -*.exe~ -*.dll -*.so -*.dylib - -# Test binary, built with `go test -c` -*.test - -# Output of the go coverage tool, specifically when used with LiteIDE -*.out - -# Dependency directories (remove the comment below to include it) -# vendor/ - -.env \ No newline at end of file diff --git a/user/Dockerfile b/user/Dockerfile deleted file mode 100644 index f76035c..0000000 --- a/user/Dockerfile +++ /dev/null @@ -1,17 +0,0 @@ -FROM golang:1.17-alpine - -RUN apk update && apk add --no-cache git build-base - -WORKDIR /go/github.com/swiggy-2022-bootcamp/cdp-team4/User - -COPY . /go/github.com/swiggy-2022-bootcamp/cdp-team4/User - -# get all the dependencies -RUN go get ./... - -# build -RUN go build -o /UserService - -EXPOSE 8000 - -CMD [ "/UserService" ] \ No newline at end of file diff --git a/user/app/app.go b/user/app/app.go deleted file mode 100644 index 453eab2..0000000 --- a/user/app/app.go +++ /dev/null @@ -1,59 +0,0 @@ -package app - -import ( - "log" - "os" - - "github.com/gin-gonic/gin" - - "github.com/joho/godotenv" - "github.com/swiggy-2022-bootcamp/cdp-team4/user/docs" - - swaggerFiles "github.com/swaggo/files" - ginSwagger "github.com/swaggo/gin-swagger" // gin-swagger middleware - - "github.com/swiggy-2022-bootcamp/cdp-team4/user/infra" - "github.com/swiggy-2022-bootcamp/cdp-team4/user/domain" -) - -type Routes struct { - router *gin.Engine -} - -var userHandler UserHandler - -func setupRouter() *gin.Engine { - router := gin.Default() - - // health check route - HealthCheckRouter(router) - - // user route - UserRouter(router) - router.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler)) - return router -} - -func configureSwaggerDoc() { - docs.SwaggerInfo.Title = "Swagger User API" -} - -func Start() { - err := godotenv.Load(".env") - if err != nil { - log.Fatal(err) - return - } - PORT := os.Getenv("PORT") - - userDynamodbRepository := infra.NewDynamoRepository() - - userHandler = UserHandler{ - userService: domain.NewUserService(userDynamodbRepository), - } - - configureSwaggerDoc() - router := setupRouter() - - router.Run(":" + PORT) -} \ No newline at end of file diff --git a/user/app/healthHandler.go b/user/app/healthHandler.go deleted file mode 100644 index 7e6db07..0000000 --- a/user/app/healthHandler.go +++ /dev/null @@ -1,21 +0,0 @@ -package app - -import ( - "net/http" - - "github.com/gin-gonic/gin" -) - -// Health Check -// @Summary Health of user service -// @Description use tocheck whether user service is up and running or not -// @Tags Health -// @Produce json -// @Success 200 {object} map[string]interface{} -// @Failure 400 {number} http.StatusBadRequest -// @Router / [get] -func HealthCheck() gin.HandlerFunc { - return func(c *gin.Context) { - c.JSON(http.StatusOK, gin.H{"message": "Service is running"}) - } -} \ No newline at end of file diff --git a/user/app/routes.go b/user/app/routes.go deleted file mode 100644 index a919b21..0000000 --- a/user/app/routes.go +++ /dev/null @@ -1,17 +0,0 @@ -package app - -import ( - "github.com/gin-gonic/gin" -) - -func HealthCheckRouter(gin *gin.Engine) { - gin.GET("/", HealthCheck()) -} - -func UserRouter(gin *gin.Engine) { - gin.POST("/user", userHandler.HandleUserCreation()) - gin.GET("/users", userHandler.HandleGetAllUsers()) - gin.GET("/user/:id", userHandler.HandleGetUserByID()) - gin.PATCH("/user/:id", userHandler.HandleUpdateUserByID()) - gin.DELETE("/user/:id", userHandler.HandleDeleteUserByID()) -} \ No newline at end of file diff --git a/user/app/userHandler.go b/user/app/userHandler.go deleted file mode 100644 index 6dc5352..0000000 --- a/user/app/userHandler.go +++ /dev/null @@ -1,182 +0,0 @@ -package app - -import ( - "net/http" - "github.com/gin-gonic/gin" - "github.com/swiggy-2022-bootcamp/cdp-team4/user/domain" -) - -type UserHandler struct { - userService domain.UserService -} - -type userDTO struct { - FirstName string `json:"first_name"` - LastName string `json:"last_name"` - Username string `json:"username"` - Password string `json:"password"` - Phone string `json:"phone"` - Email string `json:"email"` - Role int `json:"role"` -} - -// @Summary Create User -// @Description To register a new user for the app. -// @Tags User -// @Schemes -// @Accept json -// @Produce json -// @Param user body domain.User true "User structure" -// @Success 201 {string} http.StatusCreated -// @Failure 400 {number} http.http.StatusBadRequest -// @Router /user [POST] -func (h UserHandler) HandleUserCreation() gin.HandlerFunc { - return func (ctx *gin.Context) { - var newUser userDTO - - if err := ctx.BindJSON(&newUser); err != nil { - ctx.JSON(http.StatusBadRequest, gin.H{"message": err.Error()}) - return - } - - role, err := domain.GetEnumByIndex(newUser.Role) - if err != nil { - ctx.JSON(http.StatusInternalServerError, gin.H{"message": err.Error()}) - return - } - - user, err1 := h.userService.CreateUserInDynamodb( - newUser.FirstName, - newUser.LastName, - newUser.Username, - newUser.Phone, - newUser.Email, - newUser.Password, - role, - ) - - if err1 != nil { - ctx.JSON(http.StatusInternalServerError, err1) - } else { - data, _ := user.MarshalJSON() - ctx.Data(http.StatusCreated, "application/json", data) - } - } -} - -// @Summary Get User -// @Description To get user details. -// @Tags User -// @Schemes -// @Accept json -// @Param id path string true "User Name" -// @Produce json -// @Success 202 {object} domain.User -// @Failure 400 {number} http.StatusBadRequest -// @Security Bearer Token -// @Router /user/{id} [GET] -func (h UserHandler) HandleGetUserByID() gin.HandlerFunc { - return func(ctx *gin.Context) { - id := ctx.Param("id") - record, err := h.userService.GetUserById(id) - - if err != nil { - ctx.JSON(http.StatusBadRequest, gin.H{"message": err.Error()}) - return - } - ctx.JSON(http.StatusAccepted, gin.H{"record": record}) - } -} - - -// @Summary Get all User details -// @Description To get every user detail. -// @Tags User -// @Schemes -// @Accept json -// @Produce json -// @Success 200 {array} domain.User -// @Failure 400 {number} http.StatusBadRequest -// @Router /users [GET] -func (h UserHandler) HandleGetAllUsers() gin.HandlerFunc { - return func(ctx *gin.Context) { - records, err := h.userService.GetAllUsers() - - if err != nil { - ctx.JSON(http.StatusBadRequest, gin.H{"message": err.Error()}) - return - } - ctx.JSON(http.StatusAccepted, gin.H{"records": records}) - } -} - - -// @Summary Update User -// @Description To update user -// @Tags User -// @Schemes -// @Accept json -// @Param id path string true "User Name" -// @Param user body domain.User true "User structure" -// @Produce json -// @Success 202 {string} domain.User -// @Failure 500 {number} http.StatusInternalServerError -// @Router /user/{id} [PATCH] -func (h UserHandler) HandleUpdateUserByID() gin.HandlerFunc { - return func (ctx *gin.Context) { - var newUpdatedUser userDTO - userId := ctx.Param("id") - - if err := ctx.BindJSON(&newUpdatedUser); err != nil { - ctx.JSON(http.StatusBadRequest, gin.H{"message": err.Error()}) - return - } - - role, err := domain.GetEnumByIndex(newUpdatedUser.Role) - if err != nil { - ctx.JSON(http.StatusInternalServerError, gin.H{"message": err.Error()}) - return - } - - _, err1 := h.userService.UpdateUserById( - userId, - newUpdatedUser.FirstName, - newUpdatedUser.LastName, - newUpdatedUser.Username, - newUpdatedUser.Phone, - newUpdatedUser.Email, - newUpdatedUser.Password, - role, - ) - - if err1 != nil { - ctx.JSON(http.StatusInternalServerError, err1) - } else { - ctx.JSON(http.StatusAccepted, gin.H{"message": "user updated"}) - } - } -} - - -// @Summary Delete User -// @Description To remove a particular user. -// @Tags User -// @Schemes -// @Accept json -// @Param id path string true "User Name" -// @Produce json -// @Success 202 {string} http.StatusAccepted -// @Failure 400 {number} http.StatusBadRequest -// @Router /user/{id} [DELETE] -func (h UserHandler) HandleDeleteUserByID() gin.HandlerFunc { - return func(ctx *gin.Context) { - id := ctx.Param("id") - ok, err := h.userService.DeleteUserById(id) - - if !ok { - ctx.JSON(http.StatusBadRequest, gin.H{"message": err.Error()}) - return - } - ctx.JSON(http.StatusAccepted, gin.H{"message": "user deleted"}) - } -} \ No newline at end of file diff --git a/user/docs/docs.go b/user/docs/docs.go deleted file mode 100644 index 4f55f9e..0000000 --- a/user/docs/docs.go +++ /dev/null @@ -1,299 +0,0 @@ -// Package docs GENERATED BY SWAG; DO NOT EDIT -// This file was generated by swaggo/swag -package docs - -import "github.com/swaggo/swag" - -const docTemplate = `{ - "schemes": {{ marshal .Schemes }}, - "swagger": "2.0", - "info": { - "description": "{{escape .Description}}", - "title": "{{.Title}}", - "termsOfService": "http://swagger.io/terms/", - "contact": { - "name": "API Support", - "url": "http://www.swagger.io/support", - "email": "support@swagger.io" - }, - "license": { - "name": "Apache 2.0", - "url": "http://www.apache.org/licenses/LICENSE-2.0.html" - }, - "version": "{{.Version}}" - }, - "host": "{{.Host}}", - "basePath": "{{.BasePath}}", - "paths": { - "/": { - "get": { - "description": "use tocheck whether user service is up and running or not", - "produces": [ - "application/json" - ], - "tags": [ - "Health" - ], - "summary": "Health of user service", - "responses": { - "200": { - "description": "OK", - "schema": { - "type": "object", - "additionalProperties": true - } - }, - "400": { - "description": "Bad Request", - "schema": { - "type": "number" - } - } - } - } - }, - "/user": { - "post": { - "description": "To register a new user for the app.", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "User" - ], - "summary": "Create User", - "parameters": [ - { - "description": "User structure", - "name": "user", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/domain.User" - } - } - ], - "responses": { - "201": { - "description": "Created", - "schema": { - "type": "string" - } - }, - "400": { - "description": "Bad Request", - "schema": { - "type": "number" - } - } - } - } - }, - "/user/{id}": { - "get": { - "security": [ - { - "Bearer Token": [] - } - ], - "description": "To get user details.", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "User" - ], - "summary": "Get User", - "parameters": [ - { - "type": "string", - "description": "User Name", - "name": "id", - "in": "path", - "required": true - } - ], - "responses": { - "202": { - "description": "Accepted", - "schema": { - "$ref": "#/definitions/domain.User" - } - }, - "400": { - "description": "Bad Request", - "schema": { - "type": "number" - } - } - } - }, - "delete": { - "description": "To remove a particular user.", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "User" - ], - "summary": "Delete User", - "parameters": [ - { - "type": "string", - "description": "User Name", - "name": "id", - "in": "path", - "required": true - } - ], - "responses": { - "202": { - "description": "Accepted", - "schema": { - "type": "string" - } - }, - "400": { - "description": "Bad Request", - "schema": { - "type": "number" - } - } - } - }, - "patch": { - "description": "To update user", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "User" - ], - "summary": "Update User", - "parameters": [ - { - "type": "string", - "description": "User Name", - "name": "id", - "in": "path", - "required": true - }, - { - "description": "User structure", - "name": "user", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/domain.User" - } - } - ], - "responses": { - "202": { - "description": "Accepted", - "schema": { - "type": "string" - } - }, - "500": { - "description": "Internal Server Error", - "schema": { - "type": "number" - } - } - } - } - }, - "/users": { - "get": { - "description": "To get every user detail.", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "User" - ], - "summary": "Get all User details", - "responses": { - "200": { - "description": "OK", - "schema": { - "type": "array", - "items": { - "$ref": "#/definitions/domain.User" - } - } - }, - "400": { - "description": "Bad Request", - "schema": { - "type": "number" - } - } - } - } - } - }, - "definitions": { - "domain.User": { - "type": "object", - "properties": { - "email": { - "type": "string" - }, - "first_name": { - "type": "string" - }, - "last_name": { - "type": "string" - }, - "password": { - "type": "string" - }, - "phone": { - "type": "string" - }, - "role": { - "type": "integer" - }, - "user_id": { - "type": "string" - }, - "username": { - "type": "string" - } - } - } - } -}` - -// SwaggerInfo holds exported Swagger Info so clients can modify it -var SwaggerInfo = &swag.Spec{ - Version: "1.0", - Host: "", - BasePath: "/", - Schemes: []string{}, - Title: "User API", - Description: "User Service.", - InfoInstanceName: "swagger", - SwaggerTemplate: docTemplate, -} - -func init() { - swag.Register(SwaggerInfo.InstanceName(), SwaggerInfo) -} diff --git a/user/docs/swagger.json b/user/docs/swagger.json deleted file mode 100644 index e19e762..0000000 --- a/user/docs/swagger.json +++ /dev/null @@ -1,275 +0,0 @@ -{ - "swagger": "2.0", - "info": { - "description": "User Service.", - "title": "User API", - "termsOfService": "http://swagger.io/terms/", - "contact": { - "name": "API Support", - "url": "http://www.swagger.io/support", - "email": "support@swagger.io" - }, - "license": { - "name": "Apache 2.0", - "url": "http://www.apache.org/licenses/LICENSE-2.0.html" - }, - "version": "1.0" - }, - "basePath": "/", - "paths": { - "/": { - "get": { - "description": "use tocheck whether user service is up and running or not", - "produces": [ - "application/json" - ], - "tags": [ - "Health" - ], - "summary": "Health of user service", - "responses": { - "200": { - "description": "OK", - "schema": { - "type": "object", - "additionalProperties": true - } - }, - "400": { - "description": "Bad Request", - "schema": { - "type": "number" - } - } - } - } - }, - "/user": { - "post": { - "description": "To register a new user for the app.", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "User" - ], - "summary": "Create User", - "parameters": [ - { - "description": "User structure", - "name": "user", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/domain.User" - } - } - ], - "responses": { - "201": { - "description": "Created", - "schema": { - "type": "string" - } - }, - "400": { - "description": "Bad Request", - "schema": { - "type": "number" - } - } - } - } - }, - "/user/{id}": { - "get": { - "security": [ - { - "Bearer Token": [] - } - ], - "description": "To get user details.", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "User" - ], - "summary": "Get User", - "parameters": [ - { - "type": "string", - "description": "User Name", - "name": "id", - "in": "path", - "required": true - } - ], - "responses": { - "202": { - "description": "Accepted", - "schema": { - "$ref": "#/definitions/domain.User" - } - }, - "400": { - "description": "Bad Request", - "schema": { - "type": "number" - } - } - } - }, - "delete": { - "description": "To remove a particular user.", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "User" - ], - "summary": "Delete User", - "parameters": [ - { - "type": "string", - "description": "User Name", - "name": "id", - "in": "path", - "required": true - } - ], - "responses": { - "202": { - "description": "Accepted", - "schema": { - "type": "string" - } - }, - "400": { - "description": "Bad Request", - "schema": { - "type": "number" - } - } - } - }, - "patch": { - "description": "To update user", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "User" - ], - "summary": "Update User", - "parameters": [ - { - "type": "string", - "description": "User Name", - "name": "id", - "in": "path", - "required": true - }, - { - "description": "User structure", - "name": "user", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/domain.User" - } - } - ], - "responses": { - "202": { - "description": "Accepted", - "schema": { - "type": "string" - } - }, - "500": { - "description": "Internal Server Error", - "schema": { - "type": "number" - } - } - } - } - }, - "/users": { - "get": { - "description": "To get every user detail.", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "User" - ], - "summary": "Get all User details", - "responses": { - "200": { - "description": "OK", - "schema": { - "type": "array", - "items": { - "$ref": "#/definitions/domain.User" - } - } - }, - "400": { - "description": "Bad Request", - "schema": { - "type": "number" - } - } - } - } - } - }, - "definitions": { - "domain.User": { - "type": "object", - "properties": { - "email": { - "type": "string" - }, - "first_name": { - "type": "string" - }, - "last_name": { - "type": "string" - }, - "password": { - "type": "string" - }, - "phone": { - "type": "string" - }, - "role": { - "type": "integer" - }, - "user_id": { - "type": "string" - }, - "username": { - "type": "string" - } - } - } - } -} \ No newline at end of file diff --git a/user/docs/swagger.yaml b/user/docs/swagger.yaml deleted file mode 100644 index 9622c70..0000000 --- a/user/docs/swagger.yaml +++ /dev/null @@ -1,181 +0,0 @@ -basePath: / -definitions: - domain.User: - properties: - email: - type: string - first_name: - type: string - last_name: - type: string - password: - type: string - phone: - type: string - role: - type: integer - user_id: - type: string - username: - type: string - type: object -info: - contact: - email: support@swagger.io - name: API Support - url: http://www.swagger.io/support - description: User Service. - license: - name: Apache 2.0 - url: http://www.apache.org/licenses/LICENSE-2.0.html - termsOfService: http://swagger.io/terms/ - title: User API - version: "1.0" -paths: - /: - get: - description: use tocheck whether user service is up and running or not - produces: - - application/json - responses: - "200": - description: OK - schema: - additionalProperties: true - type: object - "400": - description: Bad Request - schema: - type: number - summary: Health of user service - tags: - - Health - /user: - post: - consumes: - - application/json - description: To register a new user for the app. - parameters: - - description: User structure - in: body - name: user - required: true - schema: - $ref: '#/definitions/domain.User' - produces: - - application/json - responses: - "201": - description: Created - schema: - type: string - "400": - description: Bad Request - schema: - type: number - summary: Create User - tags: - - User - /user/{id}: - delete: - consumes: - - application/json - description: To remove a particular user. - parameters: - - description: User Name - in: path - name: id - required: true - type: string - produces: - - application/json - responses: - "202": - description: Accepted - schema: - type: string - "400": - description: Bad Request - schema: - type: number - summary: Delete User - tags: - - User - get: - consumes: - - application/json - description: To get user details. - parameters: - - description: User Name - in: path - name: id - required: true - type: string - produces: - - application/json - responses: - "202": - description: Accepted - schema: - $ref: '#/definitions/domain.User' - "400": - description: Bad Request - schema: - type: number - security: - - Bearer Token: [] - summary: Get User - tags: - - User - patch: - consumes: - - application/json - description: To update user - parameters: - - description: User Name - in: path - name: id - required: true - type: string - - description: User structure - in: body - name: user - required: true - schema: - $ref: '#/definitions/domain.User' - produces: - - application/json - responses: - "202": - description: Accepted - schema: - type: string - "500": - description: Internal Server Error - schema: - type: number - summary: Update User - tags: - - User - /users: - get: - consumes: - - application/json - description: To get every user detail. - produces: - - application/json - responses: - "200": - description: OK - schema: - items: - $ref: '#/definitions/domain.User' - type: array - "400": - description: Bad Request - schema: - type: number - summary: Get all User details - tags: - - User -swagger: "2.0" diff --git a/user/domain/user.go b/user/domain/user.go deleted file mode 100644 index e51177b..0000000 --- a/user/domain/user.go +++ /dev/null @@ -1,78 +0,0 @@ -package domain - -import ( - "encoding/json" - "github.com/swiggy-2022-bootcamp/cdp-team4/user/utils/errs" -) - -type Role int - -const ( - Admin Role = iota // EnumIndex = 0 - Customer // EnumIndex = 1 -) - -func (r Role) String() string { - return [...]string{"admin", "seller", "customer"}[r] -} - -func (r Role) EnumIndex() int { - return int(r) -} - -func GetEnumByIndex(idx int) (Role, *errs.AppError) { - switch idx { - case 0: - return Admin, nil - case 1: - return Customer, nil - default: - return -1, errs.NewUnexpectedError("invalid enum index") - } -} - -type User struct { - UserID string `json:"user_id"` - FirstName string `json:"first_name"` - LastName string `json:"last_name"` - Username string `json:"username"` - Password string `json:"password"` - Phone string `json:"phone"` - Email string `json:"email"` - Role Role `json:"role"` -} - -func (u User) MarshalJSON() ([]byte, error) { - return json.Marshal(map[string]interface{}{ - "user_id": u.UserID, - "firstName": u.FirstName, - "lastName": u.LastName, - "email": u.Email, - "password": u.Password, - "username": u.Username, - "phone": u.Phone, - "role": u.Role, - }) -} - -func NewUser(userId, firstName, lastName, username, phone, email, password string, role Role) *User { - return &User{ - UserID: userId, - FirstName: firstName, - LastName: lastName, - Username: username, - Phone: phone, - Email: email, - Password: password, - Role: role, - } -} - -type UserDynamoDBRepository interface { - Save(User) (User, error) - FindByID(string) (*User, error) - UpdateById(User) (bool, error) - DeleteByID(string) (bool, error) - FindAll() ([]User, error) -} - diff --git a/user/domain/userService.go b/user/domain/userService.go deleted file mode 100644 index a6125dd..0000000 --- a/user/domain/userService.go +++ /dev/null @@ -1,93 +0,0 @@ -package domain - -import ( - "golang.org/x/crypto/bcrypt" - "go.mongodb.org/mongo-driver/bson/primitive" - "fmt" -) - -type UserService interface { - CreateUserInDynamodb(string, string, string, string, string, string, Role) (User, error) - GetUserById(string) (*User, error) - GetAllUsers() ([]User, error) - UpdateUserById(user_id, firstName, lastName, username, phone, email, password string, role Role) (bool, error) - DeleteUserById(string) (bool, error) -} - -type service struct { - userDynamodbRepository UserDynamoDBRepository -} - -func NewUserService(userDynamodbRepository UserDynamoDBRepository) UserService { - return &service{ - userDynamodbRepository: userDynamodbRepository, - } -} - - -func (s service) CreateUserInDynamodb(firstName, lastName, username, phone, email, password string, role Role) (User, error) { - id := _generateUniqueId() - hashedPassword, err := HashPassword(password) - if err != nil { - return User{}, err - } - user := NewUser(id, firstName, lastName, username, phone, email, hashedPassword, role) - persistedUser, err1 := s.userDynamodbRepository.Save(*user) - if err1 != nil { - return User{}, err1 - } - return persistedUser, nil -} - - -func (s service) GetUserById(userId string) (*User, error) { - res, err := s.userDynamodbRepository.FindByID(userId) - if err != nil { - return nil, err - } - return res, nil -} - - -func (s service) GetAllUsers() ([]User, error) { - res, err := s.userDynamodbRepository.FindAll() - if err != nil { - return nil, err - } - return res, nil -} - - -func (s service) UpdateUserById(user_id, firstName, lastName, username, phone, email, password string, role Role) (bool, error) { - fmt.Println(user_id, firstName, lastName, username, phone, email, password, role) - - - user := NewUser(user_id, firstName, lastName, username, phone, email, password, role) - _, err := s.userDynamodbRepository.UpdateById(*user) - if err != nil { - return false, err - } - return true, err -} - - -func (s service) DeleteUserById(userId string) (bool, error) { - _, err := s.userDynamodbRepository.DeleteByID(userId) - if err != nil { - return false, err - } - return true, err -} - - -func _generateUniqueId() string { - return primitive.NewObjectID().Hex() -} - -func HashPassword(password string) (string, error) { - bytes, err := bcrypt.GenerateFromPassword([]byte(password), 14) - if err != nil { - return string(bytes), err - } - return string(bytes), nil -} \ No newline at end of file diff --git a/user/domain/userService_test.go b/user/domain/userService_test.go deleted file mode 100644 index 0e9ba0b..0000000 --- a/user/domain/userService_test.go +++ /dev/null @@ -1,93 +0,0 @@ -package domain_test - -import ( - "testing" - - "github.com/stretchr/testify/mock" - "github.com/swiggy-2022-bootcamp/cdp-team4/user/domain" - "github.com/swiggy-2022-bootcamp/cdp-team4/user/mocks" - // "github.com/swiggy-2022-bootcamp/cdp-team4/user/utils/errs" - - "github.com/stretchr/testify/assert" -) - -var mockUserRepo = mocks.UserDynamoDBRepository{} -var userService = domain.NewUserService(&mockUserRepo) - -func TestShouldReturnNewUserService(t *testing.T) { - userService := domain.NewUserService(nil) - assert.NotNil(t, userService) -} - -func TestShouldCreateNewUser(t *testing.T) { - userID := "afshsjgj14151jou" - firstName := "Swastik" - lastName := "Sahoo" - phone := "1234567890" - email := "swastiksahoo22@gmail.com" - username := "swastik153" - password, _ := domain.HashPassword("Pass!23") - role := domain.Admin - - user := domain.NewUser(userID, firstName, lastName, username, phone, email, password, role) - mockUserRepo.On("Save", mock.Anything).Return(*user, nil) - userService.CreateUserInDynamodb(firstName, lastName, username, phone, email, password, role) - mockUserRepo.AssertNumberOfCalls(t, "Save", 1) -} - -func TestShouldGetUserByUserId(t *testing.T) { - userID := "afshsjgj14151jou" - firstName := "Swastik" - lastName := "Sahoo" - phone := "1234567890" - email := "swastiksahoo22@gmail.com" - username := "swastik153" - password, _ := domain.HashPassword("Pass!23") - role := domain.Admin - user := domain.NewUser(userID, firstName, lastName, username, phone, email, password, role) - mockUserRepo.On("FindByID", userID).Return(user, nil) - var _, _ = userService.GetUserById(userID) - mockUserRepo.AssertNumberOfCalls(t, "FindByID", 1) -} - -func TestShouldGetAllUsers(t *testing.T) { - userID := "afshsjgj14151jou" - firstName := "Swastik" - lastName := "Sahoo" - phone := "1234567890" - email := "swastiksahoo22@gmail.com" - username := "swastik153" - password, _ := domain.HashPassword("Pass!23") - role := domain.Admin - user := domain.NewUser(userID, firstName, lastName, username, phone, email, password, role) - userArr := []domain.User{*user} - mockUserRepo.On("FindAll").Return(userArr, nil) - var _, _ = userService.GetAllUsers() - mockUserRepo.AssertNumberOfCalls(t, "FindAll", 1) -} - - -func TestShouldUpdateUserByUserId(t *testing.T) { - userID := "1" - firstName := "Swastik" - lastName := "Sahoo" - phone := "1234567890" - email := "swastiksahoo22@gmail.com" - username := "swastik153" - password, _ := domain.HashPassword("Pass!23") - role := domain.Admin - mockUserRepo.On("UpdateById", mock.Anything).Return(true, nil) - - var _, err = userService.UpdateUserById(userID, firstName, lastName, username, phone, email, password, role) - assert.Nil(t, err) -} - - -func TestShouldDeleteUserByUserId(t *testing.T) { - userId := "1" - mockUserRepo.On("DeleteByID", userId).Return(true, nil) - - var _, err = userService.DeleteUserById(userId) - assert.Nil(t, err) -} - diff --git a/user/domain/user_test.go b/user/domain/user_test.go deleted file mode 100644 index 1f9ffcd..0000000 --- a/user/domain/user_test.go +++ /dev/null @@ -1,212 +0,0 @@ -package domain - -import ( - "testing" - - "github.com/stretchr/testify/assert" -) - -func TestShouldGetRoleString(t *testing.T) { - role := Admin - var expected string = "admin" - var actual string = role.String() - - assert.Equal(t, expected, actual) -} - -func TestShouldReturnEnumIndexForRole(t *testing.T) { - role := Admin - var expected int = 0 - var actual int = role.EnumIndex() - - assert.Equal(t, expected, actual) -} - -func TestShouldGetAdminEnumByIndex(t *testing.T) { - var expected Role = Admin - actual, err := GetEnumByIndex(0) - - assert.Nil(t, err) - assert.Equal(t, expected, actual) -} - -func TestShouldGetCustomerEnumByIndex(t *testing.T) { - var expected Role = Customer - actual, err := GetEnumByIndex(1) - - assert.Nil(t, err) - assert.Equal(t, expected, actual) -} - -func TestShouldReturnErrOnGetEnumByIndexForInvalidIndex(t *testing.T) { - var expected Role = -1 - actual, err := GetEnumByIndex(1000) - - assert.Error(t, err.Error()) - assert.Equal(t, expected, actual) -} - -func TestShouldReturnNewUser(t *testing.T) { - id := "absbs" - firstName := "Swastik" - lastName := "Sahoo" - phone := "1234567890" - email := "swastiksahoo22@gmail.com" - username := "swastik153" - password := "secret" - role := Admin - - user := NewUser(id, firstName, lastName, username, phone, email, password, role) - assert.Equal(t, firstName, user.FirstName) - assert.Equal(t, lastName, user.LastName) - assert.Equal(t, username, user.Username) - assert.Equal(t, phone, user.Phone) - assert.Equal(t, email, user.Email) - assert.Equal(t, password, user.Password) -} - -func TestShouldUpdateEmail(t *testing.T) { - id := "absbs" - firstName := "Swastik" - lastName := "Sahoo" - phone := "1234567890" - email := "swastiksahoo22@gmail.com" - username := "swastik153" - password := "secret" - role := Admin - - newEmail := "msadriwala.1198@gmail.com" - user := NewUser(id, firstName, lastName, username, phone, email, password, role) - - user.Email = newEmail - - assert.Equal(t, newEmail, user.Email) -} - -func TestShouldUpdatePhone(t *testing.T) { - id := "absbs" - firstName := "Swastik" - lastName := "Sahoo" - phone := "1234567890" - email := "swastiksahoo22@gmail.com" - username := "swastik153" - password := "secret" - role := Admin - - newPhone := "9999955555" - user := NewUser(id, firstName, lastName, username, phone, email, password, role) - - user.Phone = newPhone - - assert.Equal(t, newPhone, user.Phone) -} - -func TestShouldUpdateUsername(t *testing.T) { - id := "absbs" - firstName := "Swastik" - lastName := "Sahoo" - phone := "1234567890" - email := "swastiksahoo22@gmail.com" - username := "swastik153" - password := "secret" - role := Admin - - newUsername := "newUsername" - user := NewUser(id, firstName, lastName, username, phone, email, password, role) - - user.Username = newUsername - - assert.Equal(t, newUsername, user.Username) -} - -func TestShouldUpdatePassword(t *testing.T) { - id := "absbs" - firstName := "Swastik" - lastName := "Sahoo" - phone := "1234567890" - email := "swastiksahoo22@gmail.com" - username := "swastik153" - password := "secret" - role := Admin - - newPassword := "newPass" - user := NewUser(id, firstName, lastName, username, phone, email, password, role) - - user.Password = newPassword - - assert.Equal(t, newPassword, user.Password) -} - -func TestShouldUpdateFirstName(t *testing.T) { - id := "absbs" - firstName := "Swastik" - lastName := "Sahoo" - phone := "1234567890" - email := "swastiksahoo22@gmail.com" - username := "swastik153" - password := "secret" - role := Admin - - newFirstName := "SwastikNew" - user := NewUser(id, firstName, lastName, username, phone, email, password, role) - - user.FirstName = newFirstName - - assert.Equal(t, newFirstName, user.FirstName) -} - -func TestShouldUpdateLastName(t *testing.T) { - id := "absbs" - firstName := "Swastik" - lastName := "Sahoo" - phone := "1234567890" - email := "swastiksahoo22@gmail.com" - username := "swastik153" - password := "secret" - role := Admin - - newLastName := "newLastName" - user := NewUser(id, firstName, lastName, username, phone, email, password, role) - - user.LastName = newLastName - - assert.Equal(t, newLastName, user.LastName) -} - -func TestShouldUpdateRole(t *testing.T) { - id := "absbs" - firstName := "Swastik" - lastName := "Sahoo" - phone := "1234567890" - email := "swastiksahoo22@gmail.com" - username := "swastik153" - password := "secret" - role := Admin - - newRole := Customer - user := NewUser(id, firstName, lastName, username, phone, email, password, role) - - user.Role = newRole - - assert.Equal(t, newRole, user.Role) -} - -func TestShouldMarshallJson(t *testing.T) { - id := "absbs" - firstName := "Murtaza" - lastName := "Sadriwala" - phone := "9900887766" - email := "murtaza896@gmail.com" - username := "murtaza896" - password := "Pass!23" - role := Admin - - user := NewUser(id, firstName, lastName, username, phone, email, password, role) - - expectedJson := "{\"email\":\"murtaza896@gmail.com\",\"firstName\":\"Murtaza\",\"lastName\":\"Sadriwala\",\"password\":\"Pass!23\",\"phone\":\"9900887766\",\"role\":0,\"user_id\":\"absbs\",\"username\":\"murtaza896\"}" - - actualJson, _ := user.MarshalJSON() - - assert.Equal(t, expectedJson, string(actualJson)) - -} diff --git a/user/go.mod b/user/go.mod deleted file mode 100644 index c3b8d63..0000000 --- a/user/go.mod +++ /dev/null @@ -1,49 +0,0 @@ -module github.com/swiggy-2022-bootcamp/cdp-team4/user - -go 1.17 - -require ( - github.com/aws/aws-sdk-go v1.43.36 - github.com/gin-gonic/gin v1.7.7 - github.com/joho/godotenv v1.4.0 - github.com/pkg/errors v0.9.1 - github.com/stretchr/testify v1.7.0 - github.com/swaggo/files v0.0.0-20210815190702-a29dd2bc99b2 - github.com/swaggo/gin-swagger v1.4.1 - github.com/swaggo/swag v1.8.1 - go.mongodb.org/mongo-driver v1.9.0 - golang.org/x/crypto v0.0.0-20220411220226-7b82a4e95df4 -) - -require ( - github.com/KyleBanks/depth v1.2.1 // indirect - github.com/PuerkitoBio/purell v1.1.1 // indirect - github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578 // indirect - github.com/davecgh/go-spew v1.1.1 // indirect - github.com/gin-contrib/sse v0.1.0 // indirect - github.com/go-openapi/jsonpointer v0.19.5 // indirect - github.com/go-openapi/jsonreference v0.19.6 // indirect - github.com/go-openapi/spec v0.20.4 // indirect - github.com/go-openapi/swag v0.19.15 // indirect - github.com/go-playground/locales v0.13.0 // indirect - github.com/go-playground/universal-translator v0.17.0 // indirect - github.com/go-playground/validator/v10 v10.4.1 // indirect - github.com/golang/protobuf v1.3.3 // indirect - github.com/jmespath/go-jmespath v0.4.0 // indirect - github.com/josharian/intern v1.0.0 // indirect - github.com/json-iterator/go v1.1.9 // indirect - github.com/leodido/go-urn v1.2.0 // indirect - github.com/mailru/easyjson v0.7.6 // indirect - github.com/mattn/go-isatty v0.0.12 // indirect - github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 // indirect - github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742 // indirect - github.com/pmezard/go-difflib v1.0.0 // indirect - github.com/stretchr/objx v0.1.0 // indirect - github.com/ugorji/go/codec v1.1.7 // indirect - golang.org/x/net v0.0.0-20220127200216-cd36cc0744dd // indirect - golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e // indirect - golang.org/x/text v0.3.7 // indirect - golang.org/x/tools v0.1.7 // indirect - gopkg.in/yaml.v2 v2.4.0 // indirect - gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b // indirect -) diff --git a/user/go.sum b/user/go.sum deleted file mode 100644 index e6e85ca..0000000 --- a/user/go.sum +++ /dev/null @@ -1,187 +0,0 @@ -github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= -github.com/KyleBanks/depth v1.2.1 h1:5h8fQADFrWtarTdtDudMmGsC7GPbOAu6RVB3ffsVFHc= -github.com/KyleBanks/depth v1.2.1/go.mod h1:jzSb9d0L43HxTQfT+oSA1EEp2q+ne2uh6XgeJcm8brE= -github.com/PuerkitoBio/purell v1.1.1 h1:WEQqlqaGbrPkxLJWfBwQmfEAE1Z7ONdDLqrN38tNFfI= -github.com/PuerkitoBio/purell v1.1.1/go.mod h1:c11w/QuzBsJSee3cPx9rAFu61PvFxuPbtSwDGJws/X0= -github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578 h1:d+Bc7a5rLufV/sSk/8dngufqelfh6jnri85riMAaF/M= -github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578/go.mod h1:uGdkoq3SwY9Y+13GIhn11/XLaGBb4BfwItxLd5jeuXE= -github.com/agiledragon/gomonkey/v2 v2.3.1 h1:k+UnUY0EMNYUFUAQVETGY9uUTxjMdnUkP0ARyJS1zzs= -github.com/agiledragon/gomonkey/v2 v2.3.1/go.mod h1:ap1AmDzcVOAz1YpeJ3TCzIgstoaWLA6jbbgxfB4w2iY= -github.com/aws/aws-sdk-go v1.43.36 h1:8a+pYKNT7wSxUy3fi5dSqKQdfmit7SYGg5fv4zf+WuA= -github.com/aws/aws-sdk-go v1.43.36/go.mod h1:y4AeaBuwd2Lk+GepC1E9v0qOiTws0MIWAX4oIKwKHZo= -github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU= -github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= -github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= -github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= -github.com/gin-contrib/gzip v0.0.3 h1:etUaeesHhEORpZMp18zoOhepboiWnFtXrBZxszWUn4k= -github.com/gin-contrib/gzip v0.0.3/go.mod h1:YxxswVZIqOvcHEQpsSn+QF5guQtO1dCfy0shBPy4jFc= -github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE= -github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI= -github.com/gin-gonic/gin v1.6.3/go.mod h1:75u5sXoLsGZoRN5Sgbi1eraJ4GU3++wFwWzhwvtwp4M= -github.com/gin-gonic/gin v1.7.7 h1:3DoBmSbJbZAWqXJC3SLjAPfutPJJRN1U5pALB7EeTTs= -github.com/gin-gonic/gin v1.7.7/go.mod h1:axIBovoeJpVj8S3BwE0uPMTeReE4+AfFtqpqaZ1qq1U= -github.com/go-openapi/jsonpointer v0.19.3/go.mod h1:Pl9vOtqEWErmShwVjC8pYs9cog34VGT37dQOVbmoatg= -github.com/go-openapi/jsonpointer v0.19.5 h1:gZr+CIYByUqjcgeLXnQu2gHYQC9o73G2XUeOFYEICuY= -github.com/go-openapi/jsonpointer v0.19.5/go.mod h1:Pl9vOtqEWErmShwVjC8pYs9cog34VGT37dQOVbmoatg= -github.com/go-openapi/jsonreference v0.19.6 h1:UBIxjkht+AWIgYzCDSv2GN+E/togfwXUJFRTWhl2Jjs= -github.com/go-openapi/jsonreference v0.19.6/go.mod h1:diGHMEHg2IqXZGKxqyvWdfWU/aim5Dprw5bqpKkTvns= -github.com/go-openapi/spec v0.20.4 h1:O8hJrt0UMnhHcluhIdUgCLRWyM2x7QkBXRvOs7m+O1M= -github.com/go-openapi/spec v0.20.4/go.mod h1:faYFR1CvsJZ0mNsmsphTMSoRrNV3TEDoAM7FOEWeq8I= -github.com/go-openapi/swag v0.19.5/go.mod h1:POnQmlKehdgb5mhVOsnJFsivZCEZ/vjK9gh66Z9tfKk= -github.com/go-openapi/swag v0.19.15 h1:D2NRCBzS9/pEY3gP9Nl8aDqGUcPFrwG2p+CNFrLyrCM= -github.com/go-openapi/swag v0.19.15/go.mod h1:QYRuS/SOXUCsnplDa677K7+DxSOj6IPNl/eQntq43wQ= -github.com/go-playground/assert/v2 v2.0.1 h1:MsBgLAaY856+nPRTKrp3/OZK38U/wa0CcBYNjji3q3A= -github.com/go-playground/assert/v2 v2.0.1/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= -github.com/go-playground/locales v0.13.0 h1:HyWk6mgj5qFqCT5fjGBuRArbVDfE4hi8+e8ceBS/t7Q= -github.com/go-playground/locales v0.13.0/go.mod h1:taPMhCMXrRLJO55olJkUXHZBHCxTMfnGwq/HNwmWNS8= -github.com/go-playground/universal-translator v0.17.0 h1:icxd5fm+REJzpZx7ZfpaD876Lmtgy7VtROAbHHXk8no= -github.com/go-playground/universal-translator v0.17.0/go.mod h1:UkSxE5sNxxRwHyU+Scu5vgOQjsIJAF8j9muTVoKLVtA= -github.com/go-playground/validator/v10 v10.2.0/go.mod h1:uOYAAleCW8F/7oMFd6aG0GOhaH6EGOAJShg8Id5JGkI= -github.com/go-playground/validator/v10 v10.4.1 h1:pH2c5ADXtd66mxoE0Zm9SUhxE20r7aM3F26W0hOn+GE= -github.com/go-playground/validator/v10 v10.4.1/go.mod h1:nlOn6nFhuKACm19sB/8EGNn9GlaMV7XkbRSipzJ0Ii4= -github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= -github.com/golang/protobuf v1.3.3 h1:gyjaxf+svBWX08ZjK86iN9geUJF0H6gp2IRKX6Nf6/I= -github.com/golang/protobuf v1.3.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw= -github.com/golang/snappy v0.0.1/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= -github.com/google/go-cmp v0.5.2 h1:X2ev0eStA3AbceY54o37/0PQ/UWqKEiiO2dKL5OPaFM= -github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= -github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= -github.com/jmespath/go-jmespath v0.4.0 h1:BEgLn5cpjn8UN1mAw4NjwDrS35OdebyEtFe+9YPoQUg= -github.com/jmespath/go-jmespath v0.4.0/go.mod h1:T8mJZnbsbmF+m6zOOFylbeCJqk5+pHWvzYPziyZiYoo= -github.com/jmespath/go-jmespath/internal/testify v1.5.1 h1:shLQSRRSCCPj3f2gpwzGwWFoC7ycTf1rcQZHOlsJ6N8= -github.com/jmespath/go-jmespath/internal/testify v1.5.1/go.mod h1:L3OGu8Wl2/fWfCI6z80xFu9LTZmf1ZRjMHUOPmWr69U= -github.com/joho/godotenv v1.4.0 h1:3l4+N6zfMWnkbPEXKng2o2/MR5mSwTrBih4ZEkkz1lg= -github.com/joho/godotenv v1.4.0/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4= -github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY= -github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y= -github.com/json-iterator/go v1.1.9 h1:9yzud/Ht36ygwatGx56VwCZtlI/2AD15T1X2sjSuGns= -github.com/json-iterator/go v1.1.9/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= -github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU= -github.com/klauspost/compress v1.13.6/go.mod h1:/3/Vjq9QcHkK5uEr5lBEmyoZ1iFhe47etQ6QUkpK6sk= -github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= -github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= -github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= -github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= -github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= -github.com/leodido/go-urn v1.2.0 h1:hpXL4XnriNwQ/ABnpepYM/1vCLWNDfUNts8dX3xTG6Y= -github.com/leodido/go-urn v1.2.0/go.mod h1:+8+nEpDfqqsY+g338gtMEUOtuK+4dEMhiQEgxpxOKII= -github.com/mailru/easyjson v0.0.0-20190614124828-94de47d64c63/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc= -github.com/mailru/easyjson v0.0.0-20190626092158-b2ccc519800e/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc= -github.com/mailru/easyjson v0.7.6 h1:8yTIVnZgCoiM1TgqoeTl+LfU5Jg6/xL3QhGQnimLYnA= -github.com/mailru/easyjson v0.7.6/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc= -github.com/mattn/go-isatty v0.0.12 h1:wuysRhFDzyxgEmMf5xjvJ2M9dZoWAXNNr5LSBS7uHXY= -github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU= -github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 h1:ZqeYNhU3OHLH3mGKHDcjJRFFRrJa6eAM5H+CtDdOsPc= -github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= -github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742 h1:Esafd1046DLDQ0W1YjYsBW+p8U2u7vzgW2SQVmlNazg= -github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= -github.com/montanaflynn/stats v0.0.0-20171201202039-1bf9dbcd8cbe/go.mod h1:wL8QJuTMNUDYhXwkmfOly8iTdp5TEcJFWZD2D7SIkUc= -github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e h1:fD57ERR4JtEqsWbfPhv4DMiApHyliiK5xCTNVSPiaAs= -github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= -github.com/otiai10/copy v1.7.0 h1:hVoPiN+t+7d2nzzwMiDHPSOogsWAStewq3TwU05+clE= -github.com/otiai10/copy v1.7.0/go.mod h1:rmRl6QPdJj6EiUqXQ/4Nn2lLXoNQjFCQbbNrxgc/t3U= -github.com/otiai10/curr v0.0.0-20150429015615-9b4961190c95/go.mod h1:9qAhocn7zKJG+0mI8eUu6xqkFDYS2kb2saOteoSB3cE= -github.com/otiai10/curr v1.0.0/go.mod h1:LskTG5wDwr8Rs+nNQ+1LlxRjAtTZZjtJW4rMXl6j4vs= -github.com/otiai10/mint v1.3.0/go.mod h1:F5AjcsTsWUqX+Na9fpHb52P8pcRX2CI6A3ctIT91xUo= -github.com/otiai10/mint v1.3.3/go.mod h1:/yxELlJQ0ufhjUwhshSj+wFjZ78CnZ48/1wtmBH1OTc= -github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= -github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= -github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= -github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= -github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc= -github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc= -github.com/smartystreets/goconvey v1.6.4/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA= -github.com/stretchr/objx v0.1.0 h1:4G4v2dO3VZwixGIRoQ5Lfboy6nUhCyYzaqnIAPPhYs4= -github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= -github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= -github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= -github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= -github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY= -github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= -github.com/swaggo/files v0.0.0-20210815190702-a29dd2bc99b2 h1:+iNTcqQJy0OZ5jk6a5NLib47eqXK8uYcPX+O4+cBpEM= -github.com/swaggo/files v0.0.0-20210815190702-a29dd2bc99b2/go.mod h1:lKJPbtWzJ9JhsTN1k1gZgleJWY/cqq0psdoMmaThG3w= -github.com/swaggo/gin-swagger v1.4.1 h1:F2vJndw+Q+ZBOlsC6CaodqXJV3ZOf6hpg/4Y6MEx5BM= -github.com/swaggo/gin-swagger v1.4.1/go.mod h1:hmJ1vPn+XjUvnbzjCdUAxVqgraxELxk8x5zAsjCE5mg= -github.com/swaggo/swag v1.7.9/go.mod h1:gZ+TJ2w/Ve1RwQsA2IRoSOTidHz6DX+PIG8GWvbnoLU= -github.com/swaggo/swag v1.8.1 h1:JuARzFX1Z1njbCGz+ZytBR15TFJwF2Q7fu8puJHhQYI= -github.com/swaggo/swag v1.8.1/go.mod h1:ugemnJsPZm/kRwFUnzBlbHRd0JY9zE1M4F+uy2pAaPQ= -github.com/tidwall/pretty v1.0.0/go.mod h1:XNkn88O1ChpSDQmQeStsy+sBenx6DDtFZJxhVysOjyk= -github.com/ugorji/go v1.1.7 h1:/68gy2h+1mWMrwZFeD1kQialdSzAb432dtpeJ42ovdo= -github.com/ugorji/go v1.1.7/go.mod h1:kZn38zHttfInRq0xu/PH0az30d+z6vm202qpg1oXVMw= -github.com/ugorji/go/codec v1.1.7 h1:2SvQaVZ1ouYrrKKwoSk2pzd4A9evlKJb9oTL+OaLUSs= -github.com/ugorji/go/codec v1.1.7/go.mod h1:Ax+UKWsSmolVDwsd+7N3ZtXu+yMGCf907BLYF3GoBXY= -github.com/urfave/cli/v2 v2.3.0/go.mod h1:LJmUH05zAU44vOAcrfzZQKsZbVcdbOG8rtL3/XcUArI= -github.com/xdg-go/pbkdf2 v1.0.0/go.mod h1:jrpuAogTd400dnrH08LKmI/xc1MbPOebTwRqcT5RDeI= -github.com/xdg-go/scram v1.0.2/go.mod h1:1WAq6h33pAW+iRreB34OORO2Nf7qel3VV3fjBj+hCSs= -github.com/xdg-go/stringprep v1.0.2/go.mod h1:8F9zXuvzgwmyT5DUm4GUfZGDdT3W+LCvS6+da4O5kxM= -github.com/youmark/pkcs8 v0.0.0-20181117223130-1be2e3e5546d/go.mod h1:rHwXgn7JulP+udvsHwJoVG1YGAP6VLg4y9I5dyZdqmA= -github.com/yuin/goldmark v1.4.0/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= -go.mongodb.org/mongo-driver v1.9.0 h1:f3aLGJvQmBl8d9S40IL+jEyBC6hfLPbJjv9t5hEM9ck= -go.mongodb.org/mongo-driver v1.9.0/go.mod h1:0sQWfOeY63QTntERDJJ/0SuKK0T1uVSgKCuAROlKEPY= -golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= -golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= -golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= -golang.org/x/crypto v0.0.0-20201216223049-8b5274cf687f/go.mod h1:jdWPYTVW3xRLrWPugEBEK3UY2ZEsg3UU495nc5E+M+I= -golang.org/x/crypto v0.0.0-20220411220226-7b82a4e95df4 h1:kUhD7nTDoI3fVd9G4ORWrbV5NY0liEs/Jg2pv5f+bBA= -golang.org/x/crypto v0.0.0-20220411220226-7b82a4e95df4/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= -golang.org/x/mod v0.4.2 h1:Gz96sIWK3OalVv/I/qNygP42zyoKp3xptRVCWRFEBvo= -golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= -golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= -golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= -golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20210421230115-4e50805a0758/go.mod h1:72T/g9IO56b78aLF+1Kcs5dz7/ng1VjMUvfKvpfy+jM= -golang.org/x/net v0.0.0-20210805182204-aaa1db679c0d/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= -golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= -golang.org/x/net v0.0.0-20220127200216-cd36cc0744dd h1:O7DYs+zxREGLKzKoMQrtrEacpb0ZVXA5rIwylE2Xchk= -golang.org/x/net v0.0.0-20220127200216-cd36cc0744dd/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= -golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210420072515-93ed5bcd2bfe/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e h1:fLOSk5Q00efkSvAm+4xcoXD+RRmLmmulPn5I3Y9F2EM= -golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw= -golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= -golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= -golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= -golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= -golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= -golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= -golang.org/x/text v0.3.7 h1:olpwvP2KacW1ZWvsR7uQhoyTYvKAupfQrRGBFM352Gk= -golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= -golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= -golang.org/x/tools v0.0.0-20190328211700-ab21143f2384/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= -golang.org/x/tools v0.0.0-20190531172133-b3315ee88b7d/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= -golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.1.7 h1:6j8CgantCy3yc8JGBqkDLMKWqZ0RDU2g1HVgacojGWQ= -golang.org/x/tools v0.1.7/go.mod h1:LGqMHiF4EqQNHR1JncWGqT5BVaXmza+X+BDGol+dOxo= -golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE= -golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f h1:BLraFXnmrev5lT+xlilqcH8XK9/i0At2xKjWk4p6zsU= -gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.2.3/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= -gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= -gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -gopkg.in/yaml.v3 v3.0.0-20200615113413-eeeca48fe776/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b h1:h8qDotaEPuJATrMmW04NCwg7v22aHH28wwpauUhK9Oo= -gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/user/infra/dynamodbRepo.go b/user/infra/dynamodbRepo.go deleted file mode 100644 index 5534bde..0000000 --- a/user/infra/dynamodbRepo.go +++ /dev/null @@ -1,240 +0,0 @@ -package infra - -import ( - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/dynamodb" - "github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute" - "github.com/swiggy-2022-bootcamp/cdp-team4/user/domain" - "time" - "context" - "fmt" -) - -type UserDynamoDBRepository struct { - Session *dynamodb.DynamoDB - TableName string -} - -func NewDynamoRepository() UserDynamoDBRepository { - svc := connect() - return UserDynamoDBRepository{Session: svc, TableName: "users"} -} - -func connect() *dynamodb.DynamoDB { - // Create AWS Session - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - // Return DynamoDB client - return dynamodb.New(sess) -} - - -func (repo UserDynamoDBRepository) Save(user domain.User) (domain.User, error) { - ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) - defer cancel() - - dynamodbUser := toPersistedDynamodbEntity(user) - - attributeValue, err := dynamodbattribute.MarshalMap(dynamodbUser) - if err != nil { - return domain.User{}, err - } - - item := &dynamodb.PutItemInput{ - Item: attributeValue, - TableName: aws.String(repo.TableName), - } - - _, err = repo.Session.PutItemWithContext(ctx, item) - - if err != nil { - return domain.User{}, err - } - - return user, err -} - - -func (repo UserDynamoDBRepository) FindByID(id string) (*domain.User, error) { - ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) - defer cancel() - - input := &dynamodb.GetItemInput{ - TableName: aws.String(repo.TableName), - Key: map[string]*dynamodb.AttributeValue{ - "user_id": { - S: aws.String(id), - }, - }, - } - - result, err := repo.Session.GetItemWithContext(ctx, input) - if err != nil { - return nil, err - } - - if result.Item == nil { - return nil, fmt.Errorf("item not found") - } - - user := domain.User{} - err = dynamodbattribute.UnmarshalMap(result.Item, &user) - - if err != nil { - return nil, fmt.Errorf("unmarshal map - %s", err.Error()) - } - - return &user, nil -} - - -func (repo UserDynamoDBRepository) FindAll() ([]domain.User, error) { - - // Build the query input parameters - params := &dynamodb.ScanInput{ - TableName: aws.String(repo.TableName), - } - - // Make the DynamoDB Query API call - result, err := repo.Session.Scan(params) - if err != nil { - return nil, err - } - var users []domain.User = []domain.User{} - for _, i := range result.Items { - user := domain.User{} - - err = dynamodbattribute.UnmarshalMap(i, &user) - - if err != nil { - panic(err) - } - users = append(users, user) - } - return users, nil -} - - -func (repo UserDynamoDBRepository) UpdateById(user domain.User) (bool, error) { - ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) - defer cancel() - - prevUserInput := &dynamodb.GetItemInput{ - TableName: aws.String(repo.TableName), - Key: map[string]*dynamodb.AttributeValue{ - "user_id": { - S: aws.String(user.UserID), - }, - }, - } - - prevUserResult, err := repo.Session.GetItemWithContext(ctx, prevUserInput) - if err != nil { - return false, err - } - - oldUser := domain.User{} - err = dynamodbattribute.UnmarshalMap(prevUserResult.Item, &oldUser) - - if err != nil { - return false, fmt.Errorf("unmarshal map - %s", err.Error()) - } - - if user.FirstName == "" { - user.FirstName = oldUser.FirstName - } - - if user.LastName == "" { - user.LastName = oldUser.LastName - } - - if user.Phone == "" { - user.Phone = oldUser.Phone - } - - if user.Email == "" { - user.Email = oldUser.Email - } - - if user.Username == "" { - user.Username = oldUser.Username - } - - if user.Password == "" { - user.Password = oldUser.Password - } - - input := &dynamodb.UpdateItemInput{ - ExpressionAttributeValues: map[string]*dynamodb.AttributeValue{ - ":s": { - S: aws.String(user.FirstName), - }, ":s1": { - S: aws.String(user.LastName), - }, ":s2": { - S: aws.String(user.Phone), - }, ":s3": { - S: aws.String(user.Email), - }, ":s4": { - S: aws.String(user.Username), - }, ":s5": { - S: aws.String(user.Password), - }, ":s6": { - S: aws.String(time.Now().String()), - }, - }, - Key: map[string]*dynamodb.AttributeValue{ - "user_id": { - S: aws.String(user.UserID), - }, - }, - ReturnValues: aws.String("UPDATED_NEW"), - UpdateExpression: aws.String("set first_name =:s, last_name = :s1, phone = :s2, email = :s3, username = :s4, password = :s5, updated_at =:s6"), - TableName: aws.String(repo.TableName), - } - - _, err1 := repo.Session.UpdateItemWithContext(ctx, input) - if err1 != nil { - return false, err1 - } - return true, err1 -} - - - -func (repo UserDynamoDBRepository) DeleteByID(id string) (bool, error) { - ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) - defer cancel() - input := &dynamodb.DeleteItemInput{ - Key: map[string]*dynamodb.AttributeValue{ - "user_id": { - S: aws.String(id), - }, - }, - TableName: aws.String(repo.TableName), - } - - _, err := repo.Session.DeleteItemWithContext(ctx, input) - if err != nil { - return false, fmt.Errorf("unable to delete - %s", err.Error()) - } - return true, nil -} - - -func toPersistedDynamodbEntity(u domain.User) *UserModel { - return &UserModel{ - UserID: u.UserID, - FirstName: u.FirstName, - LastName: u.LastName, - Phone: u.Phone, - Email: u.Email, - Username: u.Username, - Password: u.Password, - Role: u.Role, - CreatedAt: time.Now(), - UpdatedAt: time.Now(), - } -} diff --git a/user/infra/dynamodbRepo_test.go b/user/infra/dynamodbRepo_test.go deleted file mode 100644 index 89a9c11..0000000 --- a/user/infra/dynamodbRepo_test.go +++ /dev/null @@ -1,116 +0,0 @@ -package infra_test - -import ( - "testing" - - "github.com/stretchr/testify/assert" - "github.com/swiggy-2022-bootcamp/cdp-team4/user/domain" - "github.com/swiggy-2022-bootcamp/cdp-team4/user/infra" -) - -var testUserService = infra.NewDynamoRepository() -var insertedid string -var inserteduserid string - -func TestShouldCreateNewUserinDynamoDB(t *testing.T) { - userID := "afshsjgj14151joi" - firstName := "Swastik" - lastName := "Sahoo" - phone := "1234567890" - email := "swastiksahoo22@gmail.com" - username := "swastik153" - password, _ := domain.HashPassword("Pass!23") - role := domain.Admin - - user := domain.NewUser(userID, firstName, lastName, username, phone, email, password, role) - res, err := testUserService.Save(*user) - t.Logf("Inserted user is %s\n", res) - assert.NotNil(t, res) - assert.Nil(t, err) -} - - -func TestShouldGetUserByUserIdDynamoDB(t *testing.T) { - userID := "afshsjgj14151joi" - firstName := "Swastik" - lastName := "Sahoo" - phone := "1234567890" - email := "swastiksahoo22@gmail.com" - username := "swastik153" - password, _ := domain.HashPassword("Pass!23") - role := domain.Admin - - t.Logf("Inserted User Id is %s Reading\n", userID) - res, err := testUserService.FindByID(userID) - t.Logf("Read %v", res) - - user := domain.NewUser(userID, firstName, lastName, username, phone, email, password, role) - - assert.NotNil(t, res) - assert.Nil(t, err) - - assert.Equal(t, res.FirstName, user.FirstName) - assert.Equal(t, res.LastName, user.LastName) - assert.Equal(t, res.Username, user.Username) - assert.Equal(t, res.Phone, user.Phone) - assert.Equal(t, res.Email, user.Email) - assert.Equal(t, res.Role, user.Role) -} - -func TestShouldUpdateUserByIdDynamoDB(t *testing.T) { - userID := "afshsjgj14151joi" - firstName := "SwastikU" - lastName := "SahooU" - phone := "1234567890U" - email := "swastiksahoo22@gmail.comU" - username := "swastik153U" - password, _ := domain.HashPassword("Pass!23U") - role := domain.Admin - - user := domain.NewUser(userID, firstName, lastName, username, phone, email, password, role) - - t.Logf("Inserted User Id is %s Reading\n", userID) - res, err := testUserService.UpdateById(*user) - t.Logf("Read %v", res) - - assert.NotNil(t, res) - assert.Nil(t, err) - - assert.Equal(t, res,true) -} - -func TestShouldUpdateUserByIdDynamoDB2(t *testing.T) { - userID := "afshsjgj14151joi" - firstName := "" - lastName := "" - phone := "" - email := "" - username := "" - password := "" - role := domain.Admin - - user := domain.NewUser(userID, firstName, lastName, username, phone, email, password, role) - - t.Logf("Inserted User Id is %s Reading\n", userID) - res, err := testUserService.UpdateById(*user) - t.Logf("Read %v", res) - - assert.NotNil(t, res) - assert.Nil(t, err) - - assert.Equal(t, res,true) -} - -func TestShouldGetAllUsersDynamoDB(t *testing.T) { - res, err := testUserService.FindAll() - assert.NotNil(t, res) - assert.Nil(t, err) -} - - -func TestShouldDeleteUserByIdDynamoDB(t *testing.T) { - userID := "afshsjgj14151joi" - res, err := testUserService.DeleteByID(userID) - assert.NotNil(t, res) - assert.Nil(t, err) -} \ No newline at end of file diff --git a/user/infra/userModel.go b/user/infra/userModel.go deleted file mode 100644 index 9047fe3..0000000 --- a/user/infra/userModel.go +++ /dev/null @@ -1,20 +0,0 @@ -package infra - -import ( - "time" - - "github.com/swiggy-2022-bootcamp/cdp-team4/user/domain" -) - -type UserModel struct { - UserID string `json:"user_id"` - FirstName string `json:"first_name"` - LastName string `json:"last_name"` - Username string `json:"username"` - Password string `json:"password"` - Phone string `json:"phone"` - Email string `json:"email"` - Role domain.Role `json:"role"` - CreatedAt time.Time `json:"created_at"` - UpdatedAt time.Time `json:"updated_at"` -} diff --git a/user/main.go b/user/main.go deleted file mode 100644 index 3867c6f..0000000 --- a/user/main.go +++ /dev/null @@ -1,20 +0,0 @@ -package main - -import "github.com/swiggy-2022-bootcamp/cdp-team4/user/app" - -// @title User API -// @version 1.0 -// @description User Service. -// @termsOfService http://swagger.io/terms/ - -// @contact.name API Support -// @contact.url http://www.swagger.io/support -// @contact.email support@swagger.io - -// @license.name Apache 2.0 -// @license.url http://www.apache.org/licenses/LICENSE-2.0.html - -// @BasePath / -func main() { - app.Start() -} \ No newline at end of file diff --git a/user/mockRequest/mockRequest.http b/user/mockRequest/mockRequest.http deleted file mode 100644 index 59ad49b..0000000 --- a/user/mockRequest/mockRequest.http +++ /dev/null @@ -1,37 +0,0 @@ -# Get Users - -# curl -H "X-API-Key: 9e4a5970" https://my.api.mockaroo.com/users.json -GET https://my.api.mockaroo.com/users.json -X-API-Key: 9e4a5970 - -### - -# Get Users by id - -# curl -H "X-API-Key: 9e4a5970" https://my.api.mockaroo.com/users/123.json -GET https://my.api.mockaroo.com/users/123.json -X-API-Key: 9e4a5970 - -### - -# Create Users by id - -# curl -H "X-API-Key: 9e4a5970" -X POST https://my.api.mockaroo.com/users.json -POST https://my.api.mockaroo.com/users.json -X-API-Key: 9e4a5970 - -### - -# Update User by user id - -# curl -H "X-API-Key: 9e4a5970" -X PATCH -d '{"first_name":"test"}' https://my.api.mockaroo.com/users/123.json -PATCH https://my.api.mockaroo.com/users/123.json -X-API-Key: 9e4a5970 - -### - -# Delete user by user id - -# curl -H "X-API-Key: 9e4a5970" -X DELETE https://my.api.mockaroo.com/users/123.json -DELETE https://my.api.mockaroo.com/users/123.json -X-API-Key: 9e4a5970 \ No newline at end of file diff --git a/user/mocks/UserDynamoDBRepository.go b/user/mocks/UserDynamoDBRepository.go deleted file mode 100644 index fbadea1..0000000 --- a/user/mocks/UserDynamoDBRepository.go +++ /dev/null @@ -1,122 +0,0 @@ -// Code generated by mockery v2.10.6. DO NOT EDIT. - -package mocks - -import ( - mock "github.com/stretchr/testify/mock" - domain "github.com/swiggy-2022-bootcamp/cdp-team4/user/domain" -) - -// UserDynamoDBRepository is an autogenerated mock type for the UserDynamoDBRepository type -type UserDynamoDBRepository struct { - mock.Mock -} - -// DeleteByID provides a mock function with given fields: _a0 -func (_m *UserDynamoDBRepository) DeleteByID(_a0 string) (bool, error) { - ret := _m.Called(_a0) - - var r0 bool - if rf, ok := ret.Get(0).(func(string) bool); ok { - r0 = rf(_a0) - } else { - r0 = ret.Get(0).(bool) - } - - var r1 error - if rf, ok := ret.Get(1).(func(string) error); ok { - r1 = rf(_a0) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// FindAll provides a mock function with given fields: -func (_m *UserDynamoDBRepository) FindAll() ([]domain.User, error) { - ret := _m.Called() - - var r0 []domain.User - if rf, ok := ret.Get(0).(func() []domain.User); ok { - r0 = rf() - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).([]domain.User) - } - } - - var r1 error - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// FindByID provides a mock function with given fields: _a0 -func (_m *UserDynamoDBRepository) FindByID(_a0 string) (*domain.User, error) { - ret := _m.Called(_a0) - - var r0 *domain.User - if rf, ok := ret.Get(0).(func(string) *domain.User); ok { - r0 = rf(_a0) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*domain.User) - } - } - - var r1 error - if rf, ok := ret.Get(1).(func(string) error); ok { - r1 = rf(_a0) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// Save provides a mock function with given fields: _a0 -func (_m *UserDynamoDBRepository) Save(_a0 domain.User) (domain.User, error) { - ret := _m.Called(_a0) - - var r0 domain.User - if rf, ok := ret.Get(0).(func(domain.User) domain.User); ok { - r0 = rf(_a0) - } else { - r0 = ret.Get(0).(domain.User) - } - - var r1 error - if rf, ok := ret.Get(1).(func(domain.User) error); ok { - r1 = rf(_a0) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// UpdateById provides a mock function with given fields: _a0 -func (_m *UserDynamoDBRepository) UpdateById(_a0 domain.User) (bool, error) { - ret := _m.Called(_a0) - - var r0 bool - if rf, ok := ret.Get(0).(func(domain.User) bool); ok { - r0 = rf(_a0) - } else { - r0 = ret.Get(0).(bool) - } - - var r1 error - if rf, ok := ret.Get(1).(func(domain.User) error); ok { - r1 = rf(_a0) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} diff --git a/user/utils/errs/errors.go b/user/utils/errs/errors.go deleted file mode 100644 index d7c9467..0000000 --- a/user/utils/errs/errors.go +++ /dev/null @@ -1,63 +0,0 @@ -package errs - -import ( - "github.com/pkg/errors" - "net/http" -) - -type AppError struct { - Code int `json:",omitempty"` - Message string `json:"message"` -} - -func (e AppError) Error() error { - return errors.New(e.Message) -} - -func (e AppError) AsMessage() *AppError { - return &AppError{ - Message: e.Message, - } -} - -func NewNotFoundError(message string) *AppError { - return &AppError{ - Message: message, - Code: http.StatusNotFound, - } -} - -func NewUnexpectedError(message string) *AppError { - return &AppError{ - Message: message, - Code: http.StatusInternalServerError, - } -} - -func NewValidationError(message string) *AppError { - return &AppError{ - Message: message, - Code: http.StatusUnprocessableEntity, - } -} - -func NewBadRequest(message string) *AppError { - return &AppError{ - Message: message, - Code: http.StatusBadRequest, - } -} - -func NewAuthenticationError(message string) *AppError { - return &AppError{ - Message: message, - Code: http.StatusUnauthorized, - } -} - -func NewAuthorizationError(message string) *AppError { - return &AppError{ - Message: message, - Code: http.StatusForbidden, - } -} From a30264144e89cc69cd426bd82d3da6f2c04f176a Mon Sep 17 00:00:00 2001 From: murtaza896 Date: Sun, 24 Apr 2022 12:34:16 +0530 Subject: [PATCH 04/15] | Cleans validation logic | --- gateway/app/responseDTO.go | 7 ++++ gateway/app/userHandler.go | 44 ++++++++++++++++--------- gateway/go.mod | 1 + gateway/go.sum | 2 ++ gateway/utils/errs/errors.go | 63 ++++++++++++++++++++++++++++++++++++ 5 files changed, 102 insertions(+), 15 deletions(-) create mode 100644 gateway/app/responseDTO.go create mode 100644 gateway/utils/errs/errors.go diff --git a/gateway/app/responseDTO.go b/gateway/app/responseDTO.go new file mode 100644 index 0000000..3cb16ac --- /dev/null +++ b/gateway/app/responseDTO.go @@ -0,0 +1,7 @@ +package app + +type ResponseDTO struct { + Status int `json:"status"` + Data interface{} `json:"data,omitempty"` + Message string `json:"message"` +} diff --git a/gateway/app/userHandler.go b/gateway/app/userHandler.go index 58bc85e..90dec40 100644 --- a/gateway/app/userHandler.go +++ b/gateway/app/userHandler.go @@ -4,6 +4,7 @@ import ( "context" "encoding/json" "github.com/gin-gonic/gin" + "github.com/swiggy-2022-bootcamp/cdp-team4/gateway/utils/errs" "log" "net/http" "time" @@ -12,22 +13,17 @@ import ( type userHandler struct { } -type ResponseDTO struct { - Data interface{} -} - -type authModel struct { +type AuthModel struct { UserId string Role int } type ValidationDTO struct { - UserId string `json:"user_id"` - Role int `json:"role"` + UserId string `json:"user_id"` + Role int `json:"role"` } - -func ValidateToken(authorizationHeader string) authModel { +func ValidateToken(authorizationHeader string) (*AuthModel, *errs.AppError) { authServiceUri := "http://localhost:8881/api/v1/validate" req, err := http.NewRequest("GET", authServiceUri, nil) if err != nil { @@ -53,19 +49,37 @@ func ValidateToken(authorizationHeader string) authModel { } var valDTO ValidationDTO - jsonbytes, _ := json.Marshal(resDTO.Data) - json.Unmarshal(jsonbytes, &valDTO) + marshalledData, _ := json.Marshal(resDTO.Data) + err = json.Unmarshal(marshalledData, &valDTO) + if err != nil { + return nil, errs.NewAuthenticationError(err.Error()) + } - return authModel{ + return &AuthModel{ UserId: valDTO.UserId, Role: valDTO.Role, - } + }, nil } func (h userHandler) ValidateAuthToken() gin.HandlerFunc { return func(c *gin.Context) { - res := ValidateToken(c.Request.Header.Get("Authorization")) + res, err := ValidateToken(c.Request.Header.Get("Authorization")) + + if err != nil { + response := ResponseDTO{ + Status: err.Code, + Message: err.Message, + } + c.JSON(response.Status, response) + c.Abort() + return + } - c.JSON(http.StatusOK, res) + response := ResponseDTO{ + Status: http.StatusOK, + Data: res, + Message: "User authenticated successfully", + } + c.JSON(response.Status, response) } } diff --git a/gateway/go.mod b/gateway/go.mod index b93f33a..a84da30 100644 --- a/gateway/go.mod +++ b/gateway/go.mod @@ -5,6 +5,7 @@ go 1.18 require ( github.com/gin-gonic/gin v1.7.7 github.com/joho/godotenv v1.4.0 + github.com/pkg/errors v0.9.1 ) require ( diff --git a/gateway/go.sum b/gateway/go.sum index 1a91c66..8fe2c25 100644 --- a/gateway/go.sum +++ b/gateway/go.sum @@ -28,6 +28,8 @@ github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 h1:ZqeYNhU3OH github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742 h1:Esafd1046DLDQ0W1YjYsBW+p8U2u7vzgW2SQVmlNazg= github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= +github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= +github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= diff --git a/gateway/utils/errs/errors.go b/gateway/utils/errs/errors.go new file mode 100644 index 0000000..d7c9467 --- /dev/null +++ b/gateway/utils/errs/errors.go @@ -0,0 +1,63 @@ +package errs + +import ( + "github.com/pkg/errors" + "net/http" +) + +type AppError struct { + Code int `json:",omitempty"` + Message string `json:"message"` +} + +func (e AppError) Error() error { + return errors.New(e.Message) +} + +func (e AppError) AsMessage() *AppError { + return &AppError{ + Message: e.Message, + } +} + +func NewNotFoundError(message string) *AppError { + return &AppError{ + Message: message, + Code: http.StatusNotFound, + } +} + +func NewUnexpectedError(message string) *AppError { + return &AppError{ + Message: message, + Code: http.StatusInternalServerError, + } +} + +func NewValidationError(message string) *AppError { + return &AppError{ + Message: message, + Code: http.StatusUnprocessableEntity, + } +} + +func NewBadRequest(message string) *AppError { + return &AppError{ + Message: message, + Code: http.StatusBadRequest, + } +} + +func NewAuthenticationError(message string) *AppError { + return &AppError{ + Message: message, + Code: http.StatusUnauthorized, + } +} + +func NewAuthorizationError(message string) *AppError { + return &AppError{ + Message: message, + Code: http.StatusForbidden, + } +} From 4fb2e8dfa1df9a2990517d742a5dfb883187e123 Mon Sep 17 00:00:00 2001 From: murtaza896 Date: Sun, 24 Apr 2022 12:45:10 +0530 Subject: [PATCH 05/15] | Cleans validation logic | --- gateway/app/userHandler.go | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/gateway/app/userHandler.go b/gateway/app/userHandler.go index 90dec40..9ce6ea6 100644 --- a/gateway/app/userHandler.go +++ b/gateway/app/userHandler.go @@ -39,13 +39,19 @@ func ValidateToken(authorizationHeader string) (*AuthModel, *errs.AppError) { res, err := client.Do(req) if err != nil { log.Fatalf("%v", err) + return nil, errs.NewAuthenticationError(err.Error()) } var resDTO ResponseDTO err = json.NewDecoder(res.Body).Decode(&resDTO) if err != nil { - log.Fatalf("unable to decode response %v", err) + //log.Fatalf("unable to decode response %v", err) + return nil, errs.NewUnexpectedError(err.Error()) + } + + if resDTO.Status == http.StatusUnauthorized { + return nil, errs.NewAuthenticationError(resDTO.Message) } var valDTO ValidationDTO From c4509ca511cf71466442f3504938ce66290a66bd Mon Sep 17 00:00:00 2001 From: murtaza896 Date: Sun, 24 Apr 2022 13:19:22 +0530 Subject: [PATCH 06/15] | scaffolding for auth with gateway | --- gateway/app/authMiddleware.go | 93 +++++++++++++++++++++++++++++++++ gateway/app/router.go | 11 +++- gateway/app/userHandler.go | 97 +++++++++-------------------------- 3 files changed, 127 insertions(+), 74 deletions(-) create mode 100644 gateway/app/authMiddleware.go diff --git a/gateway/app/authMiddleware.go b/gateway/app/authMiddleware.go new file mode 100644 index 0000000..cdfac1b --- /dev/null +++ b/gateway/app/authMiddleware.go @@ -0,0 +1,93 @@ +package app + +import ( + "context" + "encoding/json" + "github.com/gin-gonic/gin" + "github.com/swiggy-2022-bootcamp/cdp-team4/gateway/utils/errs" + "log" + "net/http" + "time" +) + +type AuthModel struct { + UserId string + Role int +} + +type ValidationDTO struct { + UserId string `json:"user_id"` + Role int `json:"role"` +} + +func ValidateToken(authorizationHeader string) (*AuthModel, *errs.AppError) { + authServiceUri := "http://localhost:8881/api/v1/validate" + req, err := http.NewRequest("GET", authServiceUri, nil) + if err != nil { + log.Fatalf("%v", err) + } + + ctx, cancel := context.WithTimeout(req.Context(), 1*time.Minute) + defer cancel() + + req = req.WithContext(ctx) + req.Header.Set("Authorization", authorizationHeader) + client := http.DefaultClient + res, err := client.Do(req) + if err != nil { + //log.Fatalf("%v", err) + return nil, errs.NewAuthenticationError(err.Error()) + } + + var resDTO ResponseDTO + err = json.NewDecoder(res.Body).Decode(&resDTO) + + if err != nil { + //log.Fatalf("unable to decode response %v", err) + return nil, errs.NewUnexpectedError(err.Error()) + } + + if resDTO.Status == http.StatusUnauthorized { + return nil, errs.NewAuthenticationError(resDTO.Message) + } + + var valDTO ValidationDTO + marshalledData, _ := json.Marshal(resDTO.Data) + err = json.Unmarshal(marshalledData, &valDTO) + if err != nil { + return nil, errs.NewAuthenticationError(err.Error()) + } + + return &AuthModel{ + UserId: valDTO.UserId, + Role: valDTO.Role, + }, nil +} + +func ValidateAuthToken() gin.HandlerFunc { + return func(c *gin.Context) { + res, err := ValidateToken(c.Request.Header.Get("Authorization")) + + if err != nil { + response := ResponseDTO{ + Status: err.Code, + Message: err.Message, + } + c.JSON(response.Status, response) + c.Abort() + return + } + + c.Params = append(c.Params, gin.Param{ + Key: "userId", + Value: res.UserId, + }) + + isAdmin := "false" + if res.Role == 1 { + isAdmin = "true" + } + + c.Request.Header.Set("admin", isAdmin) + } +} diff --git a/gateway/app/router.go b/gateway/app/router.go index 087d1ba..87bcda4 100644 --- a/gateway/app/router.go +++ b/gateway/app/router.go @@ -20,6 +20,13 @@ func init() { } func RegisterUserRoutes() { - handler := userHandler{} - v1.GET("/users", handler.ValidateAuthToken()) + userHandler := userHandler{} + users := v1.Group("/user") + + v1.GET("/users", ValidateAuthToken(), userHandler.GetAllUsers) + + users.POST("/", userHandler.CreateUser) + users.GET("/", ValidateAuthToken(), userHandler.GetUser) + users.PATCH("/", ValidateAuthToken(), userHandler.UpdateUser) + users.DELETE("/", ValidateAuthToken(), userHandler.DeleteUser) } diff --git a/gateway/app/userHandler.go b/gateway/app/userHandler.go index 9ce6ea6..a3262e2 100644 --- a/gateway/app/userHandler.go +++ b/gateway/app/userHandler.go @@ -1,91 +1,44 @@ package app import ( - "context" - "encoding/json" "github.com/gin-gonic/gin" - "github.com/swiggy-2022-bootcamp/cdp-team4/gateway/utils/errs" - "log" "net/http" - "time" ) type userHandler struct { } -type AuthModel struct { - UserId string - Role int +func (uh userHandler) GetAllUsers(c *gin.Context) { + isAdmin := c.Request.Header.Get("admin") + if isAdmin == "true" { + c.JSON(http.StatusOK, gin.H{"userId": c.Param("userId")}) + c.Abort() + return + } else { + c.JSON(http.StatusUnauthorized, gin.H{}) + c.Abort() + return + } } -type ValidationDTO struct { - UserId string `json:"user_id"` - Role int `json:"role"` +func (uh userHandler) GetUser(c *gin.Context) { + c.JSON(http.StatusOK, gin.H{"userId": c.Param("userId")}) + c.Abort() + return } -func ValidateToken(authorizationHeader string) (*AuthModel, *errs.AppError) { - authServiceUri := "http://localhost:8881/api/v1/validate" - req, err := http.NewRequest("GET", authServiceUri, nil) - if err != nil { - log.Fatalf("%v", err) - } - - ctx, cancel := context.WithTimeout(req.Context(), 1*time.Minute) - defer cancel() - - req = req.WithContext(ctx) - req.Header.Set("Authorization", authorizationHeader) - client := http.DefaultClient - res, err := client.Do(req) - if err != nil { - log.Fatalf("%v", err) - return nil, errs.NewAuthenticationError(err.Error()) - } - - var resDTO ResponseDTO - err = json.NewDecoder(res.Body).Decode(&resDTO) - - if err != nil { - //log.Fatalf("unable to decode response %v", err) - return nil, errs.NewUnexpectedError(err.Error()) - } - - if resDTO.Status == http.StatusUnauthorized { - return nil, errs.NewAuthenticationError(resDTO.Message) - } - - var valDTO ValidationDTO - marshalledData, _ := json.Marshal(resDTO.Data) - err = json.Unmarshal(marshalledData, &valDTO) - if err != nil { - return nil, errs.NewAuthenticationError(err.Error()) - } - - return &AuthModel{ - UserId: valDTO.UserId, - Role: valDTO.Role, - }, nil +func (uh userHandler) UpdateUser(c *gin.Context) { + c.JSON(http.StatusOK, gin.H{"userId": c.Param("userId")}) + c.Abort() + return } -func (h userHandler) ValidateAuthToken() gin.HandlerFunc { - return func(c *gin.Context) { - res, err := ValidateToken(c.Request.Header.Get("Authorization")) +func (uh userHandler) DeleteUser(c *gin.Context) { + c.JSON(http.StatusOK, gin.H{"userId": c.Param("userId")}) + c.Abort() + return +} - if err != nil { - response := ResponseDTO{ - Status: err.Code, - Message: err.Message, - } - c.JSON(response.Status, response) - c.Abort() - return - } +func (uh userHandler) CreateUser(c *gin.Context) { - response := ResponseDTO{ - Status: http.StatusOK, - Data: res, - Message: "User authenticated successfully", - } - c.JSON(response.Status, response) - } } From ddc27e901003440f85514a38eb881547d1c99c3e Mon Sep 17 00:00:00 2001 From: murtaza896 Date: Sun, 24 Apr 2022 13:26:41 +0530 Subject: [PATCH 07/15] | scaffolding for auth with gateway | --- gateway/app/authMiddleware.go | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/gateway/app/authMiddleware.go b/gateway/app/authMiddleware.go index cdfac1b..031de36 100644 --- a/gateway/app/authMiddleware.go +++ b/gateway/app/authMiddleware.go @@ -7,6 +7,7 @@ import ( "github.com/swiggy-2022-bootcamp/cdp-team4/gateway/utils/errs" "log" "net/http" + "os" "time" ) @@ -21,8 +22,10 @@ type ValidationDTO struct { } func ValidateToken(authorizationHeader string) (*AuthModel, *errs.AppError) { - authServiceUri := "http://localhost:8881/api/v1/validate" - req, err := http.NewRequest("GET", authServiceUri, nil) + authServiceUri := os.Getenv("AUTH_SERVICE_URI") + validateTokenApi := "/api/v1/validate" + + req, err := http.NewRequest("GET", authServiceUri+validateTokenApi, nil) if err != nil { log.Fatalf("%v", err) } From e93c36a0d3e4c97a01659bb0f851318d67ce4c46 Mon Sep 17 00:00:00 2001 From: murtaza896 Date: Sun, 24 Apr 2022 13:27:49 +0530 Subject: [PATCH 08/15] | scaffolding for auth with gateway | --- gateway/.env | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/gateway/.env b/gateway/.env index 84e2cd8..4953131 100644 --- a/gateway/.env +++ b/gateway/.env @@ -1 +1,2 @@ -PORT=8882 \ No newline at end of file +PORT=8882 +AUTH_SERVICE_URI=http://localhost:8001 \ No newline at end of file From 5b14c22c634d1b98d5440031794ac7a4716205c4 Mon Sep 17 00:00:00 2001 From: murtaza896 Date: Sun, 24 Apr 2022 13:30:17 +0530 Subject: [PATCH 09/15] | changed port to 8000 | --- gateway/.env | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gateway/.env b/gateway/.env index 4953131..c3fb6e3 100644 --- a/gateway/.env +++ b/gateway/.env @@ -1,2 +1,2 @@ -PORT=8882 +PORT=8000 AUTH_SERVICE_URI=http://localhost:8001 \ No newline at end of file From 7dd7c69ec5b0a4a9eefe002ebf7d6d81b748d7f7 Mon Sep 17 00:00:00 2001 From: Swastik Sahoo 8082 Date: Sun, 24 Apr 2022 15:00:24 +0530 Subject: [PATCH 10/15] | Handle get user | --- gateway/.env | 3 ++- gateway/app/userHandler.go | 51 +++++++++++++++++++++++++++++++++++++- 2 files changed, 52 insertions(+), 2 deletions(-) diff --git a/gateway/.env b/gateway/.env index c3fb6e3..3257769 100644 --- a/gateway/.env +++ b/gateway/.env @@ -1,2 +1,3 @@ PORT=8000 -AUTH_SERVICE_URI=http://localhost:8001 \ No newline at end of file +AUTH_SERVICE_URI=http://localhost:8001 +USER_SERVICE_URI=http://localhost:8002 \ No newline at end of file diff --git a/gateway/app/userHandler.go b/gateway/app/userHandler.go index a3262e2..cf43db6 100644 --- a/gateway/app/userHandler.go +++ b/gateway/app/userHandler.go @@ -3,6 +3,12 @@ package app import ( "github.com/gin-gonic/gin" "net/http" + "os" + // "log" + // "fmt" + "encoding/json" + "context" + "time" ) type userHandler struct { @@ -22,7 +28,50 @@ func (uh userHandler) GetAllUsers(c *gin.Context) { } func (uh userHandler) GetUser(c *gin.Context) { - c.JSON(http.StatusOK, gin.H{"userId": c.Param("userId")}) + + userServiceURI := os.Getenv("USER_SERVICE_URI") + "/user/" + c.Param("userId") + + req, err := http.NewRequest("GET", userServiceURI, nil) + if err != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + + ctx, cancel := context.WithTimeout(req.Context(), 1*time.Minute) + defer cancel() + + req = req.WithContext(ctx) + client := http.DefaultClient + res, err1 := client.Do(req) + if err1 != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err1.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + + var userResDTO ResponseDTO + err = json.NewDecoder(res.Body).Decode(&userResDTO) + + if err != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + + c.JSON(userResDTO.Status, userResDTO) c.Abort() return } From 77760f9fe25294cd0cf054a75e76549163bee687 Mon Sep 17 00:00:00 2001 From: Swastik Sahoo 8082 Date: Sun, 24 Apr 2022 16:33:16 +0530 Subject: [PATCH 11/15] | Added get and post user handler | --- gateway/app/userHandler.go | 96 +++++++++++++++++++++++++++++++++++++- 1 file changed, 95 insertions(+), 1 deletion(-) diff --git a/gateway/app/userHandler.go b/gateway/app/userHandler.go index cf43db6..798cb20 100644 --- a/gateway/app/userHandler.go +++ b/gateway/app/userHandler.go @@ -5,12 +5,35 @@ import ( "net/http" "os" // "log" - // "fmt" + "fmt" "encoding/json" "context" "time" + "bytes" ) +type ShippingAddressDTO struct { + FirstName string `json:"firstname"` + LastName string `json:"lastname"` + City string `json:"city"` + Address1 string `json:"address_1"` + Address2 string `json:"address_2"` + CountryID uint32 `json:"country_id"` + PostCode uint32 `json:"postcode"` +} + +type UserDTO struct { + FirstName string `json:"first_name"` + LastName string `json:"last_name"` + Username string `json:"username"` + Password string `json:"password"` + Phone string `json:"phone"` + Email string `json:"email"` + Role int `json:"role"` + Address ShippingAddressDTO `json:"address"` + Fax string `json:"fax"` +} + type userHandler struct { } @@ -89,5 +112,76 @@ func (uh userHandler) DeleteUser(c *gin.Context) { } func (uh userHandler) CreateUser(c *gin.Context) { + userServiceURI := os.Getenv("USER_SERVICE_URI") + "/user" + + var newUser UserDTO + + if err := c.BindJSON(&newUser); err != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + + fmt.Printf("here1: %v", newUser) + + userJSON, err1 := json.Marshal(newUser) + + if err1 != nil { + fmt.Println("err1: ", err1.Error()) + } + + req, err2 := http.NewRequest("POST", userServiceURI, bytes.NewBuffer(userJSON)) + + if err2 != nil { + fmt.Println("err2: ", err2.Error()) + } + + fmt.Printf("resp: %v", req) + + if err2 != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err2.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + ctx, cancel := context.WithTimeout(req.Context(), 1*time.Minute) + defer cancel() + + req = req.WithContext(ctx) + client := http.DefaultClient + res, err1 := client.Do(req) + if err1 != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err1.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + + var userResDTO ResponseDTO + err := json.NewDecoder(res.Body).Decode(&userResDTO) + + if err != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + + c.JSON(userResDTO.Status, userResDTO) + c.Abort() + return } From 081a33d762e94a95e85e3cff5ce4555613faa84e Mon Sep 17 00:00:00 2001 From: Swastik Sahoo 8082 Date: Sun, 24 Apr 2022 16:33:16 +0530 Subject: [PATCH 12/15] | Added User handlers | --- gateway/app/userHandler.go | 288 ++++++++++++++++++++++++++++++++++++- 1 file changed, 281 insertions(+), 7 deletions(-) diff --git a/gateway/app/userHandler.go b/gateway/app/userHandler.go index cf43db6..3bf51c6 100644 --- a/gateway/app/userHandler.go +++ b/gateway/app/userHandler.go @@ -5,26 +5,91 @@ import ( "net/http" "os" // "log" - // "fmt" + "fmt" "encoding/json" "context" "time" + "bytes" ) +type ShippingAddressDTO struct { + FirstName string `json:"firstname"` + LastName string `json:"lastname"` + City string `json:"city"` + Address1 string `json:"address_1"` + Address2 string `json:"address_2"` + CountryID uint32 `json:"country_id"` + PostCode uint32 `json:"postcode"` +} + +type UserDTO struct { + FirstName string `json:"first_name"` + LastName string `json:"last_name"` + Username string `json:"username"` + Password string `json:"password"` + Phone string `json:"phone"` + Email string `json:"email"` + Role int `json:"role"` + Address ShippingAddressDTO `json:"address"` + Fax string `json:"fax"` +} + type userHandler struct { } func (uh userHandler) GetAllUsers(c *gin.Context) { isAdmin := c.Request.Header.Get("admin") - if isAdmin == "true" { - c.JSON(http.StatusOK, gin.H{"userId": c.Param("userId")}) + if isAdmin == "false" { + c.JSON(http.StatusUnauthorized, gin.H{}) c.Abort() return - } else { - c.JSON(http.StatusUnauthorized, gin.H{}) + } + + userServiceURI := os.Getenv("USER_SERVICE_URI") + "/users" + + req, err := http.NewRequest("GET", userServiceURI, nil) + if err != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + + ctx, cancel := context.WithTimeout(req.Context(), 1*time.Minute) + defer cancel() + + req = req.WithContext(ctx) + client := http.DefaultClient + res, err1 := client.Do(req) + if err1 != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err1.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + + var userResDTO ResponseDTO + err = json.NewDecoder(res.Body).Decode(&userResDTO) + + if err != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err.Error(), + } + c.JSON(responseDto.Status, responseDto) c.Abort() return } + + c.JSON(userResDTO.Status, userResDTO) + c.Abort() + return } func (uh userHandler) GetUser(c *gin.Context) { @@ -77,17 +142,226 @@ func (uh userHandler) GetUser(c *gin.Context) { } func (uh userHandler) UpdateUser(c *gin.Context) { - c.JSON(http.StatusOK, gin.H{"userId": c.Param("userId")}) + userServiceURI := os.Getenv("USER_SERVICE_URI") + "/user/" + c.Param("userId") + + var newUser UserDTO + + if err := c.BindJSON(&newUser); err != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + + fmt.Printf("here1: %v", newUser) + + userJSON, err1 := json.Marshal(newUser) + + if err1 != nil { + fmt.Println("err1: ", err1.Error()) + } + + req, err2 := http.NewRequest("PATCH", userServiceURI, bytes.NewBuffer(userJSON)) + + if err2 != nil { + fmt.Println("err2: ", err2.Error()) + } + + fmt.Printf("resp: %v", req) + + if err2 != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err2.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + + ctx, cancel := context.WithTimeout(req.Context(), 1*time.Minute) + defer cancel() + + req = req.WithContext(ctx) + client := http.DefaultClient + res, err1 := client.Do(req) + if err1 != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err1.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + + var userResDTO ResponseDTO + err := json.NewDecoder(res.Body).Decode(&userResDTO) + + if err != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + + c.JSON(userResDTO.Status, userResDTO) c.Abort() return } func (uh userHandler) DeleteUser(c *gin.Context) { - c.JSON(http.StatusOK, gin.H{"userId": c.Param("userId")}) + userServiceURI := os.Getenv("USER_SERVICE_URI") + "/user/" + c.Param("userId") + + var newUser UserDTO + + if err := c.BindJSON(&newUser); err != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + + fmt.Printf("here1: %v", newUser) + + userJSON, err1 := json.Marshal(newUser) + + if err1 != nil { + fmt.Println("err1: ", err1.Error()) + } + + req, err2 := http.NewRequest("DELETE", userServiceURI, bytes.NewBuffer(userJSON)) + + if err2 != nil { + fmt.Println("err2: ", err2.Error()) + } + + fmt.Printf("resp: %v", req) + + if err2 != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err2.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + + ctx, cancel := context.WithTimeout(req.Context(), 1*time.Minute) + defer cancel() + + req = req.WithContext(ctx) + client := http.DefaultClient + res, err1 := client.Do(req) + if err1 != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err1.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + + var userResDTO ResponseDTO + err := json.NewDecoder(res.Body).Decode(&userResDTO) + + if err != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + + c.JSON(userResDTO.Status, userResDTO) c.Abort() return } func (uh userHandler) CreateUser(c *gin.Context) { + userServiceURI := os.Getenv("USER_SERVICE_URI") + "/user" + var newUser UserDTO + + if err := c.BindJSON(&newUser); err != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + + fmt.Printf("here1: %v", newUser) + + userJSON, err1 := json.Marshal(newUser) + + if err1 != nil { + fmt.Println("err1: ", err1.Error()) + } + + req, err2 := http.NewRequest("POST", userServiceURI, bytes.NewBuffer(userJSON)) + + if err2 != nil { + fmt.Println("err2: ", err2.Error()) + } + + fmt.Printf("resp: %v", req) + + if err2 != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err2.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + + ctx, cancel := context.WithTimeout(req.Context(), 1*time.Minute) + defer cancel() + + req = req.WithContext(ctx) + client := http.DefaultClient + res, err1 := client.Do(req) + if err1 != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err1.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + + var userResDTO ResponseDTO + err := json.NewDecoder(res.Body).Decode(&userResDTO) + + if err != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + + c.JSON(userResDTO.Status, userResDTO) + c.Abort() + return } From c47d53fabe058ad3cb65e07c988d86137b0aa94d Mon Sep 17 00:00:00 2001 From: suhassuhas Date: Mon, 25 Apr 2022 22:12:01 +0530 Subject: [PATCH 13/15] | Added Order Handler | --- gateway/.env | 4 +- gateway/app/app.go | 9 +- gateway/app/orderHandler.go | 607 +++++++++++++++++++++++++++++++++ gateway/app/router.go | 37 +- gateway/app/shippingHandler.go | 542 +++++++++++++++++++++++++++++ gateway/go.mod | 1 + gateway/go.sum | 16 + 7 files changed, 1209 insertions(+), 7 deletions(-) create mode 100644 gateway/app/orderHandler.go create mode 100644 gateway/app/shippingHandler.go diff --git a/gateway/.env b/gateway/.env index 3257769..a90f526 100644 --- a/gateway/.env +++ b/gateway/.env @@ -1,3 +1,5 @@ PORT=8000 AUTH_SERVICE_URI=http://localhost:8001 -USER_SERVICE_URI=http://localhost:8002 \ No newline at end of file +USER_SERVICE_URI=http://localhost:8002 +ORDER_SERVICE_URI=http://localhost:8007 +SHIPPING_SERVICE_URI=http://localhost:8012 \ No newline at end of file diff --git a/gateway/app/app.go b/gateway/app/app.go index e27c6ef..fd1a290 100644 --- a/gateway/app/app.go +++ b/gateway/app/app.go @@ -1,15 +1,17 @@ package app -import "github.com/joho/godotenv" - import ( "fmt" "log" "os" + + "github.com/joho/godotenv" ) func Start() { RegisterUserRoutes() + RegisterOrderRoutes() + RegisterShippingRoutes() err := godotenv.Load(".env") if err != nil { log.Fatal(err) @@ -20,8 +22,9 @@ func Start() { log.Fatalf("Error loading .env file") } PORT := os.Getenv("PORT") + fmt.Print(PORT) - err = Router.Run(fmt.Sprintf(":%s", PORT)) + err = Router.Run(":8000") if err != nil { return } diff --git a/gateway/app/orderHandler.go b/gateway/app/orderHandler.go new file mode 100644 index 0000000..c8aa9e6 --- /dev/null +++ b/gateway/app/orderHandler.go @@ -0,0 +1,607 @@ +package app + +import ( + "net/http" + "os" + + "github.com/gin-gonic/gin" + + // "log" + "bytes" + "context" + "encoding/json" + "fmt" + "time" +) + +type ProductRecordDTO struct { + Product string `json:"name"` + Cost int16 `json:"cost"` + Quantity int `json:"quantity"` +} + +type OrderRecordDTO struct { + UserID string `json:"user_id"` + OrderID string `json:"order_id"` + Status string `json:"status"` + Products []ProductRecordDTO `json:"products"` + TotalCost int16 `json:"total_cost"` +} + +type OrderConfirmResponseDTO struct { + UserID string `json:"user_id"` + OrderID string `json:"order_id"` + Status string `json:"status"` + TotalCost int16 `json:"total_cost"` + ShippingPrice int16 `json:"shipping_price"` + RewardspointsConsumed int16 `json:"reward_points"` +} + +type InvoiceDTO struct { + UserID string `json:"user_id"` + Products []ProductRecordDTO `json:"products"` + Status string `json:"status"` + TotalCost int16 `json:"total_cost"` + ShippingPrice int16 `json:"shipping_price"` + RewardspointsConsumed int16 `json:"reward_points"` +} + +type OrderOverviewRecordDTO struct { + OrderID string `json:"order_id"` + Products map[string]int `json:"products"` +} + +type RequestDTO struct { + Id string `json:"id"` + Status string `json:"status"` +} + +type orderHandler struct { +} + +func (oh orderHandler) GetOrderByID(c *gin.Context) { + + isAdmin := c.Request.Header.Get("admin") + if isAdmin == "false" { + c.JSON(http.StatusUnauthorized, gin.H{}) + c.Abort() + return + } + + orderServiceURI := os.Getenv("ORDER_SERVICE_URI") + "/order/" + c.Param("id") + + req, err := http.NewRequest("GET", orderServiceURI, nil) + if err != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + + ctx, cancel := context.WithTimeout(req.Context(), 1*time.Minute) + defer cancel() + + req = req.WithContext(ctx) + client := http.DefaultClient + res, err1 := client.Do(req) + if err1 != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err1.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + + var orderResDTO ResponseDTO + err = json.NewDecoder(res.Body).Decode(&orderResDTO) + + if err != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + + c.JSON(orderResDTO.Status, orderResDTO) +} + +func (oh orderHandler) GetOrderByUserID(c *gin.Context) { + + orderServiceURI := os.Getenv("ORDER_SERVICE_URI") + "/order/user/" + c.Param("user_id") + + req, err := http.NewRequest("GET", orderServiceURI, nil) + if err != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + + ctx, cancel := context.WithTimeout(req.Context(), 1*time.Minute) + defer cancel() + + req = req.WithContext(ctx) + client := http.DefaultClient + res, err1 := client.Do(req) + if err1 != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err1.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + + var orderResDTO ResponseDTO + err = json.NewDecoder(res.Body).Decode(&orderResDTO) + + if err != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + + c.JSON(orderResDTO.Status, orderResDTO) +} + +func (oh orderHandler) GetOrderByStatus(c *gin.Context) { + + isAdmin := c.Request.Header.Get("admin") + if isAdmin == "false" { + c.JSON(http.StatusUnauthorized, gin.H{}) + c.Abort() + return + } + + orderServiceURI := os.Getenv("ORDER_SERVICE_URI") + "/order/status/" + c.Param("status") + + req, err := http.NewRequest("GET", orderServiceURI, nil) + if err != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + + ctx, cancel := context.WithTimeout(req.Context(), 1*time.Minute) + defer cancel() + + req = req.WithContext(ctx) + client := http.DefaultClient + res, err1 := client.Do(req) + if err1 != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err1.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + + var orderResDTO ResponseDTO + err = json.NewDecoder(res.Body).Decode(&orderResDTO) + + if err != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + + c.JSON(orderResDTO.Status, orderResDTO) +} + +func (oh orderHandler) GetOrderInvoice(c *gin.Context) { + + orderServiceURI := os.Getenv("ORDER_SERVICE_URI") + "/order/invoice/" + c.Param("order_id") + + req, err := http.NewRequest("GET", orderServiceURI, nil) + if err != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + + ctx, cancel := context.WithTimeout(req.Context(), 1*time.Minute) + defer cancel() + + req = req.WithContext(ctx) + client := http.DefaultClient + res, err1 := client.Do(req) + if err1 != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err1.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + + var orderResDTO ResponseDTO + err = json.NewDecoder(res.Body).Decode(&orderResDTO) + + if err != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + + c.JSON(orderResDTO.Status, orderResDTO) +} + +func (oh orderHandler) GetAllOrders(c *gin.Context) { + + isAdmin := c.Request.Header.Get("admin") + if isAdmin == "false" { + c.JSON(http.StatusUnauthorized, gin.H{}) + c.Abort() + return + } + + orderServiceURI := os.Getenv("ORDER_SERVICE_URI") + "/orders" + + req, err := http.NewRequest("GET", orderServiceURI, nil) + if err != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + + ctx, cancel := context.WithTimeout(req.Context(), 1*time.Minute) + defer cancel() + + req = req.WithContext(ctx) + client := http.DefaultClient + res, err1 := client.Do(req) + if err1 != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err1.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + + var orderResDTO ResponseDTO + err = json.NewDecoder(res.Body).Decode(&orderResDTO) + + if err != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + + c.JSON(orderResDTO.Status, orderResDTO) +} + +func (oh orderHandler) UpdateOrder(c *gin.Context) { + isAdmin := c.Request.Header.Get("admin") + if isAdmin == "false" { + c.JSON(http.StatusUnauthorized, gin.H{}) + c.Abort() + return + } + orderServiceURI := os.Getenv("ORDER_SERVICE_URI") + "/order/status" + + var updateOrder RequestDTO + + if err := c.BindJSON(&updateOrder); err != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + + fmt.Printf("here1: %v", updateOrder) + + orderJSON, err1 := json.Marshal(updateOrder) + + if err1 != nil { + fmt.Println("err1: ", err1.Error()) + } + + req, err2 := http.NewRequest("PUT", orderServiceURI, bytes.NewBuffer(orderJSON)) + + if err2 != nil { + fmt.Println("err2: ", err2.Error()) + } + + fmt.Printf("resp: %v", req) + + if err2 != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err2.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + + ctx, cancel := context.WithTimeout(req.Context(), 1*time.Minute) + defer cancel() + + req = req.WithContext(ctx) + client := http.DefaultClient + res, err1 := client.Do(req) + if err1 != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err1.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + + var orderResDTO ResponseDTO + err := json.NewDecoder(res.Body).Decode(&orderResDTO) + + if err != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + + c.JSON(orderResDTO.Status, orderResDTO) +} + +func (oh orderHandler) DeleteOrder(c *gin.Context) { + isAdmin := c.Request.Header.Get("admin") + if isAdmin == "false" { + c.JSON(http.StatusUnauthorized, gin.H{}) + c.Abort() + return + } + orderServiceURI := os.Getenv("ORDER_SERVICE_URI") + "/order/" + c.Param("id") + + req, err2 := http.NewRequest("DELETE", orderServiceURI, nil) + + if err2 != nil { + fmt.Println("err2: ", err2.Error()) + } + + fmt.Printf("resp: %v", req) + + if err2 != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err2.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + + ctx, cancel := context.WithTimeout(req.Context(), 1*time.Minute) + defer cancel() + + req = req.WithContext(ctx) + client := http.DefaultClient + res, err1 := client.Do(req) + if err1 != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err1.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + + var orderResDTO ResponseDTO + err := json.NewDecoder(res.Body).Decode(&orderResDTO) + + if err != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + + c.JSON(orderResDTO.Status, orderResDTO) + c.Abort() +} + +func (oh orderHandler) CreateOrder(c *gin.Context) { + isAdmin := c.Request.Header.Get("admin") + if isAdmin == "false" { + c.JSON(http.StatusUnauthorized, gin.H{}) + c.Abort() + return + } + orderServiceURI := os.Getenv("ORDER_SERVICE_URI") + "/order" + + var newOrder OrderRecordDTO + + if err := c.BindJSON(&newOrder); err != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + + fmt.Printf("here1: %v", newOrder) + + orderJSON, err1 := json.Marshal(newOrder) + + if err1 != nil { + fmt.Println("err1: ", err1.Error()) + } + + req, err2 := http.NewRequest("POST", orderServiceURI, bytes.NewBuffer(orderJSON)) + + if err2 != nil { + fmt.Println("err2: ", err2.Error()) + } + + fmt.Printf("resp: %v", req) + + if err2 != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err2.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + + ctx, cancel := context.WithTimeout(req.Context(), 1*time.Minute) + defer cancel() + + req = req.WithContext(ctx) + client := http.DefaultClient + res, err1 := client.Do(req) + if err1 != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err1.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + + var orderResDTO ResponseDTO + err := json.NewDecoder(res.Body).Decode(&orderResDTO) + + if err != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + + c.JSON(orderResDTO.Status, orderResDTO) +} + +func (oh orderHandler) ConfirmOrder(c *gin.Context) { + orderServiceURI := os.Getenv("ORDER_SERVICE_URI") + "/confirm/" + c.Param("user_id") + + var newOrder OrderRecordDTO + + if err := c.BindJSON(&newOrder); err != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + + fmt.Printf("here1: %v", newOrder) + + orderJSON, err1 := json.Marshal(newOrder) + + if err1 != nil { + fmt.Println("err1: ", err1.Error()) + } + + req, err2 := http.NewRequest("POST", orderServiceURI, bytes.NewBuffer(orderJSON)) + + if err2 != nil { + fmt.Println("err2: ", err2.Error()) + } + + fmt.Printf("resp: %v", req) + + if err2 != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err2.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + + ctx, cancel := context.WithTimeout(req.Context(), 1*time.Minute) + defer cancel() + + req = req.WithContext(ctx) + client := http.DefaultClient + res, err1 := client.Do(req) + if err1 != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err1.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + + var orderResDTO ResponseDTO + err := json.NewDecoder(res.Body).Decode(&orderResDTO) + + if err != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + + c.JSON(orderResDTO.Status, orderResDTO) +} diff --git a/gateway/app/router.go b/gateway/app/router.go index 87bcda4..06620f8 100644 --- a/gateway/app/router.go +++ b/gateway/app/router.go @@ -2,9 +2,6 @@ package app import ( "github.com/gin-gonic/gin" - //swaggerFiles "github.com/swaggo/files" - //ginSwagger "github.com/swaggo/gin-swagger" - //"github.com/swiggy-2022-bootcamp/cdp-team4/gateway/docs" ) var v1 *gin.RouterGroup @@ -30,3 +27,37 @@ func RegisterUserRoutes() { users.PATCH("/", ValidateAuthToken(), userHandler.UpdateUser) users.DELETE("/", ValidateAuthToken(), userHandler.DeleteUser) } + +func RegisterOrderRoutes() { + orderhandler := orderHandler{} + orders := v1.Group("/order") + + v1.GET("/orders", ValidateAuthToken(), orderhandler.GetAllOrders) + + orders.POST("/", ValidateAuthToken(), orderhandler.CreateOrder) + orders.GET("/:id", ValidateAuthToken(), orderhandler.GetOrderByID) + orders.GET("/user/:user_id", ValidateAuthToken(), orderhandler.GetOrderByUserID) + orders.GET("/status/:status", ValidateAuthToken(), orderhandler.GetOrderByStatus) + orders.PUT("/:id", ValidateAuthToken(), orderhandler.UpdateOrder) + orders.DELETE("/:id", ValidateAuthToken(), orderhandler.DeleteOrder) + orders.POST("/confirm/:user_id", ValidateAuthToken(), orderhandler.ConfirmOrder) + orders.GET("/order/invoice/:order_id", ValidateAuthToken(), orderhandler.GetOrderInvoice) +} + +func RegisterShippingRoutes() { + shippingHandler := shippingHandler{} + shippingAddress := v1.Group("/shippingaddress") + + shippingAddress.POST("/", ValidateAuthToken(), shippingHandler.CreateShippingAddress) + shippingAddress.GET("/:id", ValidateAuthToken(), shippingHandler.GetShippingAddressByID) + shippingAddress.PUT("/:id", ValidateAuthToken(), shippingHandler.UpdateShippingAddress) + shippingAddress.DELETE("/:id", ValidateAuthToken(), shippingHandler.DeleteShippingAddress) + + shippingCost := v1.Group("/shippingcost") + + shippingCost.POST("/", ValidateAuthToken(), shippingHandler.CreateShippingCost) + shippingCost.GET("/:city", ValidateAuthToken(), shippingHandler.GetShippingCostByCity) + shippingCost.PUT("/", ValidateAuthToken(), shippingHandler.UpdateShippingCost) + shippingCost.DELETE("/:city", ValidateAuthToken(), shippingHandler.DeleteShippingCost) + +} diff --git a/gateway/app/shippingHandler.go b/gateway/app/shippingHandler.go new file mode 100644 index 0000000..82bcbce --- /dev/null +++ b/gateway/app/shippingHandler.go @@ -0,0 +1,542 @@ +package app + +import ( + "net/http" + "os" + + "github.com/gin-gonic/gin" + + // "log" + "bytes" + "context" + "encoding/json" + "fmt" + "time" +) + +type ShippingAddressRecordDTO struct { + FirstName string `json:"firstname"` + LastName string `json:"lastname"` + City string `json:"city"` + Address1 string `json:"address_1"` + Address2 string `json:"address_2"` + CountryID int `json:"country_id"` + PostCode int `json:"postcode"` +} + +type ShippingCostRecordDTO struct { + City string `json:"city"` + Cost int `json:"cost"` +} + +type shippingHandler struct { +} + +func (sh shippingHandler) GetShippingAddressByID(c *gin.Context) { + + shippingAddressServiceURI := os.Getenv("SHIPPING_SERVICE_URI") + "/shippingaddress/" + c.Param("id") + + req, err := http.NewRequest("GET", shippingAddressServiceURI, nil) + if err != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + + ctx, cancel := context.WithTimeout(req.Context(), 1*time.Minute) + defer cancel() + + req = req.WithContext(ctx) + client := http.DefaultClient + res, err1 := client.Do(req) + if err1 != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err1.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + + var shippingAddressResDTO ResponseDTO + err = json.NewDecoder(res.Body).Decode(&shippingAddressResDTO) + + if err != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + + c.JSON(shippingAddressResDTO.Status, shippingAddressResDTO) +} + +func (sh shippingHandler) UpdateShippingAddress(c *gin.Context) { + shippingAddressServiceURI := os.Getenv("SHIPPING_SERVICE_URI") + "/shippingaddress/" + c.Param("id") + + var updateShippingAddress ShippingAddressRecordDTO + + if err := c.BindJSON(&updateShippingAddress); err != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + + fmt.Printf("here1: %v", updateShippingAddress) + + shippingAddressJSON, err1 := json.Marshal(updateShippingAddress) + + if err1 != nil { + fmt.Println("err1: ", err1.Error()) + } + + req, err2 := http.NewRequest("PUT", shippingAddressServiceURI, bytes.NewBuffer(shippingAddressJSON)) + + if err2 != nil { + fmt.Println("err2: ", err2.Error()) + } + + fmt.Printf("resp: %v", req) + + if err2 != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err2.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + + ctx, cancel := context.WithTimeout(req.Context(), 1*time.Minute) + defer cancel() + + req = req.WithContext(ctx) + client := http.DefaultClient + res, err1 := client.Do(req) + if err1 != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err1.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + + var shippingAddressResDTO ResponseDTO + err := json.NewDecoder(res.Body).Decode(&shippingAddressResDTO) + + if err != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + + c.JSON(shippingAddressResDTO.Status, shippingAddressResDTO) +} + +func (sh shippingHandler) DeleteShippingAddress(c *gin.Context) { + shippingAddressServiceURI := os.Getenv("SHIPPING_SERVICE_URI") + "/shippingaddress/" + c.Param("id") + + req, err2 := http.NewRequest("DELETE", shippingAddressServiceURI, nil) + + if err2 != nil { + fmt.Println("err2: ", err2.Error()) + } + + fmt.Printf("resp: %v", req) + + if err2 != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err2.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + + ctx, cancel := context.WithTimeout(req.Context(), 1*time.Minute) + defer cancel() + + req = req.WithContext(ctx) + client := http.DefaultClient + res, err1 := client.Do(req) + if err1 != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err1.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + + var shippingAddressResDTO ResponseDTO + err := json.NewDecoder(res.Body).Decode(&shippingAddressResDTO) + + if err != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + + c.JSON(shippingAddressResDTO.Status, shippingAddressResDTO) + c.Abort() +} + +func (sh shippingHandler) CreateShippingAddress(c *gin.Context) { + shippingAddressServiceURI := os.Getenv("SHIPPING_SERVICE_URI") + "/shippingaddress" + + var newShippingAddress ShippingAddressRecordDTO + + if err := c.BindJSON(&newShippingAddress); err != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + + fmt.Printf("here1: %v", newShippingAddress) + + shippingAddressJSON, err1 := json.Marshal(newShippingAddress) + + if err1 != nil { + fmt.Println("err1: ", err1.Error()) + } + + req, err2 := http.NewRequest("POST", shippingAddressServiceURI, bytes.NewBuffer(shippingAddressJSON)) + + if err2 != nil { + fmt.Println("err2: ", err2.Error()) + } + + fmt.Printf("resp: %v", req) + + if err2 != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err2.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + + ctx, cancel := context.WithTimeout(req.Context(), 1*time.Minute) + defer cancel() + + req = req.WithContext(ctx) + client := http.DefaultClient + res, err1 := client.Do(req) + if err1 != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err1.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + + var shippingAddressResDTO ResponseDTO + err := json.NewDecoder(res.Body).Decode(&shippingAddressResDTO) + + if err != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + + c.JSON(shippingAddressResDTO.Status, shippingAddressResDTO) +} + +func (sh shippingHandler) GetShippingCostByCity(c *gin.Context) { + + isAdmin := c.Request.Header.Get("admin") + if isAdmin == "false" { + c.JSON(http.StatusUnauthorized, gin.H{}) + c.Abort() + return + } + + shippingCostServiceURI := os.Getenv("SHIPPING_SERVICE_URI") + "/shippingcost/" + c.Param("city") + + req, err := http.NewRequest("GET", shippingCostServiceURI, nil) + if err != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + + ctx, cancel := context.WithTimeout(req.Context(), 1*time.Minute) + defer cancel() + + req = req.WithContext(ctx) + client := http.DefaultClient + res, err1 := client.Do(req) + if err1 != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err1.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + + var shippingCostResDTO ResponseDTO + err = json.NewDecoder(res.Body).Decode(&shippingCostResDTO) + + if err != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + + c.JSON(shippingCostResDTO.Status, shippingCostResDTO) +} + +func (sh shippingHandler) UpdateShippingCost(c *gin.Context) { + + isAdmin := c.Request.Header.Get("admin") + if isAdmin == "false" { + c.JSON(http.StatusUnauthorized, gin.H{}) + c.Abort() + return + } + + shippingCostServiceURI := os.Getenv("SHIPPING_SERVICE_URI") + "/shippingcost" + + var updateShippingCost ShippingCostRecordDTO + + if err := c.BindJSON(&updateShippingCost); err != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + + fmt.Printf("here1: %v", updateShippingCost) + + shippingCostJSON, err1 := json.Marshal(updateShippingCost) + + if err1 != nil { + fmt.Println("err1: ", err1.Error()) + } + + req, err2 := http.NewRequest("PUT", shippingCostServiceURI, bytes.NewBuffer(shippingCostJSON)) + + if err2 != nil { + fmt.Println("err2: ", err2.Error()) + } + + fmt.Printf("resp: %v", req) + + if err2 != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err2.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + + ctx, cancel := context.WithTimeout(req.Context(), 1*time.Minute) + defer cancel() + + req = req.WithContext(ctx) + client := http.DefaultClient + res, err1 := client.Do(req) + if err1 != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err1.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + + var shippingCostsResDTO ResponseDTO + err := json.NewDecoder(res.Body).Decode(&shippingCostsResDTO) + + if err != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + + c.JSON(shippingCostsResDTO.Status, shippingCostsResDTO) +} + +func (sh shippingHandler) DeleteShippingCost(c *gin.Context) { + shippingCostServiceURI := os.Getenv("SHIPPING_SERVICE_URI") + "/shippingcost/" + c.Param("city") + + req, err2 := http.NewRequest("DELETE", shippingCostServiceURI, nil) + + if err2 != nil { + fmt.Println("err2: ", err2.Error()) + } + + fmt.Printf("resp: %v", req) + + if err2 != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err2.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + + ctx, cancel := context.WithTimeout(req.Context(), 1*time.Minute) + defer cancel() + + req = req.WithContext(ctx) + client := http.DefaultClient + res, err1 := client.Do(req) + if err1 != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err1.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + + var shippingCostResDTO ResponseDTO + err := json.NewDecoder(res.Body).Decode(&shippingCostResDTO) + + if err != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + + c.JSON(shippingCostResDTO.Status, shippingCostResDTO) + c.Abort() +} + +func (sh shippingHandler) CreateShippingCost(c *gin.Context) { + shippingAddressServiceURI := os.Getenv("SHIPPING_SERVICE_URI") + "/shippingcost" + + var newShippingCost ShippingCostRecordDTO + + if err := c.BindJSON(&newShippingCost); err != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + + fmt.Printf("here1: %v", newShippingCost) + + shippingCostJSON, err1 := json.Marshal(newShippingCost) + + if err1 != nil { + fmt.Println("err1: ", err1.Error()) + } + + req, err2 := http.NewRequest("POST", shippingAddressServiceURI, bytes.NewBuffer(shippingCostJSON)) + + if err2 != nil { + fmt.Println("err2: ", err2.Error()) + } + + fmt.Printf("resp: %v", req) + + if err2 != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err2.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + + ctx, cancel := context.WithTimeout(req.Context(), 1*time.Minute) + defer cancel() + + req = req.WithContext(ctx) + client := http.DefaultClient + res, err1 := client.Do(req) + if err1 != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err1.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + + var shippingCostResDTO ResponseDTO + err := json.NewDecoder(res.Body).Decode(&shippingCostResDTO) + + if err != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + + c.JSON(shippingCostResDTO.Status, shippingCostResDTO) +} diff --git a/gateway/go.mod b/gateway/go.mod index a84da30..d89a4b3 100644 --- a/gateway/go.mod +++ b/gateway/go.mod @@ -9,6 +9,7 @@ require ( ) require ( + github.com/gin-contrib/cors v1.3.1 // indirect github.com/gin-contrib/sse v0.1.0 // indirect github.com/go-playground/locales v0.13.0 // indirect github.com/go-playground/universal-translator v0.17.0 // indirect diff --git a/gateway/go.sum b/gateway/go.sum index 8fe2c25..03f5456 100644 --- a/gateway/go.sum +++ b/gateway/go.sum @@ -1,27 +1,39 @@ github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/gin-contrib/cors v1.3.1 h1:doAsuITavI4IOcd0Y19U4B+O0dNWihRyX//nn4sEmgA= +github.com/gin-contrib/cors v1.3.1/go.mod h1:jjEJ4268OPZUcU7k9Pm653S7lXUGcqMADzFA61xsmDk= github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE= github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI= +github.com/gin-gonic/gin v1.5.0/go.mod h1:Nd6IXA8m5kNZdNEHMBd93KT+mdY3+bewLgRvmCsR2Do= github.com/gin-gonic/gin v1.7.7 h1:3DoBmSbJbZAWqXJC3SLjAPfutPJJRN1U5pALB7EeTTs= github.com/gin-gonic/gin v1.7.7/go.mod h1:axIBovoeJpVj8S3BwE0uPMTeReE4+AfFtqpqaZ1qq1U= github.com/go-playground/assert/v2 v2.0.1 h1:MsBgLAaY856+nPRTKrp3/OZK38U/wa0CcBYNjji3q3A= github.com/go-playground/assert/v2 v2.0.1/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= +github.com/go-playground/locales v0.12.1/go.mod h1:IUMDtCfWo/w/mtMfIE/IG2K+Ey3ygWanZIBtBW0W2TM= github.com/go-playground/locales v0.13.0 h1:HyWk6mgj5qFqCT5fjGBuRArbVDfE4hi8+e8ceBS/t7Q= github.com/go-playground/locales v0.13.0/go.mod h1:taPMhCMXrRLJO55olJkUXHZBHCxTMfnGwq/HNwmWNS8= +github.com/go-playground/universal-translator v0.16.0/go.mod h1:1AnU7NaIRDWWzGEKwgtJRd2xk99HeFyHw3yid4rvQIY= github.com/go-playground/universal-translator v0.17.0 h1:icxd5fm+REJzpZx7ZfpaD876Lmtgy7VtROAbHHXk8no= github.com/go-playground/universal-translator v0.17.0/go.mod h1:UkSxE5sNxxRwHyU+Scu5vgOQjsIJAF8j9muTVoKLVtA= github.com/go-playground/validator/v10 v10.4.1 h1:pH2c5ADXtd66mxoE0Zm9SUhxE20r7aM3F26W0hOn+GE= github.com/go-playground/validator/v10 v10.4.1/go.mod h1:nlOn6nFhuKACm19sB/8EGNn9GlaMV7XkbRSipzJ0Ii4= +github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.3.3 h1:gyjaxf+svBWX08ZjK86iN9geUJF0H6gp2IRKX6Nf6/I= github.com/golang/protobuf v1.3.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/joho/godotenv v1.4.0 h1:3l4+N6zfMWnkbPEXKng2o2/MR5mSwTrBih4ZEkkz1lg= github.com/joho/godotenv v1.4.0/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4= +github.com/json-iterator/go v1.1.7/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= github.com/json-iterator/go v1.1.9 h1:9yzud/Ht36ygwatGx56VwCZtlI/2AD15T1X2sjSuGns= github.com/json-iterator/go v1.1.9/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= +github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= +github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= +github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= +github.com/leodido/go-urn v1.1.0/go.mod h1:+cyI34gQWZcE1eQU7NVgKkkzdXDQHr1dBMtdAPozLkw= github.com/leodido/go-urn v1.2.0 h1:hpXL4XnriNwQ/ABnpepYM/1vCLWNDfUNts8dX3xTG6Y= github.com/leodido/go-urn v1.2.0/go.mod h1:+8+nEpDfqqsY+g338gtMEUOtuK+4dEMhiQEgxpxOKII= +github.com/mattn/go-isatty v0.0.9/go.mod h1:YNRxwqDuOph6SZLI9vUUz6OYw3QyUt7WiY2yME+cCiQ= github.com/mattn/go-isatty v0.0.12 h1:wuysRhFDzyxgEmMf5xjvJ2M9dZoWAXNNr5LSBS7uHXY= github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 h1:ZqeYNhU3OHLH3mGKHDcjJRFFRrJa6eAM5H+CtDdOsPc= @@ -45,6 +57,7 @@ golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPh golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190813064441-fde4db37ae7a/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200116001909-b77594299b42 h1:vEOn+mP2zCOVzKckCZy6YsCtDblrpj/w7B9nxGNELpg= golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= @@ -52,6 +65,9 @@ golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/go-playground/assert.v1 v1.2.1/go.mod h1:9RXL0bg/zibRAgZUYszZSwO/z8Y/a8bDuhia5mkpMnE= +gopkg.in/go-playground/validator.v9 v9.29.1/go.mod h1:+c9/zcJMFNgbLvly1L1V+PpxWdVbfP1avr/N00E2vyQ= gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.8 h1:obN1ZagJSUGI0Ek/LBmuj4SNLPfIny3KsKFopxRdj10= gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= From 8a0eeb496c10e72c946c1944038223623d8c1ee9 Mon Sep 17 00:00:00 2001 From: poojasethia Date: Tue, 26 Apr 2022 18:14:08 +0530 Subject: [PATCH 14/15] |Added Product admin handler| --- gateway/.env | 5 +- gateway/app/app.go | 4 + gateway/app/productAdminHandler.go | 499 +++++++++++++++++++++++++++++ gateway/app/router.go | 39 +++ 4 files changed, 546 insertions(+), 1 deletion(-) create mode 100644 gateway/app/productAdminHandler.go diff --git a/gateway/.env b/gateway/.env index a90f526..3d0f28c 100644 --- a/gateway/.env +++ b/gateway/.env @@ -2,4 +2,7 @@ PORT=8000 AUTH_SERVICE_URI=http://localhost:8001 USER_SERVICE_URI=http://localhost:8002 ORDER_SERVICE_URI=http://localhost:8007 -SHIPPING_SERVICE_URI=http://localhost:8012 \ No newline at end of file +SHIPPING_SERVICE_URI=http://localhost:8012 +PRODUCT_ADMIN_SERVICE_URI=http://localhost:8004 +PRODUCT_FRONT_STORE_SERVICE_URI=http://localhost:8003 +CATEGORY_SERVICE_URI=http://localhost:8005 \ No newline at end of file diff --git a/gateway/app/app.go b/gateway/app/app.go index fd1a290..559265c 100644 --- a/gateway/app/app.go +++ b/gateway/app/app.go @@ -12,6 +12,10 @@ func Start() { RegisterUserRoutes() RegisterOrderRoutes() RegisterShippingRoutes() + RegisterProductAdminRoutes() + RegisterProductFrontStoreRoutes() + RegisterCategoryRoutes() + err := godotenv.Load(".env") if err != nil { log.Fatal(err) diff --git a/gateway/app/productAdminHandler.go b/gateway/app/productAdminHandler.go new file mode 100644 index 0000000..31d8d98 --- /dev/null +++ b/gateway/app/productAdminHandler.go @@ -0,0 +1,499 @@ +package app + +import ( + "net/http" + "os" + + "bytes" + "context" + "encoding/json" + "fmt" + "time" + + "github.com/gin-gonic/gin" +) + +type productAdminHandler struct { +} + +func (pah productAdminHandler) GetAllProducts(c *gin.Context) { + isAdmin := c.Request.Header.Get("admin") + if isAdmin == "false" { + c.JSON(http.StatusUnauthorized, gin.H{}) + c.Abort() + return + } + productAdminServiceURI := os.Getenv("PRODUCT_ADMIN_SERVICE_URI") + "/products" + + req, err := http.NewRequest("GET", productAdminServiceURI, nil) + if err != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + ctx, cancel := context.WithTimeout(req.Context(), 1*time.Minute) + defer cancel() + + req = req.WithContext(ctx) + client := http.DefaultClient + res, err1 := client.Do(req) + if err1 != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err1.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + var productResponseDTO ResponseDTO + err = json.NewDecoder(res.Body).Decode(&productResponseDTO) + + if err != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + + c.JSON(productResponseDTO.Status, productResponseDTO) +} + +func (pah productAdminHandler) AddProduct(c *gin.Context) { + isAdmin := c.Request.Header.Get("admin") + if isAdmin == "false" { + c.JSON(http.StatusUnauthorized, gin.H{}) + c.Abort() + return + } + productAdminServiceURI := os.Getenv("PRODUCT_ADMIN_SERVICE_URI") + "/products/" + + var newProduct ProductAdminDTO + if err := c.BindJSON(&newProduct); err != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + + fmt.Printf("here1: %v", newProduct) + + productJSON, err1 := json.Marshal(newProduct) + if err1 != nil { + fmt.Println("err1: ", err1.Error()) + } + + req, err2 := http.NewRequest("POST", productAdminServiceURI, bytes.NewBuffer(productJSON)) + if err2 != nil { + fmt.Println("err2: ", err2.Error()) + } + + fmt.Printf("resp: %v", req) + + if err2 != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err2.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + + ctx, cancel := context.WithTimeout(req.Context(), 1*time.Minute) + defer cancel() + + req = req.WithContext(ctx) + client := http.DefaultClient + res, err1 := client.Do(req) + if err1 != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err1.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + + var productResponseDTO ResponseDTO + err := json.NewDecoder(res.Body).Decode(&productResponseDTO) + + if err != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + + c.JSON(productResponseDTO.Status, productResponseDTO) +} + +func (pah productAdminHandler) GetProductByID(c *gin.Context) { + isAdmin := c.Request.Header.Get("admin") + if isAdmin == "false" { + c.JSON(http.StatusUnauthorized, gin.H{}) + c.Abort() + return + } + productAdminServiceURI := os.Getenv("PRODUCT_ADMIN_SERVICE_URI") + "/products/" + c.Param("id") + + req, err := http.NewRequest("GET", productAdminServiceURI, nil) + if err != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + ctx, cancel := context.WithTimeout(req.Context(), 1*time.Minute) + defer cancel() + req = req.WithContext(ctx) + client := http.DefaultClient + res, err1 := client.Do(req) + if err1 != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err1.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + + var productResponseDTO ResponseDTO + err = json.NewDecoder(res.Body).Decode(&productResponseDTO) + + if err != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + + c.JSON(productResponseDTO.Status, productResponseDTO) +} + +func (pah productAdminHandler) UpdateProductByID(c *gin.Context) { + isAdmin := c.Request.Header.Get("admin") + if isAdmin == "false" { + c.JSON(http.StatusUnauthorized, gin.H{}) + c.Abort() + return + } + productAdminServiceURI := os.Getenv("PRODUCT_ADMIN_SERVICE_URI") + "/products/" + c.Param("id") + var newProduct ProductAdminDTO + if err := c.BindJSON(&newProduct); err != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + + fmt.Printf("here1: %v", newProduct) + + productJSON, err1 := json.Marshal(newProduct) + if err1 != nil { + fmt.Println("err1: ", err1.Error()) + } + req, err := http.NewRequest("PUT", productAdminServiceURI, bytes.NewBuffer(productJSON)) + if err != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + ctx, cancel := context.WithTimeout(req.Context(), 1*time.Minute) + defer cancel() + + req = req.WithContext(ctx) + client := http.DefaultClient + res, err1 := client.Do(req) + if err1 != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err1.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + + var productResponseDTO ResponseDTO + err = json.NewDecoder(res.Body).Decode(&productResponseDTO) + + if err != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + + c.JSON(productResponseDTO.Status, productResponseDTO) +} + +func (pah productAdminHandler) DeleteProductByID(c *gin.Context) { + isAdmin := c.Request.Header.Get("admin") + if isAdmin == "false" { + c.JSON(http.StatusUnauthorized, gin.H{}) + c.Abort() + return + } + productAdminServiceURI := os.Getenv("PRODUCT_ADMIN_SERVICE_URI") + "/products/" + c.Param("id") + + req, err := http.NewRequest("DELETE", productAdminServiceURI, nil) + if err != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + ctx, cancel := context.WithTimeout(req.Context(), 1*time.Minute) + defer cancel() + req = req.WithContext(ctx) + client := http.DefaultClient + res, err1 := client.Do(req) + if err1 != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err1.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + + var productResponseDTO ResponseDTO + err = json.NewDecoder(res.Body).Decode(&productResponseDTO) + + if err != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + + c.JSON(productResponseDTO.Status, productResponseDTO) + c.Abort() +} + +func (pah productAdminHandler) SearchByCategoryID(c *gin.Context) { + isAdmin := c.Request.Header.Get("admin") + if isAdmin == "false" { + c.JSON(http.StatusUnauthorized, gin.H{}) + c.Abort() + return + } + productAdminServiceURI := os.Getenv("PRODUCT_ADMIN_SERVICE_URI") + "/products/search/category/" + c.Param("categoryid") + + req, err := http.NewRequest("GET", productAdminServiceURI, nil) + if err != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + ctx, cancel := context.WithTimeout(req.Context(), 1*time.Minute) + defer cancel() + req = req.WithContext(ctx) + client := http.DefaultClient + res, err1 := client.Do(req) + if err1 != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err1.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + + var productResponseDTO ResponseDTO + err = json.NewDecoder(res.Body).Decode(&productResponseDTO) + + if err != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + + c.JSON(productResponseDTO.Status, productResponseDTO) +} + +func (pah productAdminHandler) SearchByManufacturerID(c *gin.Context) { + isAdmin := c.Request.Header.Get("admin") + if isAdmin == "false" { + c.JSON(http.StatusUnauthorized, gin.H{}) + c.Abort() + return + } + productAdminServiceURI := os.Getenv("PRODUCT_ADMIN_SERVICE_URI") + "/products/search/manufacturer/" + c.Param("id") + + req, err := http.NewRequest("GET", productAdminServiceURI, nil) + if err != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + ctx, cancel := context.WithTimeout(req.Context(), 1*time.Minute) + defer cancel() + req = req.WithContext(ctx) + client := http.DefaultClient + res, err1 := client.Do(req) + if err1 != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err1.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + + var productResponseDTO ResponseDTO + err = json.NewDecoder(res.Body).Decode(&productResponseDTO) + + if err != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + + c.JSON(productResponseDTO.Status, productResponseDTO) +} + +func (pah productAdminHandler) SearchByKeyword(c *gin.Context) { + isAdmin := c.Request.Header.Get("admin") + if isAdmin == "false" { + c.JSON(http.StatusUnauthorized, gin.H{}) + c.Abort() + return + } + productAdminServiceURI := os.Getenv("PRODUCT_ADMIN_SERVICE_URI") + "/products/search/keyword/" + c.Param("keyword") + + req, err := http.NewRequest("GET", productAdminServiceURI, nil) + if err != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + ctx, cancel := context.WithTimeout(req.Context(), 1*time.Minute) + defer cancel() + req = req.WithContext(ctx) + client := http.DefaultClient + res, err1 := client.Do(req) + if err1 != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err1.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + + var productResponseDTO ResponseDTO + err = json.NewDecoder(res.Body).Decode(&productResponseDTO) + + if err != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + + c.JSON(productResponseDTO.Status, productResponseDTO) +} + +//================DTO================== +type ProductSEOURLDTO struct { + Keyword string `json:"keyword"` + LanguageID string `json:"language_id"` + StoreID string `json:"store_id"` +} + +type ProductDescriptionDTO struct { + LanguageID string `json:"language_id"` + Name string `json:"name"` + Description string `json:"description"` + MetaTitle string `json:"meta_title"` + MetaDescription string `json:"meta_description"` + MetaKeyword string `json:"meta_keyword"` + Tag string `json:"tag"` +} + +type ProductAdminDTO struct { + Model string `json:"model"` + Quantity int64 `json:"quantity"` + Price float64 `json:"price"` + ManufacturerID string `json:"manufacturer_id"` + SKU string `json:"sku"` + ProductSEOURLs []ProductSEOURLDTO `json:"product_seo_url"` + Points int64 `json:"points"` + Reward int64 `json:"reward"` + ImageURL string `json:"image_url"` + IsShippable bool `json:"is_shippable"` + Weight float64 `json:"weight"` + Length float64 `json:"length"` + Width float64 `json:"width"` + Height float64 `json:"height"` + MinimumQuantity int64 `json:"minimum_quantity"` + RelatedProducts []string `json:"related_products"` + ProductDescriptions []ProductDescriptionDTO `json:"product_description"` + ProductCategories []string `json:"product_categories"` +} diff --git a/gateway/app/router.go b/gateway/app/router.go index 06620f8..1e0a699 100644 --- a/gateway/app/router.go +++ b/gateway/app/router.go @@ -61,3 +61,42 @@ func RegisterShippingRoutes() { shippingCost.DELETE("/:city", ValidateAuthToken(), shippingHandler.DeleteShippingCost) } + +func RegisterProductAdminRoutes() { + productAdminHandler := productAdminHandler{} + products := v1.Group("/products") + + v1.GET("/products", ValidateAuthToken(), productAdminHandler.GetAllProducts) + + products.POST("/", ValidateAuthToken(), productAdminHandler.AddProduct) + products.GET("/:id", ValidateAuthToken(), productAdminHandler.GetProductByID) + products.PUT("/:id", ValidateAuthToken(), productAdminHandler.UpdateProductByID) + products.DELETE("/:id", ValidateAuthToken(), productAdminHandler.DeleteProductByID) + + search := products.Group("/search") + search.GET("/category/:categoryid", ValidateAuthToken(), productAdminHandler.SearchByCategoryID) + search.GET("/manufacturer/:id", ValidateAuthToken(), productAdminHandler.SearchByManufacturerID) + search.GET("/keyword/:keyword", ValidateAuthToken(), productAdminHandler.SearchByKeyword) +} + +func RegisterProductFrontStoreRoutes() { + // productFrontStoreHandler := productFrontStoreHandler{} + // products := v1.Group("/products") + + // v1.GET("/products", ValidateAuthToken(), productFrontStoreHandler.HandleGetAllProducts) + + // products.GET("/:id", ValidateAuthToken(), productFrontStoreHandler.HandleGetProductByID) + // products.GET("/category/:id", ValidateAuthToken(), productFrontStoreHandler.HandleGetProductsByCategory) +} + +func RegisterCategoryRoutes() { + // categoryHandler := categoryHandler{} + // categories := v1.Group("/categories") + + // categories.POST("/", ValidateAuthToken(), categoryHandler.HandleAddCategory) + // categories.GET("/", ValidateAuthToken(), categoryHandler.HandleGetAllCategories) + // categories.GET("/:id", ValidateAuthToken(), categoryHandler.HandleGetCategoryByID) + // categories.PUT("/:id", ValidateAuthToken(), categoryHandler.HandleUpdateCategoryByID) + // categories.DELETE("/", ValidateAuthToken(), categoryHandler.HandleDeleteCategories) + // categories.DELETE("/:id", ValidateAuthToken(), categoryHandler.HandleDeleteCategoryByID) +} From 19af6ed9e70bc8d0639fc8eb18625d235006cc91 Mon Sep 17 00:00:00 2001 From: nitesh585 Date: Tue, 26 Apr 2022 19:14:25 +0530 Subject: [PATCH 15/15] |Added Payment handler| --- gateway/.env | 9 +- gateway/app/app.go | 1 + gateway/app/paymentHandler.go | 211 ++++++++++++++++++++++++++++++++++ gateway/app/router.go | 11 +- 4 files changed, 227 insertions(+), 5 deletions(-) create mode 100644 gateway/app/paymentHandler.go diff --git a/gateway/.env b/gateway/.env index 3d0f28c..22c5282 100644 --- a/gateway/.env +++ b/gateway/.env @@ -1,8 +1,9 @@ PORT=8000 AUTH_SERVICE_URI=http://localhost:8001 USER_SERVICE_URI=http://localhost:8002 -ORDER_SERVICE_URI=http://localhost:8007 -SHIPPING_SERVICE_URI=http://localhost:8012 -PRODUCT_ADMIN_SERVICE_URI=http://localhost:8004 PRODUCT_FRONT_STORE_SERVICE_URI=http://localhost:8003 -CATEGORY_SERVICE_URI=http://localhost:8005 \ No newline at end of file +PRODUCT_ADMIN_SERVICE_URI=http://localhost:8004 +CATEGORY_SERVICE_URI=http://localhost:8005 +ORDER_SERVICE_URI=http://localhost:8007 +PAYMENT_SERVICE_URI=http://localhost:8008 +SHIPPING_SERVICE_URI=http://localhost:8012 \ No newline at end of file diff --git a/gateway/app/app.go b/gateway/app/app.go index 559265c..a730a40 100644 --- a/gateway/app/app.go +++ b/gateway/app/app.go @@ -15,6 +15,7 @@ func Start() { RegisterProductAdminRoutes() RegisterProductFrontStoreRoutes() RegisterCategoryRoutes() + RegisterPaymentRoutes() err := godotenv.Load(".env") if err != nil { diff --git a/gateway/app/paymentHandler.go b/gateway/app/paymentHandler.go new file mode 100644 index 0000000..c658e1f --- /dev/null +++ b/gateway/app/paymentHandler.go @@ -0,0 +1,211 @@ +package app + +import ( + "bytes" + "context" + "encoding/json" + "net/http" + "os" + "time" + + "github.com/gin-gonic/gin" +) + +type PaymentRecordDTO struct { + Amount int16 + Currency string + Status string + OrderID string + UserID string + Method string + Description string + VPA string + Notes []string +} + +type PaymentMethodDTO struct { + Id string + Method string + Agree string + Comment string +} + +type PaymentHandler struct { +} + +func (ph PaymentHandler) InitiatePayment(c *gin.Context) { + isAdmin := c.Request.Header.Get("admin") + if isAdmin == "true" { + c.JSON(http.StatusUnauthorized, gin.H{}) + c.Abort() + return + } + var paymentDto PaymentRecordDTO + + if err := c.BindJSON(&paymentDto); err != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + + paymentServiceURI := os.Getenv("PAYMENT_SERVICE_URI") + "/pay" + paymentJSON, _ := json.Marshal(paymentDto) + + req, err := http.NewRequest("POST", paymentServiceURI, bytes.NewBuffer(paymentJSON)) + if err != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + + ctx, cancel := context.WithTimeout(req.Context(), 1*time.Minute) + defer cancel() + + req = req.WithContext(ctx) + client := http.DefaultClient + res, err1 := client.Do(req) + if err1 != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err1.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + + if err != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + + c.JSON(200, res.Body) + c.Abort() +} + +func (ph PaymentHandler) AddPaymentMethod(c *gin.Context) { + isAdmin := c.Request.Header.Get("admin") + if isAdmin == "true" { + c.JSON(http.StatusUnauthorized, gin.H{}) + c.Abort() + return + } + var paymentDto PaymentMethodDTO + + if err := c.BindJSON(&paymentDto); err != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + + paymentServiceURI := os.Getenv("PAYMENT_SERVICE_URI") + "/pay/paymentMethods" + paymentJSON, _ := json.Marshal(paymentDto) + + req, err := http.NewRequest("POST", paymentServiceURI, bytes.NewBuffer(paymentJSON)) + if err != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + + ctx, cancel := context.WithTimeout(req.Context(), 1*time.Minute) + defer cancel() + + req = req.WithContext(ctx) + client := http.DefaultClient + res, err1 := client.Do(req) + if err1 != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err1.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + + if err != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + + c.JSON(200, res.Body) + c.Abort() +} + +func (ph PaymentHandler) GetPaymentMethod(c *gin.Context) { + isAdmin := c.Request.Header.Get("admin") + if isAdmin == "true" { + c.JSON(http.StatusUnauthorized, gin.H{}) + c.Abort() + return + } + + paymentServiceURI := os.Getenv("PAYMENT_SERVICE_URI") + "/pay/paymentMethods/" + c.Param("userId") + + req, err := http.NewRequest("GET", paymentServiceURI, nil) + if err != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + + ctx, cancel := context.WithTimeout(req.Context(), 1*time.Minute) + defer cancel() + + req = req.WithContext(ctx) + client := http.DefaultClient + res, err1 := client.Do(req) + if err1 != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err1.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + + if err != nil { + responseDto := ResponseDTO{ + Status: http.StatusBadRequest, + Message: err.Error(), + } + c.JSON(responseDto.Status, responseDto) + c.Abort() + return + } + + c.JSON(200, res.Body) + c.Abort() +} diff --git a/gateway/app/router.go b/gateway/app/router.go index 1e0a699..4d270d9 100644 --- a/gateway/app/router.go +++ b/gateway/app/router.go @@ -72,13 +72,22 @@ func RegisterProductAdminRoutes() { products.GET("/:id", ValidateAuthToken(), productAdminHandler.GetProductByID) products.PUT("/:id", ValidateAuthToken(), productAdminHandler.UpdateProductByID) products.DELETE("/:id", ValidateAuthToken(), productAdminHandler.DeleteProductByID) - + search := products.Group("/search") search.GET("/category/:categoryid", ValidateAuthToken(), productAdminHandler.SearchByCategoryID) search.GET("/manufacturer/:id", ValidateAuthToken(), productAdminHandler.SearchByManufacturerID) search.GET("/keyword/:keyword", ValidateAuthToken(), productAdminHandler.SearchByKeyword) } +func RegisterPaymentRoutes() { + paymentHandler := PaymentHandler{} + payment := v1.Group("/pay") + + payment.POST("/", ValidateAuthToken(), paymentHandler.InitiatePayment) + payment.POST("/paymentMethod", ValidateAuthToken(), paymentHandler.AddPaymentMethod) + payment.GET("/paymentMethod/:id", ValidateAuthToken(), paymentHandler.GetPaymentMethod) +} + func RegisterProductFrontStoreRoutes() { // productFrontStoreHandler := productFrontStoreHandler{} // products := v1.Group("/products")