-
Notifications
You must be signed in to change notification settings - Fork 3
/
routesfactoids.go
89 lines (80 loc) · 2.2 KB
/
routesfactoids.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
77
78
79
80
81
82
83
84
85
86
87
88
89
package main
import (
"github.com/gin-gonic/gin"
"gorm.io/gorm"
"gorm.io/gorm/clause"
"io"
"net/http"
"strings"
)
const MaxFactoidLength = 1000
func getFactoids(c *gin.Context) {
factoids := make([]Factoid, 0)
err := Database.Find(&factoids).Error
if err != nil {
c.JSON(http.StatusInternalServerError, Error{Message: err.Error()})
return
}
c.JSON(http.StatusOK, factoids)
}
func getFactoid(c *gin.Context) {
name := c.Param("name")
if strings.HasPrefix(name, "/") {
name = strings.TrimPrefix(name, "/")
}
if _, exists := c.GetQuery("search"); exists {
factoids := make([]Factoid, 0)
err := Database.Where("name LIKE ?", name+"%").Find(&factoids).Error
if err != nil {
c.JSON(http.StatusInternalServerError, Error{Message: err.Error()})
return
}
c.JSON(http.StatusOK, factoids)
} else {
factoid := Factoid{Name: name}
err := Database.Where(&factoid).First(&factoid).Error
if err != nil {
if err == gorm.ErrRecordNotFound {
c.Status(404)
} else {
c.JSON(http.StatusInternalServerError, Error{Message: err.Error()})
}
return
}
c.JSON(http.StatusOK, factoid)
}
}
func updateFactoid(c *gin.Context) {
name := c.Param("name")
if strings.HasPrefix(name, "/") {
name = strings.TrimPrefix(name, "/")
}
body, err := io.ReadAll(io.LimitReader(c.Request.Body, MaxFactoidLength))
if err != nil {
c.JSON(http.StatusInternalServerError, Error{Message: err.Error()})
return
}
factoid := Factoid{Name: name, Content: string(body)}
err = Database.Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "name"}}, DoUpdates: clause.AssignmentColumns([]string{"content"})}).Create(&factoid).Error
if err != nil {
c.JSON(http.StatusInternalServerError, Error{Message: err.Error()})
return
}
c.JSON(http.StatusOK, factoid)
}
func deleteFactoid(c *gin.Context) {
name := c.Param("name")
if strings.HasPrefix(name, "/") {
name = strings.TrimPrefix(name, "/")
}
factoid := Factoid{Name: name}
res := Database.Where(&factoid).Delete(&factoid)
if res.Error != nil {
c.JSON(http.StatusInternalServerError, Error{Message: res.Error.Error()})
return
} else if res.RowsAffected == 0 {
c.Status(http.StatusNotFound)
} else {
c.Status(http.StatusNoContent)
}
}