2fas-server/internal/api/icons/app/queries/web_service.go

93 lines
2.2 KiB
Go
Raw Normal View History

2022-12-31 10:22:38 +01:00
package queries
import (
"errors"
2022-12-31 10:22:38 +01:00
"github.com/doug-martin/goqu/v9"
"gorm.io/datatypes"
"gorm.io/gorm"
"github.com/twofas/2fas-server/internal/api/icons/adapters"
"github.com/twofas/2fas-server/internal/common/db"
2022-12-31 10:22:38 +01:00
)
type WebServicePresenter struct {
Id string `json:"id"`
Name string `json:"name"`
Description string `json:"description"`
Issuers datatypes.JSON `json:"issuers"`
Tags datatypes.JSON `json:"tags"`
IconsCollections datatypes.JSON `json:"icons_collections"`
MatchRules datatypes.JSON `json:"match_rules"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
}
type WebServiceQuery struct {
Id string `uri:"service_id" validate:"omitempty,uuid4"`
Search string `uri:"search" validate:"omitempty,max=128"`
}
type WebServiceQueryHandler struct {
Database *gorm.DB
Qb *goqu.Database
}
func (h *WebServiceQueryHandler) FindOne(query *WebServiceQuery) (*WebServicePresenter, error) {
ds := h.Qb.From("web_services")
ds = ds.Where(
goqu.C("id").Eq(query.Id),
goqu.C("deleted_at").IsNull(),
)
sql, _, err := ds.ToSQL()
if err != nil {
return nil, db.QueryPrepError(err)
}
2022-12-31 10:22:38 +01:00
presenter := &WebServicePresenter{}
result := h.Database.Raw(sql).First(&presenter)
if result.Error != nil {
if errors.Is(result.Error, gorm.ErrRecordNotFound) {
return nil, adapters.WebServiceCouldNotBeFound{Identifier: query.Id}
}
return nil, db.WrapError(err)
2022-12-31 10:22:38 +01:00
}
return presenter, nil
}
func (h *WebServiceQueryHandler) FindAll(query *WebServiceQuery) ([]*WebServicePresenter, error) {
var presenter []*WebServicePresenter
ds := h.Qb.From("web_services")
ds = ds.Where(goqu.And(
goqu.C("deleted_at").IsNull(),
))
if query.Search != "" {
ds.Where(
goqu.Or(
goqu.C("name").Eq(query.Search),
goqu.L(`JSON_CONTAINS('tags', '`+query.Search+`', '$')`),
goqu.L(`JSON_CONTAINS('issuers', '`+query.Search+`', '$')`),
),
)
}
sql, _, err := ds.ToSQL()
if err != nil {
return nil, db.QueryPrepError(err)
}
2022-12-31 10:22:38 +01:00
result := h.Database.Raw(sql).Find(&presenter)
if err := result.Error; err != nil {
return nil, db.WrapError(err)
}
2022-12-31 10:22:38 +01:00
return presenter, nil
}