Skip to content

Commit

Permalink
feat: update repository and domain models
Browse files Browse the repository at this point in the history
  • Loading branch information
kyong0612 committed Mar 13, 2024
1 parent 20f3a33 commit aa9ee25
Show file tree
Hide file tree
Showing 10 changed files with 330 additions and 227 deletions.
117 changes: 57 additions & 60 deletions cmd/app/main.go
Original file line number Diff line number Diff line change
@@ -1,76 +1,73 @@
package main

import (
"context"
"fmt"
"log"
"os"
"strconv"
"time"

_ "github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5"
"github.com/joho/godotenv"
"github.com/kyong0612/my-go-clean-architecture/internal/repository"
"github.com/kyong0612/my-go-clean-architecture/internal/rest"
"github.com/kyong0612/my-go-clean-architecture/internal/rest/middleware"
"github.com/kyong0612/my-go-clean-architecture/usecase/article"
"github.com/labstack/echo/v4"
)

// const (
// defaultTimeout = 30
// defaultAddress = ":9090"
// )
const (
defaultTimeout = 30
defaultAddress = ":9090"
)

// func init() {
// err := godotenv.Load()
// if err != nil {
// log.Fatal("Error loading .env file")
// }
// }
func init() {

Check failure on line 25 in cmd/app/main.go

View workflow job for this annotation

GitHub Actions / build

don't use `init` function (gochecknoinits)
err := godotenv.Load()
if err != nil {
log.Fatal("Error loading .env file")
}
}

