Skip to content

Commit

Permalink
refactor: Removing crud and using plain object (#36)
Browse files Browse the repository at this point in the history
* refactor: Removing crud and using plain object

* fix: Bumping httputils for fixing cancelation of getRow

* fix: Aligning httputils version for ketchup and auth
  • Loading branch information
ViBiOh authored Apr 29, 2020
1 parent 8e481cd commit f3ee4b6
Show file tree
Hide file tree
Showing 19 changed files with 445 additions and 776 deletions.
52 changes: 5 additions & 47 deletions cmd/ketchup/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,13 @@ import (
authStore "github.com/ViBiOh/auth/v2/pkg/store/db"
"github.com/ViBiOh/httputils/v3/pkg/alcotest"
"github.com/ViBiOh/httputils/v3/pkg/cors"
"github.com/ViBiOh/httputils/v3/pkg/crud"
"github.com/ViBiOh/httputils/v3/pkg/db"
"github.com/ViBiOh/httputils/v3/pkg/httputils"
"github.com/ViBiOh/httputils/v3/pkg/logger"
"github.com/ViBiOh/httputils/v3/pkg/owasp"
"github.com/ViBiOh/httputils/v3/pkg/prometheus"
"github.com/ViBiOh/httputils/v3/pkg/swagger"
"github.com/ViBiOh/ketchup/pkg/github"
"github.com/ViBiOh/ketchup/pkg/middleware"
"github.com/ViBiOh/ketchup/pkg/renderer"
"github.com/ViBiOh/ketchup/pkg/scheduler"
ketchupService "github.com/ViBiOh/ketchup/pkg/service/ketchup"
Expand Down Expand Up @@ -56,16 +55,12 @@ func main() {
prometheusConfig := prometheus.Flags(fs, "prometheus")
owaspConfig := owasp.Flags(fs, "")
corsConfig := cors.Flags(fs, "cors")
swaggerConfig := swagger.Flags(fs, "swagger")

dbConfig := db.Flags(fs, "db")
mailerConfig := mailer.Flags(fs, "mailer")
githubConfig := github.Flags(fs, "github")
schedulerConfig := scheduler.Flags(fs, "scheduler")

crudUserConfig := crud.GetConfiguredFlags(usersPath, "Users")(fs, "users")
crudKetchupConfig := crud.GetConfiguredFlags(ketchupsPath, "Ketchup")(fs, "ketchups")

logger.Fatal(fs.Parse(os.Args[1:]))

alcotest.DoAndExit(alcotestConfig)
Expand All @@ -86,53 +81,16 @@ func main() {

userServiceApp := userService.New(userStore.New(ketchupDb), authService, identProvider)
repositoryApp := repositoryService.New(repositoryStore.New(ketchupDb), githubApp)
ketchupApp := ketchupService.New(ketchupStore.New(ketchupDb), repositoryApp, userServiceApp)

schedulerApp := scheduler.New(schedulerConfig, repositoryApp, ketchupApp, githubApp, mailerApp)
ketchupService := ketchupService.New(ketchupStore.New(ketchupDb), repositoryApp, userServiceApp)

rendererApp, err := renderer.New(ketchupApp)
logger.Fatal(err)

/* Crud and Swagger related things */
crudUserApp, err := crud.New(crudUserConfig, userServiceApp)
logger.Fatal(err)
schedulerApp := scheduler.New(schedulerConfig, repositoryApp, ketchupService, githubApp, mailerApp)

crudKetchupApp, err := crud.New(crudKetchupConfig, ketchupApp)
rendererApp, err := renderer.New(ketchupService)
logger.Fatal(err)

swaggerApp, err := swagger.New(swaggerConfig, server.Swagger, crudUserApp.Swagger, crudKetchupApp.Swagger)
logger.Fatal(err)

swaggerHandler := http.StripPrefix(apiPath, swaggerApp.Handler())
userHandler := http.StripPrefix(usersPath, crudUserApp.Handler())

protectedUserHandler := httputils.ChainMiddlewares(userHandler, authMiddleware.Middleware)
protectedKetchupHandler := httputils.ChainMiddlewares(http.StripPrefix(ketchupsPath, crudKetchupApp.Handler()), authMiddleware.Middleware)
/* Crud and Swagger related things */

rendererHandler := httputils.ChainMiddlewares(rendererApp.Handler(), authMiddleware.Middleware)
rendererHandler := httputils.ChainMiddlewares(rendererApp.Handler(), authMiddleware.Middleware, middleware.New(userServiceApp).Middleware)

handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.TrimSuffix(r.URL.Path, "/") == usersPath && r.Method == http.MethodPost {
userHandler.ServeHTTP(w, r)
return
}

if strings.HasPrefix(r.URL.Path, usersPath) {
protectedUserHandler.ServeHTTP(w, r)
return
}

if strings.HasPrefix(r.URL.Path, ketchupsPath) {
protectedKetchupHandler.ServeHTTP(w, r)
return
}

if strings.HasPrefix(r.URL.Path, apiPath) {
swaggerHandler.ServeHTTP(w, r)
return
}

if strings.HasPrefix(r.URL.Path, faviconPath) {
http.ServeFile(w, r, path.Join("static", r.URL.Path))
}
Expand Down
2 changes: 1 addition & 1 deletion ddl.sql
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ CREATE TABLE ketchup (
creation_date TIMESTAMP WITH TIME ZONE DEFAULT now()
);

CREATE UNIQUE INDEX ketchup_user ON ketchup(user_id);
CREATE UNIQUE INDEX ketchup_id ON ketchup(user_id, repository_id);

-- data
DO $$
Expand Down
4 changes: 2 additions & 2 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ go 1.14

require (
github.com/DATA-DOG/go-sqlmock v1.4.1
github.com/ViBiOh/auth/v2 v2.4.1
github.com/ViBiOh/httputils/v3 v3.17.0
github.com/ViBiOh/auth/v2 v2.4.2
github.com/ViBiOh/httputils/v3 v3.17.1
github.com/ViBiOh/mailer v1.7.0
github.com/lib/pq v1.4.0
)
9 changes: 4 additions & 5 deletions go.sum
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
github.com/DATA-DOG/go-sqlmock v1.4.1 h1:ThlnYciV1iM/V0OSF/dtkqWb6xo5qITT1TJBG1MRDJM=
github.com/DATA-DOG/go-sqlmock v1.4.1/go.mod h1:f/Ixk793poVmq4qj/V1dPUg2JEAKC73Q5eFN3EC/SaM=
github.com/ViBiOh/auth/v2 v2.4.1 h1:BHQOBnl+EjcJSsO3p03dpcKNjWdbDBKKNFGq56iGZ34=
github.com/ViBiOh/auth/v2 v2.4.1/go.mod h1:aHuSObavFpVwKj9crXMVzhey++MWQ/ZatptLKBHAzcU=
github.com/ViBiOh/auth/v2 v2.4.2 h1:YWDAz6LKobs6brxbGD7iJwNdO4alM/bb5Oc9RWaxpXA=
github.com/ViBiOh/auth/v2 v2.4.2/go.mod h1:9eMGfYkNQ+7ekSiORzDRHRk1UfIFJ7g+R4R9tFACSOY=
github.com/ViBiOh/httputils/v3 v3.13.0/go.mod h1:exwp/UNyjMLfZTIl8i7x+AfBc4+9x2ar1VDvV0qWbv0=
github.com/ViBiOh/httputils/v3 v3.16.1/go.mod h1:XaNCzKOhynf+7U0E0RXrzGLtMkLxpVzrHwa0N1ANTmo=
github.com/ViBiOh/httputils/v3 v3.17.0 h1:GKt6ZQbBWnjk9qVGd4OAxLPaXLqtNW9C+RBPOQfRC3w=
github.com/ViBiOh/httputils/v3 v3.17.0/go.mod h1:XaNCzKOhynf+7U0E0RXrzGLtMkLxpVzrHwa0N1ANTmo=
github.com/ViBiOh/httputils/v3 v3.17.1 h1:Yo1gncmsuAnAJxMqMmoXWKILLnHR7nLJrf9bZ1XQ0mY=
github.com/ViBiOh/httputils/v3 v3.17.1/go.mod h1:XaNCzKOhynf+7U0E0RXrzGLtMkLxpVzrHwa0N1ANTmo=
github.com/ViBiOh/mailer v1.7.0 h1:ht6G7eNu/IhIgpqw7R2PHXd8l4IIPxX6gekKIfK6V+Q=
github.com/ViBiOh/mailer v1.7.0/go.mod h1:h5tQIdHQIXHmKckTxUgDP0tfnKyXKet2dGdBz7iRWYY=
github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc=
Expand Down
31 changes: 31 additions & 0 deletions pkg/middleware/middleware.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package middleware

import (
"net/http"

"github.com/ViBiOh/ketchup/pkg/service/user"
)

// App of package
type App interface {
Middleware(next http.Handler) http.Handler
}

type app struct {
userService user.App
}

// New creates new App from Config
func New(userService user.App) App {
return app{
userService: userService,
}
}

func (a app) Middleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if next != nil {
next.ServeHTTP(w, r.WithContext(a.userService.StoreInContext(r.Context())))
}
})
}
2 changes: 1 addition & 1 deletion pkg/renderer/handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ func redirectWithMessage(w http.ResponseWriter, r *http.Request, message string)
}

