From 29dd04e5eeba1982d40c7abee878ba5111b7d27e Mon Sep 17 00:00:00 2001 From: alishazaee Date: Sat, 16 Nov 2024 01:52:10 +0330 Subject: [PATCH] feat(source): implement source repository for new event --- cmd/source/main.go | 32 +++++--- config.yml | 1 - go.mod | 5 +- go.sum | 1 + .../delivery/httpserver/eventhandler/event.go | 28 +++++++ .../httpserver/eventhandler/handler.go | 18 +++++ .../delivery/httpserver/eventhandler/route.go | 12 +++ source/delivery/middlewares/writekey.go | 43 ++++++++++ source/params/event.go | 20 +++++ .../redis/rediswritekey/writekey.go | 29 ++++--- source/repository/scylladb/db.go | 81 +++++++++++++++++++ source/repository/scylladb/event/create.go | 48 +++++++++++ source/repository/scylladb/event/repo.go | 17 ++++ .../migrations/1_create_events_table.down.sql | 2 +- .../migrations/1_create_events_table.up.sql | 23 +++--- source/service/event/service.go | 43 ++++++++++ source/service/writekey/service.go | 1 - source/service/writekey/service_test.go | 16 ---- .../eventvalidator/eventvalidator/create.go | 20 +++++ .../eventvalidator/validator.go | 17 ++++ 20 files changed, 406 insertions(+), 51 deletions(-) create mode 100644 source/delivery/httpserver/eventhandler/event.go create mode 100644 source/delivery/httpserver/eventhandler/handler.go create mode 100644 source/delivery/httpserver/eventhandler/route.go create mode 100644 source/delivery/middlewares/writekey.go create mode 100644 source/params/event.go create mode 100644 source/repository/scylladb/db.go create mode 100644 source/repository/scylladb/event/create.go create mode 100644 source/repository/scylladb/event/repo.go create mode 100644 source/service/event/service.go delete mode 100644 source/service/writekey/service_test.go create mode 100644 source/validator/eventvalidator/eventvalidator/create.go create mode 100644 source/validator/eventvalidator/eventvalidator/validator.go diff --git a/cmd/source/main.go b/cmd/source/main.go index dd0a8fce..ef502ab8 100644 --- a/cmd/source/main.go +++ b/cmd/source/main.go @@ -2,6 +2,7 @@ package main import ( "context" + "github.com/ormushq/ormus/source/validator/eventvalidator/eventvalidator" "log/slog" "os" "os/signal" @@ -14,9 +15,13 @@ import ( "github.com/ormushq/ormus/pkg/channel" "github.com/ormushq/ormus/pkg/channel/adapter/rabbitmqchannel" "github.com/ormushq/ormus/source/delivery/httpserver" + "github.com/ormushq/ormus/source/delivery/httpserver/eventhandler" "github.com/ormushq/ormus/source/delivery/httpserver/statushandler" sourceevent "github.com/ormushq/ormus/source/eventhandler" writekeyrepo "github.com/ormushq/ormus/source/repository/redis/rediswritekey" + "github.com/ormushq/ormus/source/repository/scylladb" + eventrepo "github.com/ormushq/ormus/source/repository/scylladb/event" + eventsvc "github.com/ormushq/ormus/source/service/event" "github.com/ormushq/ormus/source/service/writekey" ) @@ -62,16 +67,13 @@ func main() { // use slog as default logger. slog.SetDefault(l) - handlers := []httpserver.Handler{ - statushandler.New(), - } err := otela.Configure(wg, done, otela.Config{Exporter: otela.ExporterConsole}) if err != nil { panic(err.Error()) } cfg := config.C() - _, Consumer := SetupSourceServices(cfg) + _, Consumer, eventSvc, eventValidator := SetupSourceServices(cfg) Consumer.Consume(context.Background(), cfg.Source.NewSourceEventName, done, wg, Consumer.ProcessNewSourceEvent) //----------------- Setup Tracer -----------------// @@ -87,7 +89,10 @@ func main() { if err != nil { l.Error(err.Error()) } - + handlers := []httpserver.Handler{ + statushandler.New(), + eventhandler.New(eventSvc, eventValidator), + } httpServer := httpserver.New(config.C().Source, handlers) httpServer.Serve() @@ -102,7 +107,7 @@ func main() { wg.Wait() } -func SetupSourceServices(cfg config.Config) (writekey.Service, sourceevent.Consumer) { +func SetupSourceServices(cfg config.Config) (writeKeySvc writekey.Service, eventHandler sourceevent.Consumer, eventSvc eventsvc.Service, eventValidator eventvalidator.Validator) { done := make(chan bool) wg := &sync.WaitGroup{} @@ -118,8 +123,17 @@ func SetupSourceServices(cfg config.Config) (writekey.Service, sourceevent.Consu } writeKeyRepo := writekeyrepo.New(adapter) - writeKeySvc := writekey.New(&writeKeyRepo, cfg.Source) - eventHandler := sourceevent.New(outputAdapter, writeKeySvc) + writeKeySvc = writekey.New(&writeKeyRepo, cfg.Source) + eventHandler = *sourceevent.New(outputAdapter, writeKeySvc) + + DB, err := scylladb.New(cfg.Scylladb) + if err != nil { + panic(err) + } + eventRepo := eventrepo.New(DB) + eventSvc = *eventsvc.New(eventRepo) + + eventValidator = eventvalidator.New(&writeKeyRepo) - return writeKeySvc, *eventHandler + return } diff --git a/config.yml b/config.yml index aca451db..d9f74949 100644 --- a/config.yml +++ b/config.yml @@ -107,4 +107,3 @@ manager: min_retry_delay: 1s max_retry_delay: 10s - diff --git a/go.mod b/go.mod index 87a166ab..5fd7b053 100644 --- a/go.mod +++ b/go.mod @@ -7,10 +7,13 @@ require ( github.com/gocql/gocql v1.6.0 github.com/golang-jwt/jwt/v5 v5.2.1 github.com/golang-migrate/migrate/v4 v4.17.1 + github.com/golang/mock v1.1.1 + github.com/golang/protobuf v1.5.4 github.com/google/uuid v1.6.0 github.com/knadh/koanf v1.5.0 github.com/labstack/echo-jwt/v4 v4.2.0 github.com/labstack/echo/v4 v4.12.0 + github.com/labstack/gommon v0.4.2 github.com/oklog/ulid/v2 v2.1.0 github.com/prometheus/client_golang v1.11.1 github.com/rabbitmq/amqp091-go v1.10.0 @@ -59,7 +62,6 @@ require ( github.com/go-openapi/swag v0.19.15 // indirect github.com/gogo/protobuf v1.3.2 // indirect github.com/golang-jwt/jwt v3.2.2+incompatible // indirect - github.com/golang/protobuf v1.5.4 // indirect github.com/golang/snappy v0.0.4 // indirect github.com/grpc-ecosystem/grpc-gateway/v2 v2.20.0 // indirect github.com/hailocab/go-hostpool v0.0.0-20160125115350-e80d13ce29ed // indirect @@ -67,7 +69,6 @@ require ( github.com/hashicorp/go-multierror v1.1.1 // indirect github.com/inconshreveable/mousetrap v1.1.0 // indirect github.com/josharian/intern v1.0.0 // indirect - github.com/labstack/gommon v0.4.2 // indirect github.com/mailru/easyjson v0.7.7 // indirect github.com/mattn/go-colorable v0.1.13 // indirect github.com/mattn/go-isatty v0.0.20 // indirect diff --git a/go.sum b/go.sum index 98d07eb3..bc190a9c 100644 --- a/go.sum +++ b/go.sum @@ -129,6 +129,7 @@ github.com/golang-jwt/jwt/v5 v5.2.1/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVI github.com/golang-migrate/migrate/v4 v4.17.1 h1:4zQ6iqL6t6AiItphxJctQb3cFqWiSpMnX7wLTPnnYO4= github.com/golang-migrate/migrate/v4 v4.17.1/go.mod h1:m8hinFyWBn0SA4QKHuKh175Pm9wjmxj3S2Mia7dbXzM= github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= +github.com/golang/mock v1.1.1 h1:G5FRp8JnTd7RQH5kemVNlMeyXQAztQ3mOWV95KxsXH8= 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.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= diff --git a/source/delivery/httpserver/eventhandler/event.go b/source/delivery/httpserver/eventhandler/event.go new file mode 100644 index 00000000..7f84f894 --- /dev/null +++ b/source/delivery/httpserver/eventhandler/event.go @@ -0,0 +1,28 @@ +package eventhandler + +import ( + "github.com/labstack/echo/v4" + "github.com/ormushq/ormus/pkg/errmsg" + "github.com/ormushq/ormus/pkg/httpmsg" + "github.com/ormushq/ormus/pkg/httputil" + "github.com/ormushq/ormus/source/params" + "net/http" +) + +func (h Handler) NewEvent(ctx echo.Context) error { + var req params.TrackEventRequest + if err := ctx.Bind(&req); err != nil { + return httputil.NewError(ctx, http.StatusBadRequest, errmsg.ErrBadRequest) + } + resp, err := h.eventSvc.CreateNewEvent(ctx.Request().Context(), req) + + if err != nil { + msg, code := httpmsg.Error(err) + + return ctx.JSON(code, echo.Map{ + "message": msg, + "errors": err, + }) + } + return ctx.JSON(http.StatusCreated, resp) +} diff --git a/source/delivery/httpserver/eventhandler/handler.go b/source/delivery/httpserver/eventhandler/handler.go new file mode 100644 index 00000000..8d208259 --- /dev/null +++ b/source/delivery/httpserver/eventhandler/handler.go @@ -0,0 +1,18 @@ +package eventhandler + +import ( + "github.com/ormushq/ormus/source/service/event" + "github.com/ormushq/ormus/source/validator/eventvalidator/eventvalidator" +) + +type Handler struct { + eventSvc event.Service + eventValidator eventvalidator.Validator +} + +func New(EventSvc event.Service, eventValidator eventvalidator.Validator) Handler { + return Handler{ + eventSvc: EventSvc, + eventValidator: eventValidator, + } +} diff --git a/source/delivery/httpserver/eventhandler/route.go b/source/delivery/httpserver/eventhandler/route.go new file mode 100644 index 00000000..571ec357 --- /dev/null +++ b/source/delivery/httpserver/eventhandler/route.go @@ -0,0 +1,12 @@ +package eventhandler + +import ( + "github.com/labstack/echo/v4" + "github.com/ormushq/ormus/source/delivery/middlewares" +) + +func (h Handler) SetRoutes(e *echo.Echo) { + e.POST("api/source/event/", h.NewEvent, middlewares.WriteKeyMiddleware(h.eventValidator)) + + // TODO - add required routes +} diff --git a/source/delivery/middlewares/writekey.go b/source/delivery/middlewares/writekey.go new file mode 100644 index 00000000..42fb20ae --- /dev/null +++ b/source/delivery/middlewares/writekey.go @@ -0,0 +1,43 @@ +package middlewares + +import ( + "bytes" + "encoding/json" + "github.com/labstack/echo/v4" + "github.com/ormushq/ormus/source/params" + "github.com/ormushq/ormus/source/validator/eventvalidator/eventvalidator" + "io" + "net/http" +) + +func WriteKeyMiddleware(validator eventvalidator.Validator) echo.MiddlewareFunc { + return func(next echo.HandlerFunc) echo.HandlerFunc { + return func(c echo.Context) error { + body, err := io.ReadAll(c.Request().Body) + if err != nil { + return echo.NewHTTPError(http.StatusBadRequest, "Failed to read body") + } + + c.Request().Body = io.NopCloser(bytes.NewReader(body)) + + var req params.TrackEventRequest + if err := json.Unmarshal(body, &req); err != nil { + return echo.NewHTTPError(http.StatusBadRequest, "Failed to unmarshal body") + } + + isValid, err := validator.ValidateWriteKey(c.Request().Context(), req.WriteKey) + if err != nil { + return c.JSON(http.StatusInternalServerError, echo.Map{ + "message": "something went wrong", + }) + } + if !isValid { + return c.JSON(http.StatusForbidden, "the write key is invalid") + } + c.Set("body", req) + + return next(c) + } + } + +} diff --git a/source/params/event.go b/source/params/event.go new file mode 100644 index 00000000..2b829815 --- /dev/null +++ b/source/params/event.go @@ -0,0 +1,20 @@ +package params + +import ( + "time" +) + +type TrackEventRequest struct { + Type string `json:"type" validate:"required"` + Name string `json:"name" validate:"required,min=3,max=255"` + SendAt time.Time `json:"send_at" validate:"required"` + ReceivedAt time.Time `json:"received_at" validate:"required"` + Timestamp time.Time `json:"timestamp" validate:"required"` + Event string `json:"event" validate:"required"` + WriteKey string `json:"write_key" validate:"required"` + Properties map[string]interface{} `json:"properties" validate:"required"` +} + +type TrackEventResponse struct { + Id string `json:"id"` +} diff --git a/source/repository/redis/rediswritekey/writekey.go b/source/repository/redis/rediswritekey/writekey.go index 677ff98a..4b590bae 100644 --- a/source/repository/redis/rediswritekey/writekey.go +++ b/source/repository/redis/rediswritekey/writekey.go @@ -2,7 +2,9 @@ package rediswritekey import ( "context" - "fmt" + "encoding/json" + "errors" + "github.com/redis/go-redis/v9" "time" proto_source "github.com/ormushq/ormus/contract/go/source" @@ -10,8 +12,14 @@ import ( ) func (r *DB) CreateNewWriteKey(ctx context.Context, writeKey *proto_source.NewSourceEvent, expirationTime uint) error { - err := r.adapter.Client().Set(ctx, fmt.Sprintf("%s+%s", writeKey.OwnerId, writeKey.ProjectId), - writeKey.WriteKey, time.Minute*time.Duration(expirationTime)).Err() + v, err := json.Marshal( + map[string]string{"OwnerId": writeKey.OwnerId, "ProjectId": writeKey.ProjectId}, + ) + if err != nil { + return richerror.New("source").WithWrappedError(err).WithKind(richerror.KindUnexpected).WithMessage(err.Error()) + } + err = r.adapter.Client().Set(ctx, writeKey.WriteKey, v, + time.Minute*time.Duration(expirationTime)).Err() if err != nil { return richerror.New("source").WithWrappedError(err).WithKind(richerror.KindUnexpected).WithMessage(err.Error()) } @@ -19,15 +27,14 @@ func (r *DB) CreateNewWriteKey(ctx context.Context, writeKey *proto_source.NewSo return nil } -func (r *DB) GetWriteKey(ctx context.Context, ownerID, projectID string) (*proto_source.NewSourceEvent, error) { - wk, err := r.adapter.Client().Get(ctx, fmt.Sprintf("%s+%s", ownerID, projectID)).Result() +func (r *DB) IsWriteKeyValid(ctx context.Context, writeKey string) (bool, error) { + err := r.adapter.Client().Get(ctx, writeKey).Err() + if errors.Is(err, redis.Nil) { // Use errors.Is to check for redis.Nil + return false, nil + } if err != nil { - return nil, richerror.New("source.repository").WithWrappedError(err).WithKind(richerror.KindUnexpected).WithMessage(err.Error()) + return false, richerror.New("source.repository").WithWrappedError(err).WithKind(richerror.KindUnexpected).WithMessage(err.Error()) } - return &proto_source.NewSourceEvent{ - OwnerId: ownerID, - ProjectId: projectID, - WriteKey: wk, - }, nil + return true, nil } diff --git a/source/repository/scylladb/db.go b/source/repository/scylladb/db.go new file mode 100644 index 00000000..4b494a75 --- /dev/null +++ b/source/repository/scylladb/db.go @@ -0,0 +1,81 @@ +package scylladb + +import ( + "fmt" + "github.com/ormushq/ormus/adapter/scylladb" + "github.com/ormushq/ormus/adapter/scylladb/scyllainitialize" + "github.com/ormushq/ormus/logger" + "github.com/ormushq/ormus/pkg/richerror" + "github.com/scylladb/gocqlx/v2" + "log" +) + +type DB struct { + conn scylladb.SessionxInterface +} + +type Statement struct { + Query string + Values []string +} + +var statements = map[string]gocqlx.Queryx{} + +func New(scylladbConfig scylladb.Config) (*DB, error) { + cfg := scylladb.Config{ + Hosts: scylladbConfig.Hosts, + Consistency: scylladbConfig.Consistency, + Keyspace: scylladbConfig.Keyspace, + TimeoutCluster: scylladbConfig.TimeoutCluster, + NumRetries: scylladbConfig.NumRetries, + MinRetryDelay: scylladbConfig.MinRetryDelay, + MaxRetryDelay: scylladbConfig.MaxRetryDelay, + } + Sconn := scyllainitialize.NewScyllaDBConnection(cfg.Consistency, cfg.Keyspace, cfg.Hosts[0]) + + err := scyllainitialize.CreateKeySpace( + cfg.Consistency, + cfg.Keyspace, + cfg.Hosts..., + ) + if err != nil { + log.Fatal("Failed to create ScyllaDB keyspace:", err) + } + err = scyllainitialize.RunMigrations(Sconn, "./manager/repository/scyllarepo/") + if err != nil { + panic(err) + } + Session, Err := scyllainitialize.GetConnection(Sconn) + if Err != nil { + panic(Err) + } + + return &DB{ + conn: Session, + }, nil +} + +func (d *DB) GetConn() scylladb.SessionxInterface { + return d.conn +} + +func (d *DB) RegisterStatement(states ...Statement) { + for _, stat := range states { + logger.L().Debug(fmt.Sprintf("%+v", stat)) + statements[stat.Query] = d.conn.Query(stat.Query, stat.Values) + } +} + +func (d *DB) GetStatement(state Statement) (gocqlx.Queryx, error) { + if statement, ok := statements[state.Query]; ok { + return statement, nil + } + + return gocqlx.Queryx{}, richerror.New("db.GetStatement").WhitKind(richerror.KindNotFound).WithMessage("statement not found") +} + +func (d *DB) RegisterStatements(states map[string]Statement) { + for _, stat := range states { + d.RegisterStatement(stat) + } +} diff --git a/source/repository/scylladb/event/create.go b/source/repository/scylladb/event/create.go new file mode 100644 index 00000000..b05dc8b1 --- /dev/null +++ b/source/repository/scylladb/event/create.go @@ -0,0 +1,48 @@ +package event + +import ( + "context" + "github.com/google/uuid" + "github.com/ormushq/ormus/event" + "github.com/ormushq/ormus/pkg/errmsg" + "github.com/ormushq/ormus/pkg/richerror" + "github.com/ormushq/ormus/source/repository/scylladb" + "github.com/scylladb/gocqlx/v2/qb" + "time" +) + +func init() { + statements["create"] = scylladb.Statement{ + Query: `INSERT INTO event (id, type, name, send_at, received_at, timestamp, event, write_key, created_at, updated_at, properties) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, + Values: []string{"id", "type", "name", "send_at", "received_at", "timestamp", "event", "write_key", "created_at", "updated_at", "properties"}, + } +} + +func (r Repository) CreateNewEvent(ctx context.Context, evt event.CoreEvent) (string, error) { // Renamed 'R' to 'r' and 'event' to 'evt' + query, err := r.db.GetStatement(statements["create"]) + + if err != nil { + return "", richerror.New("source.repository").WithWrappedError(err).WithKind(richerror.KindUnexpected).WithMessage(errmsg.ErrSomeThingWentWrong) + } + + id := uuid.New().String() + query.BindMap(qb.M{ + "write_key": evt.WriteKey, + "id": id, + "type": evt.Type, + "name": evt.Name, + "send_at": evt.SendAt, + "received_at": evt.ReceivedAt, + "event": evt.Event, + "timestamp": evt.Timestamp, + "created_at": time.Now(), + "updated_at": time.Now(), + "properties": evt.Properties, + }) + + if err := query.Exec(); err != nil { + return "", richerror.New("source.repository").WithWrappedError(err).WithKind(richerror.KindUnexpected).WithMessage(errmsg.ErrSomeThingWentWrong) + } + + return id, nil +} diff --git a/source/repository/scylladb/event/repo.go b/source/repository/scylladb/event/repo.go new file mode 100644 index 00000000..a50f4be7 --- /dev/null +++ b/source/repository/scylladb/event/repo.go @@ -0,0 +1,17 @@ +package event + +import "github.com/ormushq/ormus/source/repository/scylladb" + +type Repository struct { + db *scylladb.DB +} + +var statements = map[string]scylladb.Statement{} + +func New(db *scylladb.DB) *Repository { + db.RegisterStatements(statements) + + return &Repository{ + db: db, + } +} diff --git a/source/repository/scylladb/migrations/1_create_events_table.down.sql b/source/repository/scylladb/migrations/1_create_events_table.down.sql index bfd996dc..3b41a53b 100644 --- a/source/repository/scylladb/migrations/1_create_events_table.down.sql +++ b/source/repository/scylladb/migrations/1_create_events_table.down.sql @@ -1 +1 @@ -DROP TABLE IF EXISTS events; \ No newline at end of file +DROP TABLE IF EXISTS event; \ No newline at end of file diff --git a/source/repository/scylladb/migrations/1_create_events_table.up.sql b/source/repository/scylladb/migrations/1_create_events_table.up.sql index a078b79b..07a2c1c6 100644 --- a/source/repository/scylladb/migrations/1_create_events_table.up.sql +++ b/source/repository/scylladb/migrations/1_create_events_table.up.sql @@ -1,10 +1,13 @@ -CREATE TABLE IF NOT EXISTS events ( - id UUID PRIMARY KEY, - name VARCHAR, - type VARCHAR, - event VARCHAR, - received_at TIMESTAMP, - send_at TIMESTAMP, - created_at TIMESTAMP, - updated_at TIMESTAMP -); \ No newline at end of file +CREATE TABLE event ( + id UUID PRIMARY KEY, + type TEXT, + name TEXT, + properties MAP, + send_at TIMESTAMP, + received_at TIMESTAMP, + timestamp TIMESTAMP, + event TEXT, + write_key TEXT, + created_at TIMESTAMP, + updated_at TIMESTAMP +); diff --git a/source/service/event/service.go b/source/service/event/service.go new file mode 100644 index 00000000..d7fb5999 --- /dev/null +++ b/source/service/event/service.go @@ -0,0 +1,43 @@ +package event + +import ( + "context" + "github.com/ormushq/ormus/event" + "github.com/ormushq/ormus/pkg/errmsg" + "github.com/ormushq/ormus/pkg/richerror" + "github.com/ormushq/ormus/source/params" +) + +type Repository interface { + CreateNewEvent(ctx context.Context, event event.CoreEvent) (string, error) +} + +type Service struct { + eventRepo Repository +} + +func New(eventRepo Repository) *Service { + return &Service{eventRepo: eventRepo} +} + +func (s Service) CreateNewEvent(ctx context.Context, newEvent params.TrackEventRequest) (*params.TrackEventResponse, error) { + e := event.CoreEvent{ + Name: newEvent.Name, + WriteKey: newEvent.Event, + Event: newEvent.Event, + SendAt: newEvent.SendAt, + ReceivedAt: newEvent.ReceivedAt, + Timestamp: newEvent.Timestamp, + Type: event.Type(newEvent.Type), + Properties: (*event.Properties)(&newEvent.Properties), + } + + id, err := s.eventRepo.CreateNewEvent(ctx, e) + if err != nil { + return nil, richerror.New("source.service").WithMessage(errmsg.ErrSomeThingWentWrong).WhitKind(richerror.KindUnexpected).WithWrappedError(err) + } + + return ¶ms.TrackEventResponse{ + Id: id, + }, nil +} diff --git a/source/service/writekey/service.go b/source/service/writekey/service.go index dff7be0a..3418cd11 100644 --- a/source/service/writekey/service.go +++ b/source/service/writekey/service.go @@ -10,7 +10,6 @@ import ( type Repository interface { CreateNewWriteKey(ctx context.Context, writeKey *proto_source.NewSourceEvent, expirationTime uint) error - GetWriteKey(ctx context.Context, ownerID, projectID string) (*proto_source.NewSourceEvent, error) } type Service struct { diff --git a/source/service/writekey/service_test.go b/source/service/writekey/service_test.go deleted file mode 100644 index 61b79d71..00000000 --- a/source/service/writekey/service_test.go +++ /dev/null @@ -1,16 +0,0 @@ -package writekey_test - -import ( - "context" - "fmt" -) - -type mockRepo struct{} - -// TODO - use https://github.com/golang/mock -func (m mockRepo) IsValidWriteKey(ctx context.Context, writeKey string) (bool, error) { - if writeKey == "" { - return false, fmt.Errorf("writekey not found") - } - return true, nil -} diff --git a/source/validator/eventvalidator/eventvalidator/create.go b/source/validator/eventvalidator/eventvalidator/create.go new file mode 100644 index 00000000..2b012cdf --- /dev/null +++ b/source/validator/eventvalidator/eventvalidator/create.go @@ -0,0 +1,20 @@ +package eventvalidator + +import ( + "context" + "github.com/ormushq/ormus/pkg/errmsg" + "github.com/ormushq/ormus/pkg/richerror" +) + +func (v Validator) ValidateWriteKey(ctx context.Context, writeKey string) (bool, error) { + isValid, err := v.repo.IsWriteKeyValid(ctx, writeKey) + if err != nil { + return false, richerror.New("source.service").WithMessage(errmsg.ErrSomeThingWentWrong).WhitKind(richerror.KindUnexpected).WithWrappedError(err) + } + + if isValid { + return true, nil + } + + return false, nil +} diff --git a/source/validator/eventvalidator/eventvalidator/validator.go b/source/validator/eventvalidator/eventvalidator/validator.go new file mode 100644 index 00000000..02e9b66c --- /dev/null +++ b/source/validator/eventvalidator/eventvalidator/validator.go @@ -0,0 +1,17 @@ +package eventvalidator + +import ( + "context" +) + +type Repository interface { + IsWriteKeyValid(ctx context.Context, writeKey string) (bool, error) +} + +type Validator struct { + repo Repository +} + +func New(repo Repository) Validator { + return Validator{repo: repo} +}