Skip to content

Commit

Permalink
chore: adding api(get) provinces in examples
Browse files Browse the repository at this point in the history
  • Loading branch information
Yuefii committed Aug 28, 2024
1 parent 959fd2d commit d67bea5
Show file tree
Hide file tree
Showing 8 changed files with 146 additions and 2 deletions.
2 changes: 1 addition & 1 deletion examples/api-go/database/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ func InitDB() (*gorm.DB, error) {
user := os.Getenv("MYSQL_USER")
password := os.Getenv("MYSQL_PASSWORD")
host := os.Getenv("MYSQL_HOST")
name := os.Getenv("MYSQL_NAME")
name := os.Getenv("MYSQL_DATABASE")

dsn := user + ":" + password + "@tcp(" + host + ":3306)/" + name + "?charset=utf8mb4&parseTime=True&loc=Local"

Expand Down
8 changes: 8 additions & 0 deletions examples/api-go/dtos/pagination_dto.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package dtos

type PaginationDTO struct {
CurrentPage int `json:"current_page"`
PerPage int `json:"per_page"`
TotalItems int `json:"total_items"`
TotalPages int `json:"total_pages"`
}
6 changes: 6 additions & 0 deletions examples/api-go/dtos/provinces_dto.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
package dtos

type ProvinceDTO struct {
Code string `json:"code"`
Name string `json:"name"`
}
6 changes: 6 additions & 0 deletions examples/api-go/dtos/response.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
package dtos

type ResponseDTO struct {
Pagination PaginationDTO `json:"pagination"`
Data interface{} `json:"data"`
}
103 changes: 103 additions & 0 deletions examples/api-go/handlers/provinces_handler.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
package handlers

import (
"net/http"
"strconv"

"github.com/gin-gonic/gin"
"github.com/yuefii/NusantaraKita/examples/api-go/dtos"
"github.com/yuefii/NusantaraKita/examples/api-go/models"
"gorm.io/gorm"
)

type Handler struct {
db *gorm.DB
}

func NewHandler(db *gorm.DB) *Handler {
return &Handler{db}
}

func (handler *Handler) GetProvinces(ctx *gin.Context) {
var province []models.Provinces
var totalItems int64

showAll := ctx.Query("show_all") == "true"
pageStr := ctx.Query("page")
perPageStr := ctx.Query("per_page")

page := 1
perPage := 10

if pageStr != "" {
if p, err := strconv.Atoi(pageStr); err == nil && p > 0 {
page = p
}
}
if perPageStr != "" {
if pp, err := strconv.Atoi(perPageStr); err == nil && pp > 0 {
perPage = pp
}
}

if showAll {

result := handler.db.Find(&province)
if result.Error != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": result.Error.Error()})
return
}
totalItems = int64(len(province))

var provinceDTOs []dtos.ProvinceDTO
for _, r := range province {
provinceDTOs = append(provinceDTOs, dtos.ProvinceDTO{
Code: r.Code,
Name: r.Name,
})
}

response := gin.H{
"data": provinceDTOs,
}
ctx.JSON(http.StatusOK, response)
return
}

result := handler.db.Model(&models.Provinces{}).Count(&totalItems)
if result.Error != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": result.Error.Error()})
return
}

result = handler.db.Offset((page - 1) * perPage).Limit(perPage).Find(&province)
if result.Error != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": result.Error.Error()})
return
}

var provinceDTOs []dtos.ProvinceDTO
for _, response := range province {
provinceDTOs = append(provinceDTOs, dtos.ProvinceDTO{
Code: response.Code,
Name: response.Name,
})
}

totalPages := int(totalItems) / perPage
if int(totalItems)%perPage != 0 {
totalPages++
}

response := dtos.ResponseDTO{
Data: provinceDTOs,
Pagination: dtos.PaginationDTO{
CurrentPage: page,
PerPage: perPage,
TotalItems: int(totalItems),
TotalPages: totalPages,
},
}

ctx.JSON(http.StatusOK, response)
}
6 changes: 6 additions & 0 deletions examples/api-go/models/provinces.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
package models

type Provinces struct {
Code string
Name string
}
13 changes: 13 additions & 0 deletions examples/api-go/routes/router.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package routes

import (
"github.com/gin-gonic/gin"
"github.com/yuefii/NusantaraKita/examples/api-go/handlers"
"gorm.io/gorm"
)

func SetupRoutes(router *gin.Engine, db *gorm.DB) {
handler := handlers.NewHandler(db)

router.GET("/api/provinces", handler.GetProvinces)
}
4 changes: 3 additions & 1 deletion main.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,16 @@ import (

"github.com/gin-gonic/gin"
"github.com/yuefii/NusantaraKita/examples/api-go/database"
"github.com/yuefii/NusantaraKita/examples/api-go/routes"
)

func main() {
_, err := database.InitDB()
db, err := database.InitDB()
if err != nil {
panic("failed to connect database.")
}
router := gin.Default()
routes.SetupRoutes(router, db)
router.GET("/", func(ctx *gin.Context) {
ctx.JSON(http.StatusOK, gin.H{"message": "project is running"})
})
Expand Down

0 comments on commit d67bea5

Please sign in to comment.