func main() {
fmt.Println("Hello World")
// //prepare database
// dbHost := os.Getenv("DATABASE_HOST")
// dbPort := os.Getenv("DATABASE_PORT")
// dbUser := os.Getenv("DATABASE_USER")
// dbPass := os.Getenv("DATABASE_PASS")
// dbName := os.Getenv("DATABASE_NAME")
// connection := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s", dbUser, dbPass, dbHost, dbPort, dbName)
// val := url.Values{}
// val.Add("parseTime", "1")
// val.Add("loc", "Asia/Jakarta")
// dsn := fmt.Sprintf("%s?%s", connection, val.Encode())
// dbConn, err := sql.Open(`rdb`, dsn)
// if err != nil {
// log.Fatal("failed to open connection to database", err)
// }
// err = dbConn.Ping()
// if err != nil {
// log.Fatal("failed to ping database ", err)
// }
//prepare database
dbHost := os.Getenv("DATABASE_HOST")
dbPort := os.Getenv("DATABASE_PORT")
dbUser := os.Getenv("DATABASE_USER")
dbPass := os.Getenv("DATABASE_PASS")
dbName := os.Getenv("DATABASE_NAME")
connURL := fmt.Sprintf("postgres://%s:%s@%s:%s/%s?sslmode=verify-full", dbUser, dbPass, dbHost, dbPort, dbName)

Check failure on line 39 in cmd/app/main.go

View workflow job for this annotation

GitHub Actions / build

host:port in url should be constructed with net.JoinHostPort and not directly with fmt.Sprintf (nosprintfhostport)

dbConn, err := pgx.Connect(context.TODO(), connURL)
if err != nil {
log.Fatal("failed to open connection to database", err)
}
defer dbConn.Close(context.TODO())

// defer func() {
// err := dbConn.Close()
// if err != nil {
// log.Fatal("got error when closing the DB connection", err)
// }
// }()
// // prepare echo
// prepare echo

// e := echo.New()
// e.Use(middleware.CORS)
// timeoutStr := os.Getenv("CONTEXT_TIMEOUT")
// timeout, err := strconv.Atoi(timeoutStr)
// if err != nil {
// log.Println("failed to parse timeout, using default timeout")
// timeout = defaultTimeout
// }
// timeoutContext := time.Duration(timeout) * time.Second
// e.Use(middleware.SetRequestContextWithTimeout(timeoutContext))
e := echo.New()
e.Use(middleware.CORS)
timeoutStr := os.Getenv("CONTEXT_TIMEOUT")
timeout, err := strconv.Atoi(timeoutStr)
if err != nil {
log.Println("failed to parse timeout, using default timeout")
timeout = defaultTimeout
}
timeoutContext := time.Duration(timeout) * time.Second

Check failure on line 57 in cmd/app/main.go

View workflow job for this annotation

GitHub Actions / build

assignments should only be cuddled with other assignments (wsl)
e.Use(middleware.SetRequestContextWithTimeout(timeoutContext))

// // Prepare Repository
// authorRepo := rdbRepo.NewAuthorRepository(dbConn)
// articleRepo := rdbRepo.NewArticleRepository(dbConn)
// Prepare Repository
repo := repository.New(dbConn)

// // Build service Layer
// svc := article.NewService(articleRepo, authorRepo)
// rest.NewArticleHandler(e, svc)
// Build service Layer
svc := article.NewService(repo)
rest.NewArticleHandler(e, svc)

// // Start Server
// address := os.Getenv("SERVER_ADDRESS")
// if address == "" {
// address = defaultAddress
// }
// log.Fatal(e.Start(os.Getenv("SERVER_ADDRESS"))) //nolint
// Start Server
address := os.Getenv("SERVER_ADDRESS")
if address == "" {
address = defaultAddress

Check failure on line 70 in cmd/app/main.go

View workflow job for this annotation

GitHub Actions / build

ineffectual assignment to address (ineffassign)
}
log.Fatal(e.Start(os.Getenv("SERVER_ADDRESS"))) //nolint
}
2 changes: 1 addition & 1 deletion domain/article.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import (

// Article is representing the Article data struct.
type Article struct {
ID int64 `json:"id"`
ID int32 `json:"id"`
Title string `json:"title" validate:"required"`
Content string `json:"content" validate:"required"`
Author Author `json:"author"`
Expand Down
10 changes: 6 additions & 4 deletions domain/author.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
package domain

import "time"

// Author representing the Author data struct.
type Author struct {
ID int64 `json:"id"`
Name string `json:"name"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
ID int32 `json:"id"`
Name string `json:"name"`
CreatedAt time.Time `json:"created_at"`

Check failure on line 9 in domain/author.go

View workflow job for this annotation

GitHub Actions / build

json(camel): got 'created_at' want 'createdAt' (tagliatelle)
UpdatedAt time.Time `json:"updated_at"`

Check failure on line 10 in domain/author.go

View workflow job for this annotation

GitHub Actions / build

json(camel): got 'updated_at' want 'updatedAt' (tagliatelle)
}
49 changes: 49 additions & 0 deletions internal/repository/article.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
package repository

import (
"context"

"github.com/kyong0612/my-go-clean-architecture/domain"
"github.com/kyong0612/my-go-clean-architecture/internal/repository/postgres"
)

func articleToModel(article postgres.Article, author postgres.Author) domain.Article {

Check failure on line 10 in internal/repository/article.go

View workflow job for this annotation

GitHub Actions / build

func `articleToModel` is unused (unused)
return domain.Article{
ID: article.ID,
Title: article.Title,
Content: article.Content,
Author: authorToModel(author),
CreatedAt: article.CreatedAt.Time,
UpdatedAt: article.UpdatedAt.Time,
}
}

func (r *Repository) FetchArticles(ctx context.Context, cursor string, num int32) (res []domain.Article, nextCursor string, err error) {

Check failure on line 21 in internal/repository/article.go

View workflow job for this annotation

GitHub Actions / build

named return "res" with type "[]domain.Article" found (nonamedreturns)
// TODO: implement the code
return nil, "", nil
}

func (r *Repository) GetArticleByID(ctx context.Context, id int32) (domain.Article, error) {
// TODO: implement the code
return domain.Article{}, nil
}

func (r *Repository) GetArticleByTitle(ctx context.Context, title string) (domain.Article, error) {
// TODO: implement the code
return domain.Article{}, nil
}

func (r *Repository) UpdateArticle(ctx context.Context, ar *domain.Article) error {
// TODO: implement the code
return nil
}

func (r *Repository) StoreArticle(ctx context.Context, a *domain.Article) error {
// TODO: implement the code
return nil
}

func (r *Repository) DeleteArticle(ctx context.Context, id int32) error {
// TODO: implement the code
return nil
}
25 changes: 25 additions & 0 deletions internal/repository/author.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package repository

import (
"context"

"github.com/kyong0612/my-go-clean-architecture/domain"
"github.com/kyong0612/my-go-clean-architecture/internal/repository/postgres"
)

func authorToModel(author postgres.Author) domain.Author {
return domain.Author{
ID: author.ID,
Name: author.Name,
CreatedAt: author.CreatedAt.Time,
UpdatedAt: author.UpdatedAt.Time,
}
}

func (r *Repository) GetAuthorByID(ctx context.Context, id int32) (domain.Author, error) {
author, err := r.db.GetAuthorByID(ctx, id)
if err != nil {
return domain.Author{}, err
}
return authorToModel(author), nil
}
13 changes: 13 additions & 0 deletions internal/repository/repository.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package repository

import "github.com/kyong0612/my-go-clean-architecture/internal/repository/postgres"

type Repository struct {
db *postgres.Queries
}

func New(db postgres.DBTX) *Repository {
return &Repository{
db: postgres.New(db),
}
}
24 changes: 12 additions & 12 deletions internal/rest/article.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,12 @@ type ResponseError struct {
//
//go:generate mockery --name ArticleService
type ArticleService interface {
Fetch(ctx context.Context, cursor string, num int64) ([]domain.Article, string, error)
GetByID(ctx context.Context, id int64) (domain.Article, error)
Update(ctx context.Context, ar *domain.Article) error
GetByTitle(ctx context.Context, title string) (domain.Article, error)
Store(context.Context, *domain.Article) error
Delete(ctx context.Context, id int64) error
FetchArticles(ctx context.Context, cursor string, num int32) ([]domain.Article, string, error)
GetArticleByID(ctx context.Context, id int32) (domain.Article, error)
UpdateArticle(ctx context.Context, ar *domain.Article) error
GetArticleByTitle(ctx context.Context, title string) (domain.Article, error)
StoreArticle(context.Context, *domain.Article) error
DeleteArticle(ctx context.Context, id int32) error
}

// ArticleHandler represent the httphandler for article.
Expand Down Expand Up @@ -57,7 +57,7 @@ func (a *ArticleHandler) FetchArticle(c echo.Context) error {
cursor := c.QueryParam("cursor")
ctx := c.Request().Context()

listAr, nextCursor, err := a.Service.Fetch(ctx, cursor, int64(num))
listAr, nextCursor, err := a.Service.FetchArticles(ctx, cursor, int32(num))
if err != nil {
return c.JSON(getStatusCode(err), ResponseError{Message: err.Error()})
}
Expand All @@ -73,10 +73,10 @@ func (a *ArticleHandler) GetByID(c echo.Context) error {
return c.JSON(http.StatusNotFound, domain.ErrNotFound.Error())
}

id := int64(idP)
id := int32(idP)
ctx := c.Request().Context()

art, err := a.Service.GetByID(ctx, id)
art, err := a.Service.GetArticleByID(ctx, id)
if err != nil {
return c.JSON(getStatusCode(err), ResponseError{Message: err.Error()})
}
Expand Down Expand Up @@ -107,7 +107,7 @@ func (a *ArticleHandler) Store(c echo.Context) (err error) {
}

ctx := c.Request().Context()
err = a.Service.Store(ctx, &article)
err = a.Service.StoreArticle(ctx, &article)
if err != nil {
return c.JSON(getStatusCode(err), ResponseError{Message: err.Error()})
}
Expand All @@ -122,10 +122,10 @@ func (a *ArticleHandler) Delete(c echo.Context) error {
return c.JSON(http.StatusNotFound, domain.ErrNotFound.Error())
}

id := int64(idP)
id := int32(idP)
ctx := c.Request().Context()

err = a.Service.Delete(ctx, id)
err = a.Service.DeleteArticle(ctx, id)
if err != nil {
return c.JSON(getStatusCode(err), ResponseError{Message: err.Error()})
}
Expand Down
Loading

0 comments on commit aa9ee25

Please sign in to comment.