Skip to content

Commit

Permalink
Merge pull request #7 from noobj/lazy_binding_and_better_resolve
Browse files Browse the repository at this point in the history
DI apply Lazy Binding in middleware
  • Loading branch information
noobj committed Feb 7, 2023
2 parents f31367a + 588809e commit 55e7fc4
Show file tree
Hide file tree
Showing 30 changed files with 349 additions and 235 deletions.
15 changes: 12 additions & 3 deletions .github/workflows/go.yml
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ jobs:
env:
COVERALLS_TOKEN: ${{ secrets.COVERALLS }}
run: goveralls -coverprofile=coverprofile.out

- name: Set flag to failed
if: failure()
id: set-flag
Expand All @@ -57,10 +57,19 @@ jobs:
uses: actions/setup-go@v3
with:
go-version: 1.18


- name: Install tools
run: |
go get github.com/golang/mock/mockgen@v1.6.0
go get go.mongodb.org/mongo-driver/x/mongo/driver/ocsp@v1.9.1
go install github.com/golang/mock/mockgen
- name: Generate Mocks
run: go generate -x ./...

- name: Build
run: go build -v ./...

- name: Set flag to failed
if: failure()
id: set-flag
Expand Down
16 changes: 8 additions & 8 deletions cmd/ahorro/fetchentries/fetchentries_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,8 @@ import (

"github.com/aws/aws-lambda-go/events"
"github.com/golang/mock/gomock"
"github.com/golobby/container/v3"
main "github.com/noobj/go-serverless-services/cmd/ahorro/fetchentries"
"github.com/noobj/go-serverless-services/internal/helpers/helper"
"github.com/noobj/go-serverless-services/internal/repositories"
UserRepository "github.com/noobj/go-serverless-services/internal/repositories/ahorro/user"
. "github.com/noobj/go-serverless-services/internal/repositories/mocks"
. "github.com/onsi/ginkgo/v2"
Expand Down Expand Up @@ -70,19 +68,21 @@ var fakeData = []bson.M{
var _ = Describe("Fetchentries", func() {
var fakeRequest events.APIGatewayV2HTTPRequest
var ctx context.Context
invoker := main.Invoker{}

BeforeEach(func() {
ctrl := gomock.NewController(GinkgoT())
m := NewMockIRepository(ctrl)

if err := helper.BindIocForTesting(m, &invoker); err != nil {
panic(err.Error())
}
ctx = context.WithValue(context.Background(), helper.ContextKeyUser, UserRepository.User{
Id: fakeObjId,
Account: "jjj",
Password: "123456",
})

container.Singleton(func() repositories.IRepository {
return m
})
fakeRequest.QueryStringParameters = make(map[string]string)
fakeRequest.QueryStringParameters["timeStart"] = "2022-01-01"
fakeRequest.QueryStringParameters["timeEnd"] = "2022-01-31"
Expand All @@ -94,22 +94,22 @@ var _ = Describe("Fetchentries", func() {
Context("when handler return expected json response", func() {
It("should pass", func() {
expectedRes := "{\"categories\":[{\"_id\":\"62badc82d420270009a51019\",\"sum\":110,\"percentage\":\"0.55\",\"name\":\"Food\",\"entries\":[{\"_id\":\"62badc82d420270009a51019\",\"amount\":110,\"date\":\"2022-01-05\",\"descr\":\"fuck\"}],\"color\":\"#a4e56c\"},{\"_id\":\"62badc82d420270009a51019\",\"sum\":90,\"percentage\":\"0.45\",\"name\":\"Abc\",\"entries\":[{\"_id\":\"62badc82d420270009a51019\",\"amount\":90,\"date\":\"2022-01-05\",\"descr\":\"fuck\"}],\"color\":\"#a4e51c\"}],\"total\":200}"
res, err := main.Handler(ctx, fakeRequest)
res, err := invoker.Invoke(ctx, fakeRequest)
fmt.Printf("%+v", res.Body)
Expect(res.Body).To(Equal(expectedRes))
Expect(err).To(BeNil())
})

It("should failed with wrong query string format", func() {
res, err := main.Handler(ctx, events.APIGatewayV2HTTPRequest{})
res, err := invoker.Invoke(ctx, events.APIGatewayV2HTTPRequest{})
Expect(res.Body).To(Equal("request query error"))
Expect(res.StatusCode).To(Equal(400))
Expect(err).To(BeNil())
})

It("should failed for not logining in", func() {
ctx = context.TODO()
res, err := main.Handler(ctx, fakeRequest)
res, err := invoker.Invoke(ctx, fakeRequest)
Expect(res.Body).To(Equal("please login in"))
Expect(res.StatusCode).To(Equal(401))
Expect(err).To(BeNil())
Expand Down
27 changes: 12 additions & 15 deletions cmd/ahorro/fetchentries/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,11 @@ import (

"github.com/aws/aws-lambda-go/events"
"github.com/aws/aws-lambda-go/lambda"
"github.com/golobby/container/v3"
"github.com/noobj/go-serverless-services/internal/helpers/helper"
bindioc "github.com/noobj/go-serverless-services/internal/middleware/bind-ioc"
jwtMiddleWare "github.com/noobj/go-serverless-services/internal/middleware/jwt_auth"
"github.com/noobj/go-serverless-services/internal/repositories"
AhorroRepository "github.com/noobj/go-serverless-services/internal/repositories/ahorro"
"github.com/noobj/go-serverless-services/internal/mongodb"
EntryRepository "github.com/noobj/go-serverless-services/internal/repositories/ahorro/entry"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
)
Expand All @@ -28,7 +28,7 @@ type Entry struct {
type AggregateResult struct {
Entries []Entry
Sum float32
Category []AhorroRepository.Category
Category []EntryRepository.Category
}

type CategoryEntriesBundle struct {
Expand All @@ -46,7 +46,11 @@ func checkTimeFormat(format string, timeString string) bool {
return err == nil
}

func Handler(ctx context.Context, request events.APIGatewayV2HTTPRequest) (events.APIGatewayProxyResponse, error) {
type Invoker struct {
entryRepository EntryRepository.EntryRepository `container:"type"`
}

func (this Invoker) Invoke(ctx context.Context, request events.APIGatewayV2HTTPRequest) (events.APIGatewayProxyResponse, error) {
user, ok := helper.GetUserFromContext(ctx)
if !ok {
return events.APIGatewayProxyResponse{Body: "please login in", StatusCode: 401}, nil
Expand Down Expand Up @@ -78,8 +82,6 @@ func Handler(ctx context.Context, request events.APIGatewayV2HTTPRequest) (event
// excludeCondition = append(excludeCondition, condition)
// }
// }
var entryRepository repositories.IRepository
container.Resolve(&entryRepository)

matchStage := bson.D{{Key: "$match", Value: bson.D{
{Key: "$expr", Value: bson.D{
Expand Down Expand Up @@ -128,7 +130,7 @@ func Handler(ctx context.Context, request events.APIGatewayV2HTTPRequest) (event
},
}}

repoResults := entryRepository.Aggregate([]bson.D{matchStage, sortStage, groupStage, sortSumStage, lookupStage})
repoResults := this.entryRepository.Aggregate([]bson.D{matchStage, sortStage, groupStage, sortSumStage, lookupStage})
var categories []CategoryEntriesBundle
total := float32(0.0)
for _, repoResult := range repoResults {
Expand Down Expand Up @@ -170,12 +172,7 @@ func Handler(ctx context.Context, request events.APIGatewayV2HTTPRequest) (event
}

func main() {
entryRepo := AhorroRepository.New()
defer entryRepo.Disconnect()()

container.Singleton(func() repositories.IRepository {
return entryRepo
})
defer mongodb.Disconnect()()

lambda.Start(jwtMiddleWare.Auth(Handler))
lambda.Start(jwtMiddleWare.Handle(bindioc.Handle[events.APIGatewayV2HTTPRequest, events.APIGatewayProxyResponse](&Invoker{})))
}
18 changes: 7 additions & 11 deletions cmd/ahorro/login/login_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,7 @@ import (
"go.mongodb.org/mongo-driver/mongo"

"github.com/golang/mock/gomock"
"github.com/golobby/container/v3"
"github.com/noobj/go-serverless-services/internal/repositories"
"github.com/noobj/go-serverless-services/internal/helpers/helper"
mocks "github.com/noobj/go-serverless-services/internal/repositories/mocks"
)

Expand All @@ -28,6 +27,7 @@ var fakeUserDoc = bson.M{"_id": fakeObjId, "account": "jjj", "password": "$2b$10

var _ = Describe("Login", func() {
var fakeRequest events.APIGatewayProxyRequest
invoker := main.Invoker{}

if err := godotenv.Load("../../../.env.example"); err != nil {
log.Println("No .env file found", err)
Expand All @@ -39,13 +39,9 @@ var _ = Describe("Login", func() {

ctrl := gomock.NewController(GinkgoT())
m := mocks.NewMockIRepository(ctrl)

container.NamedSingleton("UserRepo", func() repositories.IRepository {
return m
})
container.NamedSingleton("LoginInfoRepo", func() repositories.IRepository {
return m
})
if err := helper.BindIocForTesting(m, &invoker); err != nil {
panic(err.Error())
}

fakeSingleResult := mongo.NewSingleResultFromDocument(fakeUserDoc, nil, nil)
fakeInsertOneResult := &mongo.InsertOneResult{InsertedID: 123}
Expand All @@ -67,7 +63,7 @@ var _ = Describe("Login", func() {
mw.Close()
fakeRequest.Body = buf.String()

res, err := main.Handler(context.TODO(), fakeRequest)
res, err := invoker.Invoke(context.TODO(), fakeRequest)

header := res.Cookies
Expect(err).To(BeNil())
Expand All @@ -86,7 +82,7 @@ var _ = Describe("Login", func() {
mw.Close()
fakeRequest.Body = buf.String()

res, err := main.Handler(context.TODO(), fakeRequest)
res, err := invoker.Invoke(context.TODO(), fakeRequest)
Expect(err).To(BeNil())
Expect(res.StatusCode).To(Equal(statusCode))
Expect(res.Body).Should(Equal(body))
Expand Down
36 changes: 14 additions & 22 deletions cmd/ahorro/login/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,10 @@ import (

"github.com/aws/aws-lambda-go/events"
"github.com/aws/aws-lambda-go/lambda"
"github.com/golobby/container/v3"
"github.com/noobj/go-serverless-services/internal/config"
"github.com/noobj/go-serverless-services/internal/helpers/helper"
"github.com/noobj/go-serverless-services/internal/repositories"
bindioc "github.com/noobj/go-serverless-services/internal/middleware/bind-ioc"
"github.com/noobj/go-serverless-services/internal/mongodb"
LoginInfoRepository "github.com/noobj/go-serverless-services/internal/repositories/ahorro/logininfo"
UserRepository "github.com/noobj/go-serverless-services/internal/repositories/ahorro/user"
"go.mongodb.org/mongo-driver/bson"
Expand All @@ -25,19 +25,21 @@ type LoginDto struct {
Password string
}

func insertNewRefreshTokenIntoLoginInfo(userId primitive.ObjectID, refreshToken string) {
func (this Invoker) insertNewRefreshTokenIntoLoginInfo(userId primitive.ObjectID, refreshToken string) {
loginInfo := LoginInfoRepository.LoginInfo{
User: userId,
RefreshToken: refreshToken,
CreatedAt: primitive.NewDateTimeFromTime(time.Now()),
}
var loginInfoRepository repositories.IRepository
container.NamedResolve(&loginInfoRepository, "LoginInfoRepo")
loginInfoRepository.InsertOne(context.TODO(), loginInfo)
this.loginInfoRepository.InsertOne(context.TODO(), loginInfo)
}

func Handler(ctx context.Context, request events.APIGatewayProxyRequest) (events.APIGatewayV2HTTPResponse, error) {
var userRepository repositories.IRepository
type Invoker struct {
userRepository UserRepository.UserRepository `container:"type"`
loginInfoRepository LoginInfoRepository.LoginInfoRepository `container:"type"`
}

func (this Invoker) Invoke(ctx context.Context, request events.APIGatewayProxyRequest) (events.APIGatewayV2HTTPResponse, error) {
var requestBody LoginDto

formData, err := helper.ParseMultipartForm(request.Headers["content-type"], strings.NewReader(request.Body), request.IsBase64Encoded)
Expand All @@ -51,10 +53,8 @@ func Handler(ctx context.Context, request events.APIGatewayProxyRequest) (events
return events.APIGatewayV2HTTPResponse{Body: "request body error", StatusCode: 400}, nil
}

container.NamedResolve(&userRepository, "UserRepo")

var user UserRepository.User
err = userRepository.FindOne(context.TODO(), bson.M{"account": requestBody.Account}).Decode(&user)
err = this.userRepository.FindOne(context.TODO(), bson.M{"account": requestBody.Account}).Decode(&user)
if err != nil {
log.Println(err)
return events.APIGatewayV2HTTPResponse{Body: "couldn't find the user", StatusCode: 404}, nil
Expand All @@ -78,7 +78,7 @@ func Handler(ctx context.Context, request events.APIGatewayProxyRequest) (events
return events.APIGatewayV2HTTPResponse{Body: "internal error", StatusCode: 500}, nil
}

insertNewRefreshTokenIntoLoginInfo(user.Id, refreshToken)
this.insertNewRefreshTokenIntoLoginInfo(user.Id, refreshToken)

resp := events.APIGatewayV2HTTPResponse{
StatusCode: 200,
Expand Down Expand Up @@ -117,15 +117,7 @@ func Handler(ctx context.Context, request events.APIGatewayProxyRequest) (events
}

func main() {
userRepo := UserRepository.New()
container.NamedSingleton("UserRepo", func() repositories.IRepository {
return userRepo
})

container.NamedSingleton("LoginInfoRepo", func() repositories.IRepository {
return LoginInfoRepository.New()
})
defer userRepo.Disconnect()()
defer mongodb.Disconnect()()

lambda.Start(Handler)
lambda.Start(bindioc.Handle[events.APIGatewayProxyRequest, events.APIGatewayV2HTTPResponse](&Invoker{}))
}
23 changes: 10 additions & 13 deletions cmd/ahorro/refresh/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,10 @@ import (

"github.com/aws/aws-lambda-go/events"
"github.com/aws/aws-lambda-go/lambda"
"github.com/golobby/container/v3"
"github.com/noobj/go-serverless-services/internal/config"
"github.com/noobj/go-serverless-services/internal/helpers/helper"
"github.com/noobj/go-serverless-services/internal/repositories"
bindioc "github.com/noobj/go-serverless-services/internal/middleware/bind-ioc"
"github.com/noobj/go-serverless-services/internal/mongodb"
LoginInfoRepository "github.com/noobj/go-serverless-services/internal/repositories/ahorro/logininfo"
"go.mongodb.org/mongo-driver/bson"
)
Expand All @@ -24,7 +24,11 @@ type LoginDto struct {

var errorHandler = helper.GenerateErrorResponse[events.APIGatewayV2HTTPResponse]

func Handler(ctx context.Context, request events.APIGatewayV2HTTPRequest) (events.APIGatewayV2HTTPResponse, error) {
type Invoker struct {
loginInfoRepository LoginInfoRepository.LoginInfoRepository `container:"type"`
}

func (this *Invoker) Invoke(ctx context.Context, request events.APIGatewayV2HTTPRequest) (events.APIGatewayV2HTTPResponse, error) {
cookiesMap := helper.ParseCookie(request.Cookies)

if _, ok := cookiesMap["refresh_token"]; !ok {
Expand All @@ -43,10 +47,8 @@ func Handler(ctx context.Context, request events.APIGatewayV2HTTPRequest) (event
return errorHandler(401)
}

var loginInfoRepository repositories.IRepository
var loginInfo LoginInfoRepository.LoginInfo
container.NamedResolve(&loginInfoRepository, "LoginInfoRepo")
loginInfoRepository.FindOne(context.TODO(), bson.M{"refreshToken": cookiesMap["refresh_token"]}).Decode(&loginInfo)
this.loginInfoRepository.FindOne(context.TODO(), bson.M{"refreshToken": cookiesMap["refresh_token"]}).Decode(&loginInfo)

if loginInfo.User.Hex() != userId {
fmt.Println("Didn't match or find the loginInfo user", loginInfo.User.Hex(), userId)
Expand Down Expand Up @@ -84,12 +86,7 @@ func Handler(ctx context.Context, request events.APIGatewayV2HTTPRequest) (event
}

func main() {
repo := LoginInfoRepository.New()

container.NamedSingleton("LoginInfoRepo", func() repositories.IRepository {
return repo
})
defer repo.Disconnect()()
defer mongodb.Disconnect()()

lambda.Start(Handler)
lambda.Start(bindioc.Handle[events.APIGatewayV2HTTPRequest, events.APIGatewayV2HTTPResponse](&Invoker{}))
}
15 changes: 7 additions & 8 deletions cmd/ahorro/refresh/refresh_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,9 @@ import (

"github.com/aws/aws-lambda-go/events"
"github.com/golang/mock/gomock"
"github.com/golobby/container/v3"
"github.com/joho/godotenv"
main "github.com/noobj/go-serverless-services/cmd/ahorro/refresh"
"github.com/noobj/go-serverless-services/internal/repositories"
"github.com/noobj/go-serverless-services/internal/helpers/helper"
mockRepo "github.com/noobj/go-serverless-services/internal/repositories/mocks"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
Expand All @@ -27,16 +26,16 @@ var _ = Describe("Refresh", func() {
log.Println("No .env file found", err)
}
var fakeRequest events.APIGatewayV2HTTPRequest
invoker := main.Invoker{}

BeforeEach(func() {
fakeRequest = events.APIGatewayV2HTTPRequest{}

ctrl := gomock.NewController(GinkgoT())
m := mockRepo.NewMockIRepository(ctrl)

container.NamedSingleton("LoginInfoRepo", func() repositories.IRepository {
return m
})
if err := helper.BindIocForTesting(m, &invoker); err != nil {
panic(err.Error())
}

fakeLoginInfoDoc := bson.M{
"_id": fakeObjId,
Expand All @@ -58,7 +57,7 @@ var _ = Describe("Refresh", func() {
"refresh_token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJwYXlsb2FkIjoiNjJiYWRjODJkNDIwMjcwMDA5YTUxMDE5In0.e5WtrcxJx0w2J6xTLzOSa6TJdR33PN9hdiipazfKmiY",
}

res, err := main.Handler(context.TODO(), fakeRequest)
res, err := invoker.Invoke(context.TODO(), fakeRequest)

header := res.Cookies
Expect(err).To(BeNil())
Expand All @@ -74,7 +73,7 @@ var _ = Describe("Refresh", func() {
tokenString,
}

res, err := main.Handler(context.TODO(), fakeRequest)
res, err := invoker.Invoke(context.TODO(), fakeRequest)
Expect(err).To(BeNil())
Expect(res.StatusCode).To(Equal(401))
},
Expand Down

0 comments on commit 55e7fc4

Please sign in to comment.