Skip to content

Commit

Permalink
link service: refactoring
Browse files Browse the repository at this point in the history
Signed-off-by: Login Victor <[email protected]>
  • Loading branch information
batazor committed Aug 29, 2021
1 parent bcc9878 commit 59dd231
Show file tree
Hide file tree
Showing 35 changed files with 406 additions and 271 deletions.
6 changes: 0 additions & 6 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -352,8 +352,6 @@ github.com/gin-gonic/gin v1.4.0/go.mod h1:OW2EZn3DO8Ln9oIKOvM++LBO+5UPHJJDH72/q/
github.com/globalsign/mgo v0.0.0-20180905125535-1ca0a4f7cbcb/go.mod h1:xkRDCp4j0OGD1HRkm4kmhM+pmpv3AKq5SU7GMg4oO/Q=
github.com/globalsign/mgo v0.0.0-20181015135952-eeefdecb41b8/go.mod h1:xkRDCp4j0OGD1HRkm4kmhM+pmpv3AKq5SU7GMg4oO/Q=
github.com/go-check/check v0.0.0-20180628173108-788fd7840127/go.mod h1:9ES+weclKsC9YodN5RgxqK/VD9HM9JsCSh7rNhMZE98=
github.com/go-chi/chi/v5 v5.0.3 h1:khYQBdPivkYG1s1TAzDQG1f6eX4kD2TItYVZexL5rS4=
github.com/go-chi/chi/v5 v5.0.3/go.mod h1:DslCQbL2OYiznFReuXYUmQ2hGd1aDpCnlMNITLSKoi8=
github.com/go-chi/chi/v5 v5.0.4 h1:5e494iHzsYBiyXQAHHuI4tyJS9M3V84OuX3ufIIGHFo=
github.com/go-chi/chi/v5 v5.0.4/go.mod h1:DslCQbL2OYiznFReuXYUmQ2hGd1aDpCnlMNITLSKoi8=
github.com/go-chi/cors v1.2.0 h1:tV1g1XENQ8ku4Bq3K9ub2AtgG+p16SmzeMSGTwrOKdE=
Expand Down Expand Up @@ -1848,10 +1846,6 @@ google.golang.org/genproto v0.0.0-20210713002101-d411969a0d9a/go.mod h1:AxrInvYm
google.golang.org/genproto v0.0.0-20210716133855-ce7ef5c701ea/go.mod h1:AxrInvYm1dci+enl5hChSFPOmmUF1+uAa/UsgNRWd7k=
google.golang.org/genproto v0.0.0-20210728212813-7823e685a01f/go.mod h1:ob2IJxKrgPT52GcgX759i1sleT07tiKowYBGbczaW48=
google.golang.org/genproto v0.0.0-20210805201207-89edb61ffb67/go.mod h1:ob2IJxKrgPT52GcgX759i1sleT07tiKowYBGbczaW48=
google.golang.org/genproto v0.0.0-20210825212027-de86158e7fda h1:iT5uhT54PtbqUsWddv/nnEWdE5e/MTr+Nv3vjxlBP1A=
google.golang.org/genproto v0.0.0-20210825212027-de86158e7fda/go.mod h1:eFjDcFEctNawg4eG61bRv87N7iHBWyVhJu7u1kqDUXY=
google.golang.org/genproto v0.0.0-20210827211047-25e5f791fe06 h1:Ogdiaj9EMVKYHnDsESxwlTr/k5eqCdwoQVJEcdg0NbE=
google.golang.org/genproto v0.0.0-20210827211047-25e5f791fe06/go.mod h1:eFjDcFEctNawg4eG61bRv87N7iHBWyVhJu7u1kqDUXY=
google.golang.org/genproto v0.0.0-20210828152312-66f60bf46e71 h1:z+ErRPu0+KS02Td3fOAgdX+lnPDh/VyaABEJPD4JRQs=
google.golang.org/genproto v0.0.0-20210828152312-66f60bf46e71/go.mod h1:eFjDcFEctNawg4eG61bRv87N7iHBWyVhJu7u1kqDUXY=
google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c=
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ func Routes(
}

r.Get("/link/{hash}", h.GetByCQRS)
r.Get("/links", h.GetByAllCQRS)

return r
}
Expand Down Expand Up @@ -75,3 +76,35 @@ func (h *Handler) GetByCQRS(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
_, _ = w.Write(res) // nolint errcheck
}

