-
Notifications
You must be signed in to change notification settings - Fork 0
/
job.go
98 lines (78 loc) · 2.51 KB
/
job.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
package api
import (
"encoding/json"
"net/http"
"github.com/jvikstedt/watchful/pkg/model"
"github.com/jvikstedt/watchful/pkg/schedule"
)
func (h handler) jobGetAll(w http.ResponseWriter, r *http.Request) (interface{}, int, error) {
jobs, err := model.JobAll(h.db)
if err != nil {
return EmptyObject, http.StatusInternalServerError, err
}
return jobs, http.StatusOK, nil
}
func (h handler) jobCreate(w http.ResponseWriter, r *http.Request) (interface{}, int, error) {
decoder := json.NewDecoder(r.Body)
job := &model.Job{}
if err := decoder.Decode(job); err != nil {
return EmptyObject, http.StatusUnprocessableEntity, err
}
if err := job.Create(h.db); err != nil {
return EmptyObject, http.StatusUnprocessableEntity, err
}
return job, http.StatusCreated, nil
}
func (h handler) jobGetOne(w http.ResponseWriter, r *http.Request) (interface{}, int, error) {
jobID, err := h.getURLParamInt(r, "jobID")
if err != nil {
return EmptyObject, http.StatusUnprocessableEntity, err
}
job := model.Job{}
if err := model.JobGetOne(h.db, jobID, &job); err != nil {
return EmptyObject, http.StatusNotFound, err
}
if job.Active {
h.scheduler.AddEntry(schedule.EntryID(job.ID), job.Cron, func(id schedule.EntryID) {
h.exec.AddJob(&job, false)
})
}
return job, http.StatusOK, nil
}
func (h handler) jobUpdate(w http.ResponseWriter, r *http.Request) (interface{}, int, error) {
jobID, err := h.getURLParamInt(r, "jobID")
if err != nil {
return EmptyObject, http.StatusUnprocessableEntity, err
}
job := &model.Job{}
if err := model.JobGetOne(h.db, jobID, job); err != nil {
return EmptyObject, http.StatusNotFound, err
}
decoder := json.NewDecoder(r.Body)
if err := decoder.Decode(job); err != nil {
return EmptyObject, http.StatusUnprocessableEntity, err
}
if err := job.Update(h.db); err != nil {
return EmptyObject, http.StatusUnprocessableEntity, err
}
if job.Active {
h.scheduler.AddEntry(schedule.EntryID(job.ID), job.Cron, func(id schedule.EntryID) {
h.exec.AddJob(job, false)
})
} else {
h.scheduler.RemoveEntry(schedule.EntryID(job.ID))
}
return job, http.StatusOK, nil
}
func (h handler) jobTestRun(w http.ResponseWriter, r *http.Request) (interface{}, int, error) {
jobID, err := h.getURLParamInt(r, "jobID")
if err != nil {
return EmptyObject, http.StatusUnprocessableEntity, err
}
job := model.Job{}
if err := model.JobGetOne(h.db, jobID, &job); err != nil {
return EmptyObject, http.StatusNotFound, err
}
id := h.exec.AddJob(&job, true)
return id, http.StatusOK, nil
}