oc-lib/models/utils/abstracts.go

51 lines
1.4 KiB
Go
Raw Normal View History

2024-07-18 11:51:12 +02:00
package utils
import (
2024-07-18 13:35:14 +02:00
"cloud.o-forge.io/core/oc-lib/dbs/mongo"
"cloud.o-forge.io/core/oc-lib/logs"
2024-07-18 16:46:54 +02:00
"cloud.o-forge.io/core/oc-lib/models/resources"
2024-07-18 18:14:12 +02:00
"github.com/go-playground/validator/v10"
2024-07-18 11:51:12 +02:00
"github.com/rs/zerolog"
)
2024-07-18 18:14:12 +02:00
var validate = validator.New(validator.WithRequiredStructEnabled())
2024-07-18 11:51:12 +02:00
type AbstractAccessor struct {
Logger zerolog.Logger
2024-07-18 16:46:54 +02:00
Type string
2024-07-18 11:51:12 +02:00
}
2024-07-18 16:46:54 +02:00
func (dma *AbstractAccessor) GetType() string {
return dma.Type
}
2024-07-18 18:14:12 +02:00
func (dma *AbstractAccessor) Validate(d DBObject) error {
return validate.Struct(d)
}
2024-07-18 16:46:54 +02:00
func (dma *AbstractAccessor) SetLogger(t resources.ResourceType) {
2024-07-18 17:55:27 +02:00
dma.Logger = logs.CreateLogger(t.String(), "")
2024-07-18 16:46:54 +02:00
dma.Type = t.String()
2024-07-18 11:51:12 +02:00
}
2024-07-18 15:35:30 +02:00
func (dma *AbstractAccessor) GenericDeleteOne(id string, accessor Accessor) (DBObject, error) {
res, err := accessor.LoadOne(id)
if err != nil {
dma.Logger.Error().Msg("Could not retrieve " + id + " to db. Error: " + err.Error())
return nil, err
}
2024-07-18 16:46:54 +02:00
_, err = mongo.MONGOService.DeleteOne(id, accessor.GetType())
2024-07-18 11:51:12 +02:00
if err != nil {
dma.Logger.Error().Msg("Could not delete " + id + " to db. Error: " + err.Error())
2024-07-18 15:35:30 +02:00
return nil, err
2024-07-18 11:51:12 +02:00
}
2024-07-18 15:35:30 +02:00
return res, nil
2024-07-18 11:51:12 +02:00
}
2024-07-18 15:35:30 +02:00
func (dma *AbstractAccessor) GenericUpdateOne(set map[string]interface{}, id string, accessor Accessor) (DBObject, error) {
2024-07-18 16:46:54 +02:00
id, err := mongo.MONGOService.UpdateOne(set, id, accessor.GetType())
2024-07-18 11:51:12 +02:00
if err != nil {
dma.Logger.Error().Msg("Could not update " + id + " to db. Error: " + err.Error())
}
return accessor.LoadOne(id)
}