func (a app) getData(r *http.Request) (interface{}, error) {
ketchups, _, err := a.ketchupApp.List(r.Context(), 1, 100, "", true, nil)
ketchups, _, err := a.ketchupService.List(r.Context(), 1, 100)

return ketchups, err
}
Expand Down
57 changes: 10 additions & 47 deletions pkg/renderer/ketchups.go
Original file line number Diff line number Diff line change
@@ -1,13 +1,11 @@
package renderer

import (
"errors"
"fmt"
"net/http"
"strconv"
"strings"

"github.com/ViBiOh/httputils/v3/pkg/crud"
"github.com/ViBiOh/ketchup/pkg/model"
)

Expand Down Expand Up @@ -46,12 +44,7 @@ func (a app) handleCreate(w http.ResponseWriter, r *http.Request) {
},
}

if errs := a.ketchupApp.Check(r.Context(), nil, ketchup); len(errs) > 0 {
a.handleCrudError(w, errs)
return
}

if _, err := a.ketchupApp.Create(r.Context(), ketchup); err != nil {
if _, err := a.ketchupService.Create(r.Context(), ketchup); err != nil {
a.errorHandler(w, http.StatusInternalServerError, err, nil)
return
}
Expand All @@ -66,26 +59,19 @@ func (a app) handleUpdate(w http.ResponseWriter, r *http.Request) {
return
}

oldKetchup, err := a.ketchupApp.Get(r.Context(), id)
if err != nil {
a.errorHandler(w, http.StatusBadRequest, err, nil)
return
}

newKetchup := oldKetchup.(model.Ketchup)
newKetchup.Version = r.FormValue("version")

if errs := a.ketchupApp.Check(r.Context(), oldKetchup, newKetchup); len(errs) > 0 {
a.handleCrudError(w, errs)
return
item := model.Ketchup{
Version: r.FormValue("version"),
Repository: model.Repository{
ID: id,
},
}

if _, err := a.ketchupApp.Update(r.Context(), newKetchup); err != nil {
if err := a.ketchupService.Update(r.Context(), item); err != nil {
a.errorHandler(w, http.StatusInternalServerError, err, nil)
return
}

redirectWithMessage(w, r, fmt.Sprintf("%s updated with success!", newKetchup.Repository.Name))
redirectWithMessage(w, r, fmt.Sprintf("Updated to %s with success!", item.Version))
}

func (a app) handleDelete(w http.ResponseWriter, r *http.Request) {
Expand All @@ -95,33 +81,10 @@ func (a app) handleDelete(w http.ResponseWriter, r *http.Request) {
return
}

rawKetchup, err := a.ketchupApp.Get(r.Context(), id)
if err != nil {
a.errorHandler(w, http.StatusBadRequest, err, nil)
return
}

ketchup := rawKetchup.(model.Ketchup)

if errs := a.ketchupApp.Check(r.Context(), ketchup, nil); len(errs) > 0 {
a.handleCrudError(w, errs)
return
}

if err := a.ketchupApp.Delete(r.Context(), ketchup); err != nil {
if err := a.ketchupService.Delete(r.Context(), id); err != nil {
a.errorHandler(w, http.StatusInternalServerError, err, nil)
return
}

redirectWithMessage(w, r, fmt.Sprintf("%s deleted with success!", ketchup.Repository.Name))
}

func (a app) handleCrudError(w http.ResponseWriter, errs []crud.Error) {
errorsValues := make([]error, 1+len(errs))
errorsValues[0] = errors.New("invalid form")
for i, err := range errs {
errorsValues[i+1] = err
}

a.errorHandler(w, http.StatusBadRequest, errorsValues...)
redirectWithMessage(w, r, "Deleted with success!")
}
12 changes: 6 additions & 6 deletions pkg/renderer/renderer.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import (
"github.com/ViBiOh/httputils/v3/pkg/query"
"github.com/ViBiOh/httputils/v3/pkg/templates"
"github.com/ViBiOh/ketchup/pkg/model"
ketchupService "github.com/ViBiOh/ketchup/pkg/service/ketchup"
"github.com/ViBiOh/ketchup/pkg/service/ketchup"
)

const (
Expand All @@ -27,20 +27,20 @@ type app struct {
tpl *template.Template
version string

ketchupApp ketchupService.App
ketchupService ketchup.App
}

// New creates new App from Config
func New(ketchupApp ketchupService.App) (App, error) {
func New(ketchupService ketchup.App) (App, error) {
filesTemplates, err := templates.GetTemplates("templates", ".html")
if err != nil {
return nil, fmt.Errorf("unable to get templates: %s", err)
}

return app{
tpl: template.Must(template.New("ketchup").ParseFiles(filesTemplates...)),
version: os.Getenv("VERSION"),
ketchupApp: ketchupApp,
tpl: template.Must(template.New("ketchup").ParseFiles(filesTemplates...)),
version: os.Getenv("VERSION"),
ketchupService: ketchupService,
}, nil
}

Expand Down
32 changes: 15 additions & 17 deletions pkg/scheduler/scheduler.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@ import (
"github.com/ViBiOh/httputils/v3/pkg/logger"
"github.com/ViBiOh/ketchup/pkg/github"
"github.com/ViBiOh/ketchup/pkg/model"
ketchupService "github.com/ViBiOh/ketchup/pkg/service/ketchup"
repositoryService "github.com/ViBiOh/ketchup/pkg/service/repository"
"github.com/ViBiOh/ketchup/pkg/service/ketchup"
"github.com/ViBiOh/ketchup/pkg/service/repository"
mailer "github.com/ViBiOh/mailer/pkg/client"
)

Expand All @@ -40,10 +40,10 @@ type app struct {
hour string
loginID uint64

repositoryApp repositoryService.App
ketchupApp ketchupService.App
githubApp github.App
mailerApp mailer.App
repositoryApp repository.App
ketchupService ketchup.App
githubApp github.App
mailerApp mailer.App
}

// Flags adds flags for configuring package
Expand All @@ -56,16 +56,16 @@ func Flags(fs *flag.FlagSet, prefix string) Config {
}

// New creates new App from Config
func New(config Config, repositoryApp repositoryService.App, ketchupApp ketchupService.App, githubApp github.App, mailerApp mailer.App) App {
func New(config Config, repositoryApp repository.App, ketchupService ketchup.App, githubApp github.App, mailerApp mailer.App) App {
return app{
timezone: strings.TrimSpace(*config.timezone),
hour: strings.TrimSpace(*config.hour),
loginID: uint64(*config.loginID),

repositoryApp: repositoryApp,
ketchupApp: ketchupApp,
githubApp: githubApp,
mailerApp: mailerApp,
repositoryApp: repositoryApp,
ketchupService: ketchupService,
githubApp: githubApp,
mailerApp: mailerApp,
}
}

Expand Down Expand Up @@ -100,14 +100,12 @@ func (a app) getNewReleases(ctx context.Context) ([]model.Release, error) {
page := uint(1)

for {
repositories, totalCount, err := a.repositoryApp.List(ctx, page, pageSize, "name", true, nil)
repositories, totalCount, err := a.repositoryApp.List(ctx, page, pageSize)
if err != nil {
return nil, fmt.Errorf("unable to fetch page %d of repositories: %s", page, err)
}

for _, o := range repositories {
repository := o.(model.Repository)

for _, repository := range repositories {
release, err := a.githubApp.LastRelease(repository.Name)
if err != nil {
return nil, err
Expand All @@ -122,7 +120,7 @@ func (a app) getNewReleases(ctx context.Context) ([]model.Release, error) {

newReleases = append(newReleases, model.NewRelease(repository, release))

if _, err := a.repositoryApp.Update(ctx, repository); err != nil {
if err := a.repositoryApp.Update(ctx, repository); err != nil {
return nil, fmt.Errorf("unable to update repository %s: %s", repository.Name, err)
}
}
Expand All @@ -141,7 +139,7 @@ func (a app) getKetchupToNotify(ctx context.Context, releases []model.Release) (
repositories[index] = release.Repository
}

ketchups, err := a.ketchupApp.ListForRepositories(ctx, repositories)
ketchups, err := a.ketchupService.ListForRepositories(ctx, repositories)
if err != nil {
return nil, fmt.Errorf("unable to get ketchups for repositories: %s", err)
}
Expand Down
Loading

0 comments on commit f3ee4b6

Please sign in to comment.