oc-lib/models/utils/abstracts.go
2024-07-19 11:27:58 +02:00

73 lines
2.1 KiB
Go

package utils
import (
"cloud.o-forge.io/core/oc-lib/dbs/mongo"
"cloud.o-forge.io/core/oc-lib/logs"
"github.com/go-playground/validator/v10"
"github.com/google/uuid"
"github.com/rs/zerolog"
)
var validate = validator.New(validator.WithRequiredStructEnabled())
type AbstractObject struct {
UUID string `json:"id" required:"true" bson:"_id" validate:"required"`
Name string `json:"name" required:"true" bson:"name" validate:"required"`
}
func (r *AbstractObject) GenerateID() {
r.UUID = uuid.New().String()
}
type AbstractAccessor struct {
Logger zerolog.Logger
Type string
}
func (dma *AbstractAccessor) GetType() string {
return dma.Type
}
func (dma *AbstractAccessor) SetLogger(t DataType) {
dma.Logger = logs.CreateLogger(t.String(), "")
dma.Type = t.String()
}
func (wfa *AbstractAccessor) GenericStoreOne(data DBObject, accessor Accessor) (DBObject, int, error) {
data.GenerateID()
err := validate.Struct(data)
wfa.Logger.Error().Msg("Could not store " + data.GetName() + " to db. Error: " + err.Error())
if err != nil {
return nil, 422, err
}
id, code, err := mongo.MONGOService.StoreOne(data, wfa.GetType())
if err != nil {
wfa.Logger.Error().Msg("Could not store " + data.GetName() + " to db. Error: " + err.Error())
return nil, code, err
}
return accessor.LoadOne(id)
}
func (dma *AbstractAccessor) GenericDeleteOne(id string, accessor Accessor) (DBObject, int, error) {
res, code, err := accessor.LoadOne(id)
if err != nil {
dma.Logger.Error().Msg("Could not retrieve " + id + " to db. Error: " + err.Error())
return nil, code, err
}
_, code, err = mongo.MONGOService.DeleteOne(id, accessor.GetType())
if err != nil {
dma.Logger.Error().Msg("Could not delete " + id + " to db. Error: " + err.Error())
return nil, code, err
}
return res, 200, nil
}
func (dma *AbstractAccessor) GenericUpdateOne(set map[string]interface{}, id string, accessor Accessor) (DBObject, int, error) {
id, code, err := mongo.MONGOService.UpdateOne(set, id, accessor.GetType())
if err != nil {
dma.Logger.Error().Msg("Could not update " + id + " to db. Error: " + err.Error())
return nil, code, err
}
return accessor.LoadOne(id)
}