diff --git a/config/config.go b/config/config.go index ced4785..5329561 100644 --- a/config/config.go +++ b/config/config.go @@ -22,10 +22,10 @@ func New() *Config { return &Config{ Server: ServerConfig{ Port: getEnv("PORT", "8080"), - ConnectionString: getEnv("CONNECTION_STRING", "test.db"), + ConnectionString: getEnv("CONNECTION_STRING", "host=localhost user=astra_events password=password dbname=astra_events_db port=5432 sslmode=disable TimeZone=Europe/Moscow"), }, MSHosts: MSHosts{ - UsersHost: getEnv("ASTRA-USERS", "http://localhost:8082"), + UsersHost: getEnv("ASTRA-USERS", "http://localhost:8081"), }, } } diff --git a/dev/docker-compose.yaml b/dev/docker-compose.yaml new file mode 100644 index 0000000..2d7e687 --- /dev/null +++ b/dev/docker-compose.yaml @@ -0,0 +1,10 @@ +version: "3.9" +services: + postgres: + image: postgres:13.3 + environment: + POSTGRES_DB: "astra_events_db" + POSTGRES_USER: "astra_events" + POSTGRES_PASSWORD: "password" + ports: + - "5432:5432" \ No newline at end of file diff --git a/go.mod b/go.mod index 5ca5fa1..d672904 100644 --- a/go.mod +++ b/go.mod @@ -4,20 +4,26 @@ go 1.21rc1 require ( github.com/golang-jwt/jwt v3.2.2+incompatible // indirect + github.com/hashicorp/go-set v0.1.13 // indirect + github.com/jackc/pgpassfile v1.0.0 // indirect + github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a // indirect + github.com/jackc/pgx/v5 v5.3.1 // indirect github.com/jinzhu/inflection v1.0.0 // indirect github.com/jinzhu/now v1.1.5 // indirect github.com/labstack/echo/v4 v4.10.2 // indirect github.com/labstack/gommon v0.4.0 // indirect + github.com/lib/pq v1.10.9 // indirect github.com/mattn/go-colorable v0.1.13 // indirect github.com/mattn/go-isatty v0.0.17 // indirect github.com/mattn/go-sqlite3 v1.14.17 // indirect github.com/valyala/bytebufferpool v1.0.0 // indirect github.com/valyala/fasttemplate v1.2.2 // indirect - golang.org/x/crypto v0.6.0 // indirect - golang.org/x/net v0.7.0 // indirect - golang.org/x/sys v0.5.0 // indirect - golang.org/x/text v0.7.0 // indirect + golang.org/x/crypto v0.8.0 // indirect + golang.org/x/net v0.9.0 // indirect + golang.org/x/sys v0.7.0 // indirect + golang.org/x/text v0.9.0 // indirect golang.org/x/time v0.3.0 // indirect + gorm.io/driver/postgres v1.5.2 // indirect gorm.io/driver/sqlite v1.5.2 // indirect gorm.io/gorm v1.25.2 // indirect ) diff --git a/go.sum b/go.sum index 4f6a759..5d4d283 100644 --- a/go.sum +++ b/go.sum @@ -2,6 +2,14 @@ github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSs github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/golang-jwt/jwt v3.2.2+incompatible h1:IfV12K8xAKAnZqdXVzCZ+TOjboZ2keLg81eXfW3O+oY= github.com/golang-jwt/jwt v3.2.2+incompatible/go.mod h1:8pz2t5EyA70fFQQSrl6XZXzqecmYZeUEB8OUGHkxJ+I= +github.com/hashicorp/go-set v0.1.13 h1:k1B5goY3c7OKEzpK+gwAhJexxzAJwDN8kId8YvWrihA= +github.com/hashicorp/go-set v0.1.13/go.mod h1:0/D+R4MFUzJ6XmvjU7liXtznF1eQDxh84GJlhXw+lvo= +github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM= +github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg= +github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a h1:bbPeKD0xmW/Y25WS6cokEszi5g+S0QxI/d45PkRi7Nk= +github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM= +github.com/jackc/pgx/v5 v5.3.1 h1:Fcr8QJ1ZeLi5zsPZqQeUZhNhxfkkKBOgJuYkJHoBOtU= +github.com/jackc/pgx/v5 v5.3.1/go.mod h1:t3JDKnCBlYIc0ewLF0Q7B8MXmoIaBOZj/ic7iHozM/8= github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E= github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc= github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ= @@ -10,6 +18,8 @@ github.com/labstack/echo/v4 v4.10.2 h1:n1jAhnq/elIFTHr1EYpiYtyKgx4RW9ccVgkqByZaN github.com/labstack/echo/v4 v4.10.2/go.mod h1:OEyqf2//K1DFdE57vw2DRgWY0M7s65IVQO2FzvI4J5k= github.com/labstack/gommon v0.4.0 h1:y7cvthEAEbU0yHOf4axH8ZG2NH8knB9iNSoTO8dyIk8= github.com/labstack/gommon v0.4.0/go.mod h1:uW6kP17uPlLJsD3ijUYn3/M5bAxtlZhMI6m3MFxTMTM= +github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw= +github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o= github.com/mattn/go-colorable v0.1.11/go.mod h1:u5H1YNBxpqRaxsYJYSkiCWKzEfiAb1Gb520KVy5xxl4= github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg= @@ -21,6 +31,7 @@ github.com/mattn/go-sqlite3 v1.14.17 h1:mCRHCLDUBXgpKAqIKsaAaAsrAlbkeomtRFKXh2L6 github.com/mattn/go-sqlite3 v1.14.17/go.mod h1:2eHXhiwb8IkHr+BDWZGa96P6+rkvnG63S2DGjv9HUNg= 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.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw= github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc= @@ -29,21 +40,31 @@ github.com/valyala/fasttemplate v1.2.2 h1:lxLXG0uE3Qnshl9QyaK6XJxMXlQZELvChBOCmQ github.com/valyala/fasttemplate v1.2.2/go.mod h1:KHLXt3tVN2HBp8eijSv/kGJopbvo7S+qRAEEKiv+SiQ= golang.org/x/crypto v0.6.0 h1:qfktjS5LUO+fFKeJXZ+ikTRijMmljikvG68fpMMruSc= golang.org/x/crypto v0.6.0/go.mod h1:OFC/31mSvZgRz0V1QTNCzfAI1aIRzbiufJtkMIlEp58= +golang.org/x/crypto v0.8.0 h1:pd9TJtTueMTVQXzk8E2XESSMQDj/U7OUu0PqJqPXQjQ= +golang.org/x/crypto v0.8.0/go.mod h1:mRqEX+O9/h5TFCrQhkgjo2yKi0yYA+9ecGkdQoHrywE= golang.org/x/net v0.7.0 h1:rJrUqqhjsgNp7KqAIc25s9pZnjU7TUcSY7HcVZjdn1g= golang.org/x/net v0.7.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= +golang.org/x/net v0.9.0 h1:aWJ/m6xSmxWBx+V0XRHTlrYrPG56jKsLdTFmsSsCzOM= +golang.org/x/net v0.9.0/go.mod h1:d48xBJpPfHeWQsugry2m+kC02ZBRGRgulfHnEXEuWns= golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20211103235746-7861aae1554b/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.5.0 h1:MUK/U/4lj1t1oPg0HfuXDN/Z1wv31ZJ/YcPiGccS4DU= golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.7.0 h1:3jlCCIQZPdOYu1h8BkNvLz8Kgwtae2cagcG/VamtZRU= +golang.org/x/sys v0.7.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/text v0.7.0 h1:4BRB4x83lYWy72KwLD/qYDuTu7q9PjSagHvijDw7cLo= golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= +golang.org/x/text v0.9.0 h1:2sjJmO8cDvYveuX97RDLsxlyUxLl+GHoLxBiRdHllBE= +golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= golang.org/x/time v0.3.0 h1:rg5rLMjNzMS1RkNLzCG38eapWhnYLFYXDXj2gOlr8j4= golang.org/x/time v0.3.0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gorm.io/driver/postgres v1.5.2 h1:ytTDxxEv+MplXOfFe3Lzm7SjG09fcdb3Z/c056DTBx0= +gorm.io/driver/postgres v1.5.2/go.mod h1:fmpX0m2I1PKuR7mKZiEluwrP3hbs+ps7JIGMUBpCgl8= gorm.io/driver/sqlite v1.5.2 h1:TpQ+/dqCY4uCigCFyrfnrJnrW9zjpelWVoEVNy5qJkc= gorm.io/driver/sqlite v1.5.2/go.mod h1:qxAuCol+2r6PannQDpOP1FP6ag3mKi4esLnB/jHed+4= gorm.io/gorm v1.25.2-0.20230530020048-26663ab9bf55/go.mod h1:L4uxeKpfBml98NYqVqwAdmV1a2nBtAec/cf3fpucW/k= diff --git a/handler/event.go b/handler/event.go index 5e12a4c..821e5e4 100644 --- a/handler/event.go +++ b/handler/event.go @@ -2,7 +2,9 @@ package handler import ( "astra-events/model" + "astra-events/pkg/utils" "astra-events/services" + "github.com/hashicorp/go-set" "github.com/labstack/echo/v4" "net/http" "strconv" @@ -21,16 +23,15 @@ func (h *Handler) CreateEvent(c echo.Context) (err error) { return c.NoContent(http.StatusBadRequest) } - // TODO: Add gorutine - employee, err := services.GetUser(event.EmployeeId, c.Request().Header) - if err != nil { - return c.HTML(http.StatusBadGateway, err.Error()) - } - author, err := services.GetUser(uint(authorId), c.Request().Header) + usersMap, err := services.GetUsers([]uint{event.EmployeeId, uint(authorId)}, c.Request().Header) + if err != nil { return c.HTML(http.StatusBadGateway, err.Error()) } + employee := usersMap[event.EmployeeId] + author := usersMap[uint(authorId)] + newEvent.Start = event.Start newEvent.End = event.End newEvent.AuthorId = uint(authorId) @@ -38,34 +39,74 @@ func (h *Handler) CreateEvent(c echo.Context) (err error) { newEvent.MemberId = event.MemberId newEvent.MedicalCardId = event.MedicalCardId newEvent.Status = event.Status - - h.DB.Begin() + newEvent.Services = event.Services tx := h.DB.Create(&newEvent) if tx.RowsAffected == 0 { - h.DB.Rollback() return c.NoContent(http.StatusBadGateway) } - eventsServices := []model.EventsServices{} - - for _, service := range event.Services { - eventsServices = append(eventsServices, model.EventsServices{EventId: newEvent.ID, ServiceId: service}) - } - - tx = h.DB.Create(eventsServices) - - if tx.RowsAffected == 0 { - h.DB.Rollback() - return c.NoContent(http.StatusBadGateway) - } - - h.DB.Commit() - - newEvent.Services = event.Services - newEvent.Author = *author - newEvent.Employee = *employee + newEvent.Author = author + newEvent.Employee = employee return c.JSON(http.StatusCreated, newEvent) } + +func (h *Handler) GetEvents(c echo.Context) (err error) { + var events []model.Event + query := c.Request().URL.Query() + _, _, filterMap := utils.GetFilterParams(query) + + tx := h.DB + + if len(filterMap) > 0 { + tx = tx.Where("start >= ?", filterMap["start"]).Where("\"end\" <= ?", filterMap["end"]) + } + + tx.Find(&events) + + ids := set.New[uint](len(events) * 2) + + for _, event := range events { + ids.Insert(event.EmployeeId) + ids.Insert(event.AuthorId) + } + + usersMap, err := services.GetUsers(ids.Slice(), c.Request().Header) + if err != nil { + return c.HTML(http.StatusBadGateway, err.Error()) + } + + for i, event := range events { + events[i].Author = usersMap[event.AuthorId] + events[i].Employee = usersMap[event.EmployeeId] + } + + return c.JSON(http.StatusOK, events) +} + +func (h *Handler) GetEvent(c echo.Context) error { + var event model.Event + id := c.Param("id") + + tx := h.DB.First(&event, id) + + if tx.RowsAffected == 0 { + return c.NoContent(http.StatusNotFound) + } + + return c.JSON(http.StatusOK, event) +} + +func (h *Handler) DeleteEvent(c echo.Context) error { + id := c.Param("id") + + tx := h.DB.Delete(&model.Event{}, id) + + if tx.RowsAffected == 0 { + return c.NoContent(http.StatusNotFound) + } + + return c.NoContent(http.StatusOK) +} diff --git a/main.go b/main.go index c077e0c..6e761b9 100644 --- a/main.go +++ b/main.go @@ -6,7 +6,7 @@ import ( "astra-events/model" "github.com/labstack/echo/v4" "github.com/labstack/echo/v4/middleware" - "gorm.io/driver/sqlite" + "gorm.io/driver/postgres" "gorm.io/gorm" "gorm.io/gorm/logger" "log" @@ -26,7 +26,7 @@ func main() { }, ) - db, err := gorm.Open(sqlite.Open(config.Env.Server.ConnectionString), &gorm.Config{ + db, err := gorm.Open(postgres.Open(config.Env.Server.ConnectionString), &gorm.Config{ Logger: newLogger, }) if err != nil { @@ -36,11 +36,14 @@ func main() { e.Use(middleware.Logger()) - db.AutoMigrate(&model.Event{}, &model.EventsServices{}) + db.AutoMigrate(&model.Event{}) var h = &handler.Handler{DB: db} e.POST("/", h.CreateEvent) + e.GET("/:id", h.GetEvent) + e.GET("/", h.GetEvents) + e.DELETE("/", h.DeleteEvent) e.Logger.Fatal(e.Start(":" + config.Env.Server.Port)) } diff --git a/model/event.go b/model/event.go index 8dea2f4..dff1ac0 100644 --- a/model/event.go +++ b/model/event.go @@ -1,24 +1,25 @@ package model import ( + "github.com/lib/pq" "gorm.io/gorm" "time" ) type Event struct { gorm.Model - Start time.Time `json:"start"` - End time.Time `json:"end"` - Author User `json:"author" gorm:"-"` - AuthorId uint `json:"-"` - Employee User `json:"employee" gorm:"-"` - EmployeeId uint `json:"-"` - Member PD `json:"member" gorm:"-"` - MemberId uint `json:"-"` - Status string `json:"status"` - MedicalCard Card `json:"medicalCard" gorm:"-"` - MedicalCardId uint `json:"-"` - Services []uint `json:"services" gorm:"-"` + Start time.Time `json:"start"` + End time.Time `json:"end"` + Author User `json:"author" gorm:"-"` + AuthorId uint `json:"-"` + Employee User `json:"employee" gorm:"-"` + EmployeeId uint `json:"-"` + Member PD `json:"member" gorm:"-"` + MemberId uint `json:"-"` + Status string `json:"status"` + MedicalCard Card `json:"medicalCard" gorm:"-"` + MedicalCardId uint `json:"-"` + Services pq.Int32Array `json:"services" gorm:"type:integer[]"` } type CreateEvent struct { @@ -28,5 +29,5 @@ type CreateEvent struct { MemberId uint `json:"member_id"` Status string `json:"status"` MedicalCardId uint `json:"medical_card_id"` - Services []uint `json:"services"` + Services []int32 `json:"services"` } diff --git a/model/events_services.go b/model/events_services.go deleted file mode 100644 index d5f698e..0000000 --- a/model/events_services.go +++ /dev/null @@ -1,9 +0,0 @@ -package model - -import "gorm.io/gorm" - -type EventsServices struct { - gorm.Model - EventId uint - ServiceId uint -} diff --git a/model/user.go b/model/user.go index 9484519..54fb034 100644 --- a/model/user.go +++ b/model/user.go @@ -5,16 +5,9 @@ import "gorm.io/gorm" type ( User struct { gorm.Model - UserName string `json:"userName" gorm:"unique"` + UserName string `json:"user_name" gorm:"unique"` Password string `json:"password,omitempty"` - FirstName string `json:"firstName"` - LastName string `json:"lastName"` + FirstName string `json:"first_name"` + LastName string `json:"last_name"` } ) - -type APIUser struct { - UserName string `json:"userName" gorm:"unique"` - Password string `json:"password,omitempty"` - FirstName string `json:"firstName"` - LastName string `json:"lastName"` -} diff --git a/pkg/utils/url.go b/pkg/utils/url.go index 330e69d..196850b 100644 --- a/pkg/utils/url.go +++ b/pkg/utils/url.go @@ -35,18 +35,27 @@ func GetPaginationParams(query url.Values) (int, int) { return limitInt, offsetInt } -func GetFilterParams(query url.Values) (string, bool, string, string) { +func GetFilterParams(query url.Values) (string, bool, map[string]string) { sort := GetQueryParam(query, "sort", "id:asc") - filter := GetQueryParam(query, "filter", ":") + filter := GetQueryParam(query, "filter", "") - filters := strings.Split(filter, ":") + filtersMap := make(map[string]string) + + filters := strings.Split(filter, "|") sorts := strings.Split(sort, ":") + for _, filter := range filters { + tmp := strings.Split(filter, "=") + if len(tmp) == 2 { + filtersMap[tmp[0]] = tmp[1] + } + } + isDesc := false if sorts[1] == "desc" { isDesc = true } - return sorts[0], isDesc, filters[0], filters[1] + return sorts[0], isDesc, filtersMap } diff --git a/services/users.go b/services/users.go index 2176925..b9326f0 100644 --- a/services/users.go +++ b/services/users.go @@ -7,6 +7,7 @@ import ( "encoding/json" "errors" "net/http" + "net/url" "strconv" ) @@ -18,7 +19,7 @@ func GetUser(ID uint, header http.Header) (*model.User, error) { header) if err != nil { - return nil, errors.New("Error Request to Users Service") + return nil, errors.New("error Request to Users Service") } u := new(model.User) @@ -26,8 +27,41 @@ func GetUser(ID uint, header http.Header) (*model.User, error) { err = json.Unmarshal(data, &u) if err != nil { - return nil, errors.New("Bad Response from Users Service") + return nil, errors.New("bad Response from Users Service") } return u, nil } + +func GetUsers(ids []uint, header http.Header) (map[uint]model.User, error) { + var users []model.User + var usersMap = make(map[uint]model.User) + Url, err := url.Parse(config.Env.MSHosts.UsersHost) + if err != nil { + return nil, err + } + + jsonIds, err := json.Marshal(ids) + + Url.Path += "/batch/" + string(jsonIds[:]) + + data, err, req := api.GetRequest( + Url.String(), + header) + + if err != nil || req.StatusCode != 200 { + return nil, err + } + + err = json.Unmarshal(data, &users) + + if err != nil { + return nil, err + } + + for _, user := range users { + usersMap[user.ID] = user + } + + return usersMap, nil +} diff --git a/test.db b/test.db deleted file mode 100644 index fb12d12..0000000 Binary files a/test.db and /dev/null differ