// GetByAllCQRS ...
func (h *Handler) GetByAllCQRS(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Content-type", "application/json")

// inject spanId in response header
w.Header().Add("span-id", helpers.RegisterSpan(r.Context()))

var search = r.URL.Query().Get("search")
response, err := h.LinkQueryServiceClient.List(r.Context(), &link_cqrs.ListRequest{Filter: search})
var errorLink *v1.NotFoundError
if errors.As(err, &errorLink) {
w.WriteHeader(http.StatusNotFound)
_, _ = w.Write([]byte(`{"error": "` + err.Error() + `"}`)) // nolint errcheck
return
}
if err != nil {
w.WriteHeader(http.StatusBadRequest)
_, _ = w.Write([]byte(`{"error": "` + err.Error() + `"}`)) // nolint errcheck
return
}

res, err := jsonpb.Marshal(response.Links)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
_, _ = w.Write([]byte(`{"error": "` + err.Error() + `"}`)) // nolint errcheck
return
}

w.WriteHeader(http.StatusOK)
_, _ = w.Write(res) // nolint errcheck
}
12 changes: 6 additions & 6 deletions internal/services/api/application/http-chi/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ func (api *API) Run(
r := chi.NewRouter()

// CORS
cors := cors.New(cors.Options{
corsPolicy := cors.New(cors.Options{
AllowedOrigins: []string{"*"},
AllowedMethods: []string{"GET", "POST", "DELETE", "OPTIONS"},
AllowedHeaders: []string{"Accept", "Authorization", "Content-Type", "X-CSRF-Token"},
Expand All @@ -58,7 +58,7 @@ func (api *API) Run(
//Debug: true,
})

r.Use(cors.Handler)
r.Use(corsPolicy.Handler)
r.Use(render.SetContentType(render.ContentTypeJSON))

// A good base middleware stack
Expand All @@ -85,10 +85,10 @@ func (api *API) Run(
Addr: fmt.Sprintf(":%d", config.Port),
Handler: r,

ReadTimeout: 1 * time.Second, // the maximum duration for reading the entire request, including the body
WriteTimeout: (config.Timeout + 30*time.Second), // the maximum duration before timing out writes of the response
IdleTimeout: 30 * time.Second, // the maximum amount of time to wait for the next request when keep-alive is enabled
ReadHeaderTimeout: 2 * time.Second, // the amount of time allowed to read request headers
ReadTimeout: 1 * time.Second, // the maximum duration for reading the entire request, including the body
WriteTimeout: config.Timeout + 30*time.Second, // the maximum duration before timing out writes of the response
IdleTimeout: 30 * time.Second, // the maximum amount of time to wait for the next request when keep-alive is enabled
ReadHeaderTimeout: 2 * time.Second, // the amount of time allowed to read request headers
}

// start HTTP-server
Expand Down
14 changes: 1 addition & 13 deletions internal/services/link/application/link/link.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,6 @@ package link

import (
"context"
"encoding/json"
"errors"
"fmt"

"google.golang.org/protobuf/proto"
Expand Down Expand Up @@ -107,17 +105,7 @@ func (s *Service) Get(ctx context.Context, hash string) (*v1.Link, error) {
return resp, nil
}

func (s *Service) List(ctx context.Context, in string) (*v1.Links, error) {
// Parse args
filter := queryStore.Filter{}

if in != "" {
errJsonUnmarshal := json.Unmarshal([]byte(in), &filter)
if errJsonUnmarshal != nil {
return nil, errors.New("error parse payload as string")
}
}

func (s *Service) List(ctx context.Context, filter queryStore.Filter) (*v1.Links, error) {
const (
SAGA_NAME = "LIST_LINK"
SAGA_STEP_STORE_LIST = "SAGA_STEP_STORE_LIST"
Expand Down
52 changes: 47 additions & 5 deletions internal/services/link/application/link_cqrs/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,9 @@ import (

"github.com/batazor/shortlink/internal/pkg/logger"
"github.com/batazor/shortlink/internal/pkg/logger/field"
v1 "github.com/batazor/shortlink/internal/services/link/domain/link/v1"
v12 "github.com/batazor/shortlink/internal/services/link/domain/link_cqrs/v1"
link "github.com/batazor/shortlink/internal/services/link/domain/link/v1"
domain "github.com/batazor/shortlink/internal/services/link/domain/link_cqrs/v1"
"github.com/batazor/shortlink/internal/services/link/infrastructure/store/crud/query"
"github.com/batazor/shortlink/pkg/saga"
)

Expand All @@ -25,13 +26,13 @@ func errorHelper(ctx context.Context, logger logger.Logger, errs []error) error
return nil
}

func (s *Service) Get(ctx context.Context, hash string) (*v12.LinkView, error) {
func (s *Service) Get(ctx context.Context, hash string) (*domain.LinkView, error) {
const (
SAGA_NAME = "GET_LINK_CQRS"
SAGA_STEP_STORE_GET = "SAGA_STEP_STORE_GET_CQRS"
)

resp := &v12.LinkView{}
resp := &domain.LinkView{}

// create a new saga for get link by hash
sagaGetLink, errs := saga.New(SAGA_NAME, saga.Logger(s.logger)).
Expand Down Expand Up @@ -60,7 +61,48 @@ func (s *Service) Get(ctx context.Context, hash string) (*v12.LinkView, error) {
}

if resp == nil {
return nil, &v1.NotFoundError{Link: &v1.Link{Hash: hash}, Err: fmt.Errorf("Not found links")}
return nil, &link.NotFoundError{Link: &link.Link{Hash: hash}, Err: fmt.Errorf("Not found links")}
}

return resp, nil
}

func (s *Service) List(ctx context.Context, filter *query.Filter) (*domain.LinksView, error) {
const (
SAGA_NAME = "GET_LINKS_CQRS"
SAGA_STEP_STORE_GET = "SAGA_STEP_STORE_GET_CQRS"
)

resp := &domain.LinksView{}

// create a new saga for get link by hash
sagaGetLink, errs := saga.New(SAGA_NAME, saga.Logger(s.logger)).
WithContext(ctx).
Build()
if err := errorHelper(ctx, s.logger, errs); err != nil {
return nil, err
}

// add step: get link from store
_, errs = sagaGetLink.AddStep(SAGA_STEP_STORE_GET).
Then(func(ctx context.Context) error {
var err error
resp, err = s.queryStore.List(ctx, filter)
return err
}).
Build()
if err := errorHelper(ctx, s.logger, errs); err != nil {
return nil, err
}

// Run saga
err := sagaGetLink.Play(nil)
if err != nil {
return nil, err
}

if resp == nil {
return nil, &link.NotFoundError{Link: &link.Link{Hash: ""}, Err: fmt.Errorf("Not found links")}
}

return resp, nil
Expand Down
14 changes: 6 additions & 8 deletions internal/services/link/di/di.go
Original file line number Diff line number Diff line change
Expand Up @@ -97,24 +97,22 @@ func NewLinkStore(ctx context.Context, logger logger.Logger, db *db.Store, cache
return linkStore, nil
}

func NewCQSLinkStore(ctx context.Context, logger logger.Logger, db *db.Store) (*cqs.Store, error) {
store := &cqs.Store{}
cqsStore, err := store.Use(ctx, logger, db)
func NewCQSLinkStore(ctx context.Context, logger logger.Logger, db *db.Store, cache *cache.Cache) (*cqs.Store, error) {
store, err := cqs.New(ctx, logger, db, cache)
if err != nil {
return nil, err
}

return cqsStore, nil
return store, nil
}

func NewQueryLinkStore(ctx context.Context, logger logger.Logger, db *db.Store) (*query.Store, error) {
store := &query.Store{}
queryStore, err := store.Use(ctx, logger, db)
func NewQueryLinkStore(ctx context.Context, logger logger.Logger, db *db.Store, cache *cache.Cache) (*query.Store, error) {
store, err := query.New(ctx, logger, db, cache)
if err != nil {
return nil, err
}

return queryStore, nil
return store, nil
}

func NewLinkApplication(logger logger.Logger, mq v1.MQ, metadataService metadata_rpc.MetadataServiceClient, store *crud.Store) (*link.Service, error) {
Expand Down
18 changes: 8 additions & 10 deletions internal/services/link/di/wire_gen.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

28 changes: 14 additions & 14 deletions internal/services/link/domain/link_cqrs/v1/link.pb.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion internal/services/link/domain/link_cqrs/v1/link.proto
Original file line number Diff line number Diff line change
Expand Up @@ -26,5 +26,5 @@ message LinkView {
}

message LinksView {
repeated LinkView link = 1;
repeated LinkView links = 1;
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import (

"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"

queryStore "github.com/batazor/shortlink/internal/services/link/infrastructure/store/crud/query"
)

func (l *Link) Get(ctx context.Context, in *GetRequest) (*GetResponse, error) {
Expand All @@ -17,3 +19,19 @@ func (l *Link) Get(ctx context.Context, in *GetRequest) (*GetResponse, error) {
Link: resp,
}, nil
}

func (l *Link) List(ctx context.Context, in *ListRequest) (*ListResponse, error) {
// Parse args
filter := queryStore.Filter{
Search: &queryStore.StringFilterInput{Contains: &in.Filter},
}

resp, err := l.service.List(ctx, &filter)
if err != nil {
return nil, status.Error(codes.InvalidArgument, err.Error())
}

return &ListResponse{
Links: resp,
}, nil
}
Loading

0 comments on commit 59dd231

Please sign in to comment.