generated from PenaSide/GolangTemplate
86 lines
2.1 KiB
Go
86 lines
2.1 KiB
Go
![]() |
package repository
|
||
|
|
||
|
import (
|
||
|
"context"
|
||
|
"fmt"
|
||
|
"log"
|
||
|
"time"
|
||
|
|
||
|
"go.mongodb.org/mongo-driver/bson"
|
||
|
"go.mongodb.org/mongo-driver/bson/primitive"
|
||
|
"go.mongodb.org/mongo-driver/mongo"
|
||
|
"go.uber.org/zap"
|
||
|
"penahub.gitlab.yandexcloud.net/pena-services/customer/internal/errors"
|
||
|
"penahub.gitlab.yandexcloud.net/pena-services/customer/internal/fields"
|
||
|
"penahub.gitlab.yandexcloud.net/pena-services/customer/internal/models"
|
||
|
)
|
||
|
|
||
|
type HistoryRepositoryDeps struct {
|
||
|
Logger *zap.Logger
|
||
|
MongoDB *mongo.Collection
|
||
|
}
|
||
|
|
||
|
type HistoryRepository struct {
|
||
|
logger *zap.Logger
|
||
|
mongoDB *mongo.Collection
|
||
|
}
|
||
|
|
||
|
func NewHistoryRepository(deps *HistoryRepositoryDeps) *HistoryRepository {
|
||
|
if deps == nil {
|
||
|
log.Panicln("deps is nil on <NewHistoryRepository>")
|
||
|
}
|
||
|
|
||
|
if deps.Logger == nil {
|
||
|
log.Panicln("logger is nil on <NewHistoryRepository>")
|
||
|
}
|
||
|
|
||
|
if deps.MongoDB == nil {
|
||
|
log.Panicln("mongodb is nil on <NewHistoryRepository>")
|
||
|
}
|
||
|
|
||
|
return &HistoryRepository{
|
||
|
logger: deps.Logger,
|
||
|
mongoDB: deps.MongoDB,
|
||
|
}
|
||
|
}
|
||
|
|
||
|
func (receiver *HistoryRepository) Insert(ctx context.Context, history *models.History) (*models.History, errors.Error) {
|
||
|
history.CreatedAt = time.Now()
|
||
|
history.UpdatedAt = time.Now()
|
||
|
history.Deleted = false
|
||
|
|
||
|
result, err := receiver.mongoDB.InsertOne(ctx, history)
|
||
|
if err != nil {
|
||
|
receiver.logger.Error("failed to insert history on <Insert> of <HistoryRepository>",
|
||
|
zap.Any("history", history),
|
||
|
zap.Error(err),
|
||
|
)
|
||
|
|
||
|
return nil, errors.New(
|
||
|
fmt.Errorf("failed to insert history on <Insert> of <HistoryRepository>: %w", err),
|
||
|
errors.ErrInternalError,
|
||
|
)
|
||
|
}
|
||
|
|
||
|
insertedID := result.InsertedID.(primitive.ObjectID).Hex()
|
||
|
history.ID = insertedID
|
||
|
|
||
|
return history, nil
|
||
|
}
|
||
|
|
||
|
func (receiver *HistoryRepository) CountAll(ctx context.Context) (int64, errors.Error) {
|
||
|
count, err := receiver.mongoDB.CountDocuments(ctx, bson.M{fields.History.Deleted: false})
|
||
|
if err != nil {
|
||
|
receiver.logger.Error("failed to count all documents on <CountAll> of <HistoryRepository>",
|
||
|
zap.Error(err),
|
||
|
)
|
||
|
|
||
|
return 0, errors.New(
|
||
|
fmt.Errorf("failed to count all documents on <CountAll> of <HistoryRepository>: %w", err),
|
||
|
errors.ErrInternalError,
|
||
|
)
|
||
|
}
|
||
|
|
||
|
return count, nil
|
||
|
}
|