-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcategory.go
76 lines (63 loc) · 1.48 KB
/
category.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package api
import (
"net/http"
"strconv"
"github.com/gin-gonic/gin"
"github.com/jmoiron/sqlx"
)
const (
GET_CATEGORIES = "SELECT * FROM category;"
GET_CATEGORY_BY_ID = "SELECT * FROM category WHERE id=$1;"
INSERT_CATEGORY = "INSERT INTO category (name) VALUES (:name);"
)
type Category struct {
Id int `json:"id" db:"id"`
Name string `json:"name" db:"name"`
}
func (c *Category) CreateInDb(db *sqlx.DB) error {
_, err := db.NamedExec(INSERT_CATEGORY, c)
return err
}
func LoadCategoryFromId(db *sqlx.DB, id int) (*Category, error) {
c := &Category{}
err := db.Get(c, GET_CATEGORY_BY_ID, id)
if err != nil {
return nil, err
}
return c, nil
}
func LoadCategories(db *sqlx.DB) (*[]Category, error) {
c := &[]Category{}
err := db.Select(c, GET_CATEGORIES)
if err != nil {
return nil, err
}
return c, nil
}
func GetCategory(c *gin.Context) {
id, err := strconv.Atoi(c.Param("id"))
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"error": "please provide a valid category id",
})
return
}
cat, err := LoadCategoryFromId(APIDatabase, id)
if err != nil {
c.JSON(http.StatusNotFound, gin.H{
"error": "cannot find category with the provided id",
})
return
}
c.JSON(http.StatusOK, cat)
}
func GetCategories(c *gin.Context) {
cats, err := LoadCategories(APIDatabase)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"error": "cannot load categories, please try again later",
})
return
}
c.JSON(http.StatusOK, cats)
}