Skip to content

Commit

Permalink
Search Functionality and restructure
Browse files Browse the repository at this point in the history
  • Loading branch information
harshsinghvi committed Nov 18, 2023
1 parent 29ddda0 commit 6b5a9a3
Show file tree
Hide file tree
Showing 4 changed files with 110 additions and 73 deletions.
104 changes: 34 additions & 70 deletions controllers/controllers.go
Original file line number Diff line number Diff line change
@@ -1,80 +1,59 @@
package controllers

import (
"fmt"
"github.com/gin-gonic/gin"
// "github.com/go-pg/pg/v9"
guuid "github.com/google/uuid"
"harshsinghvi/golang-postgres-kubernetes/database"
"harshsinghvi/golang-postgres-kubernetes/models"
"harshsinghvi/golang-postgres-kubernetes/utils"
"log"
"net/http"
"strconv"
"time"

"harshsinghvi/golang-postgres-kubernetes/database"
"harshsinghvi/golang-postgres-kubernetes/models"
)

func GetAllTodos(c *gin.Context) {
var page int
var pag models.Pagination
var err error

var todos []models.Todo
var searchString = c.Query("search")
var pageString = c.Query("page")
pag.ParseString(pageString)

totalRecords, err := database.Connection.Model(&todos).Count()
if err != nil {
log.Printf("Error while getting all todos, Reason: %v\n", err)
c.JSON(http.StatusInternalServerError, gin.H{
"status": http.StatusInternalServerError,
"message": "Something went wrong",
})
querry := database.Connection.Model(&todos).Order("created_at DESC")

if searchString != "" {
querry = querry.Where(fmt.Sprintf("text like '%%%s%%'", searchString))
}

if pag.TotalRecords, err = querry.Count(); err != nil {
utils.InternalServerError(c, "Error while getting all todos, Reason:", err)
return
}

totalPages := totalRecords / 10

if c.Query("page") == "" {
page = 1
} else {
page, _ = strconv.Atoi(c.Query("page"))
if page == -1 {
err = database.Connection.Model(&todos).Order("created_at DESC").Select()
} else {
if page < 1 {
page = 1
}
err = database.Connection.Model(&todos).Order("created_at DESC").Limit(10).Offset(10 * page).Select()
}
if pag.CurrentPage != -1 {
querry = querry.Limit(10).Offset(10 * (pag.CurrentPage))
}

if err != nil {
log.Printf("Error while getting all todos, Reason: %v\n", err)
c.JSON(http.StatusInternalServerError, gin.H{
"status": http.StatusInternalServerError,
"message": "Something went wrong",
})
if err := querry.Select(); err != nil {
utils.InternalServerError(c, "Error while getting all todos, Reason:", err)
return
}

c.JSON(http.StatusOK, gin.H{
"status": http.StatusOK,
"message": "All Todos",
"data": todos,
"pagination": gin.H{
"total_records": totalRecords,
"current_page": page,
"total_pages": totalPages,
"next_page": page + 1,
"prev_page": page - 1,
},
"status": http.StatusOK,
"message": "All Todos",
"data": todos,
"pagination": pag.Validate(),
})
}

func GetSingleTodo(c *gin.Context) {
todoId := c.Param("id")
todo := &models.Todo{ID: todoId}
err := database.Connection.Select(todo)
if err != nil {
log.Printf("Error while getting a single todo, Reason: %v\n", err)
c.JSON(http.StatusNotFound, gin.H{
"status": http.StatusNotFound,
"message": "Todo not found",
})
if err := database.Connection.Select(todo); err != nil {
utils.InternalServerError(c, "Error while getting a single todo, Reason:", err)
return
}
c.JSON(http.StatusOK, gin.H{
Expand All @@ -100,11 +79,7 @@ func CreateTodo(c *gin.Context) {
})

if insertError != nil {
log.Printf("Error while inserting new todo into db, Reason: %v\n", insertError)
c.JSON(http.StatusInternalServerError, gin.H{
"status": http.StatusInternalServerError,
"message": "Something went wrong",
})
utils.InternalServerError(c, "Error while inserting new todo into db, Reason:", insertError)
return
}

Expand All @@ -120,20 +95,14 @@ func EditTodo(c *gin.Context) {
c.BindJSON(&todo)

querry := database.Connection.Model(&models.Todo{}).Set("completed = ?", todo.Completed).Set("updated_at = ?", time.Now())

if todo.Text != "" {
querry.Set("text = ?", todo.Text)
querry = querry.Set("text = ?", todo.Text)
}

res, err := querry.Where("id = ?", todoId).Update()

if err != nil {
log.Printf("Error, Reason: %v\n", err)
c.JSON(http.StatusInternalServerError, gin.H{
"status": 500,
"message": "Something went wrong",
})
return
utils.InternalServerError(c, "Error while editing todo, Reason:", err)
}

if res.RowsAffected() == 0 {
Expand All @@ -154,13 +123,8 @@ func EditTodo(c *gin.Context) {
func DeleteTodo(c *gin.Context) {
todoId := c.Param("id")
todo := &models.Todo{ID: todoId}
err := database.Connection.Delete(todo)
if err != nil {
log.Printf("Error while deleting a single todo, Reason: %v\n", err)
c.JSON(http.StatusInternalServerError, gin.H{
"status": http.StatusInternalServerError,
"message": "Something went wrong",
})
if err := database.Connection.Delete(todo); err != nil {
utils.InternalServerError(c, "Error while deleting a single todo, Reason:", err)
return
}
c.JSON(http.StatusOK, gin.H{
Expand Down
58 changes: 58 additions & 0 deletions models/pagination.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
package models

import "strconv"

type Pagination struct {
TotalRecords int `json:"total_records"`
CurrentPage int `json:"current_page"`
TotalPages int `json:"total_pages"`
NextPage int `json:"next_page"`
PrevPage int `json:"prev_page"`
}

func (pag *Pagination) Validate() *Pagination {
pag.Set(pag.CurrentPage, pag.TotalRecords)
return pag
}

func (pag *Pagination) Set(current int, totalRec int) *Pagination {
pag.TotalRecords = totalRec

if pag.TotalPages = pag.TotalRecords / 10; pag.TotalRecords%10 == 0 {
pag.TotalPages = pag.TotalPages - 1
}

if current <= 0 {
pag.PrevPage = 0
} else {
pag.PrevPage = current - 1
}

if current >= pag.TotalPages {
pag.NextPage = pag.TotalPages
} else {
pag.NextPage = current + 1
}

pag.CurrentPage = current
return pag
}

func (pag *Pagination) ParseString(pageString string) {
pag.CurrentPage = 0

if pageString == "" {
return
}

pag.CurrentPage, _ = strconv.Atoi(pageString)

if pag.CurrentPage == -1 {
return
}

if pag.CurrentPage < 0 {
pag.CurrentPage = 0
return
}
}
15 changes: 15 additions & 0 deletions utils/error.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package utils

import (
"github.com/gin-gonic/gin"
"log"
"net/http"
)

func InternalServerError(c *gin.Context, msg string, err error) {
log.Printf("%s %v\n", msg, err)
c.JSON(http.StatusInternalServerError, gin.H{
"status": http.StatusInternalServerError,
"message": "Something went wrong",
})
}
6 changes: 3 additions & 3 deletions utils/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@ import (
)

func GetEnv(varNameString string, defaultValue string) string {
var varValue string;
var varValue string
if varValue = os.Getenv(varNameString); varNameString == "" {
varValue = defaultValue
}
return varValue;
}
return varValue
}

0 comments on commit 6b5a9a3

Please sign in to comment.