DB640/internal/web/routes.go
2020-04-05 22:06:15 +02:00

65 lines
1.6 KiB
Go

package web
import (
"errors"
"net/http"
"git.1750studios.com/ToddShepard/DB640/internal/database"
"github.com/gin-gonic/gin"
"github.com/jinzhu/gorm"
"github.com/sahilm/fuzzy"
)
func getBetriebsstellen(c *gin.Context) {
var bs database.Betriebsstellen
name := c.DefaultQuery("name", "")
if name != "" {
var ordered []database.Betriebsstelle
if err := database.Db.Find(&bs, "name LIKE ?", "%"+name+"%").Error; err != nil {
if !errors.Is(err, gorm.ErrRecordNotFound) {
c.AbortWithError(http.StatusInternalServerError, err)
return
}
if len(bs) == 0 {
c.AbortWithError(http.StatusNotFound, err)
return
}
}
results := fuzzy.FindFrom(name, bs)
for i, r := range results {
ordered = append(ordered, bs[r.Index])
if i == 49 {
break
}
}
c.JSON(http.StatusOK, ordered)
return
}
if err := database.Db.Limit(c.DefaultQuery("limit", "50")).Offset(c.DefaultQuery("offset", "0")).Find(&bs).Error; err != nil {
if !errors.Is(err, gorm.ErrRecordNotFound) {
c.AbortWithError(http.StatusInternalServerError, err)
return
}
if len(bs) == 0 {
c.AbortWithError(http.StatusNotFound, err)
return
}
}
c.JSON(http.StatusOK, bs)
}
func getBetriebsstelleByCode(c *gin.Context) {
var bs database.Betriebsstelle
if err := database.Db.First(&bs, "code = ?", c.Param("code")).Error; err != nil {
if !errors.Is(err, gorm.ErrRecordNotFound) {
c.AbortWithError(http.StatusInternalServerError, err)
return
}
if err != nil {
c.AbortWithError(http.StatusNotFound, err)
return
}
}
c.JSON(http.StatusOK, bs)
}