added filtering code

pull/1066/head
Rhythm 2021-12-06 11:23:40 +05:30
parent ee5a4b8f37
commit 48a1803b8c
3 changed files with 68 additions and 1 deletions

View File

@ -21,10 +21,24 @@ func findDowntime(r *http.Request) (*downtimes.Downtime, error) {
return downtime, nil
}
func apiAllDowntimes(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
fmt.Println(vars)
ninetyDaysAgo := time.Now().Add(time.Duration(-90*24) * time.Hour)
start := ninetyDaysAgo
end := time.Now()
downtime,err := downtimes.FindAll(vars,start, end)
if err != nil {
sendErrorJson(err, w, r)
return
}
fmt.Println(downtime)
sendJsonAction(downtime, "fetch", w, r)
}
func apiAllDowntimesForServiceHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
serviceId := utils.ToInt(vars["service_id"])
ninetyDaysAgo := time.Now().Add(time.Duration(-90*24) * time.Hour)
downtime, err := downtimes.FindByService(serviceId, ninetyDaysAgo, time.Now())

View File

@ -193,6 +193,7 @@ func Router() *mux.Router {
//r.Handle("/checkin/{api}", http.HandlerFunc(checkinHitHandler))
// API DOWNTIME Routes
api.Handle("/api/downtimes", authenticated(apiAllDowntimes, false)).Methods("GET")
api.Handle("/api/service/{service_id}/downtimes", authenticated(apiAllDowntimesForServiceHandler, false)).Methods("GET")
api.Handle("/api/downtimes", authenticated(apiCreateDowntimeHandler, false)).Methods("POST")
api.Handle("/api/downtimes/{id}", authenticated(apiDowntimeHandler, false)).Methods("GET")

View File

@ -3,6 +3,8 @@ package downtimes
import (
"fmt"
"github.com/statping/statping/database"
"github.com/statping/statping/types/services"
"strconv"
"time"
)
@ -58,6 +60,56 @@ func FindByService(service int64, start time.Time, end time.Time) (*[]Downtime,
return &downtime, q.Error()
}
func ConvertToUnixTime(str string) (time.Time,error){
i, err := strconv.ParseInt(str, 10, 64)
var t time.Time
if err != nil {
return t,err
}
tm := time.Unix(i, 0)
return tm,nil
}
type invalidTimeDurationError struct{}
func (m *invalidTimeDurationError) Error() string {
return "invalid time duration"
}
func FindAll(vars map[string]string ,start time.Time, end time.Time) (*[]Downtime, error) {
var downtime []Downtime
q := db.Where("start BETWEEN ? AND ? ", start, end)
for key,val :=range vars{
switch key{
case "start":
_,ok := vars["end"]
if ok && (vars["end"]>vars["start"]) {
start,err := ConvertToUnixTime(vars["start"])
if err!=nil {
return &downtime,err
}
end,err := ConvertToUnixTime(vars["end"])
if err!=nil {
return &downtime,err
}
q = q.Where("start BETWEEN ? AND ? ", start, end)
}else {
return &downtime,&invalidTimeDurationError{}
}
case "sub_status":
q = q.Where(" sub_status = ?",val)
case "service":
allServices := services.All()
for k,v := range allServices{
if v.Name == val {
q = q.Where(" service = ?",k)
}
}
case "type":
q = q.Where(" type = ?",val)
}
}
q = q.Order("id ASC ").Find(&downtime)
return &downtime, q.Error()
}
func (c *Downtime) Create() error {
q := db.Create(c)
return q.Error()