/
updateOpening.go
77 lines (66 loc) · 1.92 KB
/
updateOpening.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
package handler
import (
"net/http"
"github.com/felipedias-dev/gopportunities/schema"
"github.com/gin-gonic/gin"
)
// @BasePath /api/v1
// @Description Update a job opening
// @Tags Openings
// @Accept json
// @Produce json
// @Param id path int true "Opening ID"
// @Success 200 {object} UpdateOpeningResponse
// @Failure 400 {object} ErrorResponse
// @Failure 404 {object} ErrorResponse
// @Failure 500 {object} ErrorResponse
// @Router /opening/:id [put]
func UpdateOpeningHandler(ctx *gin.Context) {
request := UpdateOpeningReq{}
if err := ctx.ShouldBindJSON(&request); err != nil {
logger.Errorf("update opening error: %v", err.Error())
sendError(ctx, http.StatusBadRequest, err.Error())
return
}
if request.IsEmpty() {
logger.Error("validation error: at least one field must be valid")
sendError(ctx, http.StatusBadRequest, "validation error: at least one field must be valid")
return
}
id := ctx.Param("id")
if id == "" {
logger.Error("update opening error: param id is missing")
sendError(ctx, http.StatusBadRequest, "param id is missing")
return
}
opening := schema.Opening{}
if err := db.First(&opening, id).Error; err != nil {
logger.Errorf("update opening error: %v", err.Error())
sendError(ctx, http.StatusNotFound, "opening not found")
return
}
if request.Company != "" {
opening.Company = request.Company
}
if request.Link != "" {
opening.Link = request.Link
}
if request.Location != "" {
opening.Location = request.Location
}
if request.Role != "" {
opening.Role = request.Role
}
if request.Remote != opening.Remote {
opening.Remote = request.Remote
}
if request.Salary != opening.Salary && request.Salary != 0 {
opening.Salary = request.Salary
}
if err := db.Save(&opening).Error; err != nil {
logger.Errorf("update opening error: %v", err.Error())
sendError(ctx, http.StatusInternalServerError, "update opening error")
return
}
sendSuccess(ctx, http.StatusOK, opening)
}