thread-master/backend/internal/model/publish_guard/repository/mongo.go

84 lines
2.6 KiB
Go
Raw Normal View History

2026-06-30 09:10:23 +00:00
package repository
import (
"context"
"strings"
app "haixun-backend/internal/library/errors"
"haixun-backend/internal/library/errors/code"
"haixun-backend/internal/model/publish_guard/domain/entity"
domrepo "haixun-backend/internal/model/publish_guard/domain/repository"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
type mongoRepository struct {
collection *mongo.Collection
}
func NewMongoRepository(db *mongo.Database) domrepo.Repository {
if db == nil {
return &mongoRepository{}
}
return &mongoRepository{collection: db.Collection(entity.CollectionName)}
}
func (r *mongoRepository) EnsureIndexes(ctx context.Context) error {
if r.collection == nil {
return nil
}
_, err := r.collection.Indexes().CreateOne(ctx, mongo.IndexModel{
Keys: bson.D{{Key: "tenant_id", Value: 1}, {Key: "owner_uid", Value: 1}, {Key: "account_id", Value: 1}},
Options: options.Index().SetUnique(true),
})
return err
}
func (r *mongoRepository) Get(ctx context.Context, tenantID, ownerUID, accountID string) (*entity.Policy, error) {
if r.collection == nil {
return nil, app.For(code.ThreadsAccount).DBUnavailable("Mongo is not configured")
}
var out entity.Policy
err := r.collection.FindOne(ctx, actorFilter(tenantID, ownerUID, accountID)).Decode(&out)
if err != nil {
if err == mongo.ErrNoDocuments {
return nil, app.For(code.ThreadsAccount).ResNotFound("publish guard policy not found")
}
return nil, err
}
return &out, nil
}
func (r *mongoRepository) Upsert(ctx context.Context, policy *entity.Policy) (*entity.Policy, error) {
if r.collection == nil {
return nil, app.For(code.ThreadsAccount).DBUnavailable("Mongo is not configured")
}
if policy == nil {
return nil, app.For(code.ThreadsAccount).InputMissingRequired("policy is required")
}
opts := options.Replace().SetUpsert(true)
_, err := r.collection.ReplaceOne(ctx, actorFilter(policy.TenantID, policy.OwnerUID, policy.AccountID), policy, opts)
if err != nil {
return nil, err
}
return policy, nil
}
func (r *mongoRepository) DeleteByAccount(ctx context.Context, tenantID, ownerUID, accountID string) error {
if r.collection == nil {
return app.For(code.ThreadsAccount).DBUnavailable("Mongo is not configured")
}
_, err := r.collection.DeleteOne(ctx, actorFilter(tenantID, ownerUID, accountID))
return err
}
func actorFilter(tenantID, ownerUID, accountID string) bson.M {
return bson.M{
"tenant_id": strings.TrimSpace(tenantID),
"owner_uid": strings.TrimSpace(ownerUID),
"account_id": strings.TrimSpace(accountID),
}
}