/
request.go
116 lines (94 loc) · 2.27 KB
/
request.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
package post
import (
"time"
"github.com/andycai/werite/core"
"github.com/andycai/werite/model"
"github.com/gofiber/fiber/v2"
"github.com/gosimple/slug"
)
type requestCreate struct {
ID uint `json:"id"`
Slug string `json:"slug"`
Title string `json:"title" validate:"required"`
Description string `json:"description" validate:"required"`
Body string `json:"body" validate:"required"`
Action string `json:"action" form:"action"`
CategoryID uint `json:"category_id" form:"category_id"`
PublishedAt string `json:"published_at" form:"published_at" validate:"required"`
}
func Bind(c *fiber.Ctx, post *model.Post) error {
var r requestCreate
if err := c.BodyParser(&r); err != nil {
return err
}
if err := core.Validate(r); err != nil {
return err
}
post.ID = r.ID
post.Title = r.Title
post.Description = r.Description
post.Body = r.Body
post.CategoryID = r.CategoryID
if r.Action == "draft" {
post.IsDraft = 1
} else {
post.IsDraft = 0
}
if r.Slug != "" {
post.Slug = r.Slug
} else {
post.Slug = slug.Make(r.Title)
}
if r.PublishedAt != "" {
post.PublishedAt = core.ParseDate(r.PublishedAt)
} else {
post.PublishedAt = time.Now()
}
return nil
}
type requestCategoryCreate struct {
ID uint `json:"id"`
Slug string `json:"slug"`
Name string `json:"name" validate:"required"`
Description string `json:"description" validate:"required"`
}
func BindCategory(c *fiber.Ctx, category *model.Category) error {
var r requestCategoryCreate
if err := c.BodyParser(&r); err != nil {
return err
}
if err := core.Validate(r); err != nil {
return err
}
category.ID = r.ID
category.Name = r.Name
category.Description = r.Description
if r.Slug != "" {
category.Slug = r.Slug
} else {
category.Slug = slug.Make(r.Name)
}
return nil
}
type requestTagCreate struct {
ID uint `json:"id"`
Name string `json:"name" validate:"required"`
Slug string `json:"slug"`
}
func BindTag(c *fiber.Ctx, tag *model.Tag) error {
var r requestTagCreate
if err := c.BodyParser(&r); err != nil {
return err
}
if err := core.Validate(r); err != nil {
return err
}
tag.ID = r.ID
tag.Name = r.Name
if r.Slug != "" {
tag.Slug = r.Slug
} else {
tag.Slug = slug.Make(r.Name)
}
return nil
}