From c04e382ee5f5b2b2a752969f1c00855e75f0e03b Mon Sep 17 00:00:00 2001 From: soxx Date: Fri, 14 Jun 2024 14:48:23 +0200 Subject: [PATCH] feat(postgres): added AddUserWithRelationToSource --- internal/postgres/user.go | 61 +++++++++++++++++++++++++++++++++++++++ pkg/database/postgres.go | 3 +- 2 files changed, 62 insertions(+), 2 deletions(-) create mode 100644 internal/postgres/user.go diff --git a/internal/postgres/user.go b/internal/postgres/user.go new file mode 100644 index 0000000..f24191d --- /dev/null +++ b/internal/postgres/user.go @@ -0,0 +1,61 @@ +package postgres + +import ( + "context" + "git.dragse.it/anthrove/otter-space-sdk/pkg/models" + "git.dragse.it/anthrove/otter-space-sdk/pkg/models/pgModels" + log "github.com/sirupsen/logrus" + "gorm.io/gorm" +) + +func CreateUserNodeWithSourceRelation(ctx context.Context, db *gorm.DB, anthroveUserID models.AnthroveUserID, sourceDomain string, userID string, username string) error { + user := pgModels.User{ + BaseModel: pgModels.BaseModel{ + ID: string(anthroveUserID), + }, + } + + if err := db.WithContext(ctx).FirstOrCreate(&user).Error; err != nil { + log.WithFields(log.Fields{ + "anthrove_user_id": anthroveUserID, + }).Error("database: failed to find or create user") + return err + } + + source := pgModels.Source{ + Domain: sourceDomain, + } + + if err := db.WithContext(ctx).Where(&source).First(&source).Error; err != nil { + log.WithFields(log.Fields{ + "source_domain": sourceDomain, + }).Error("database: failed to find source") + return err + } + + userSource := pgModels.UserSource{ + UserID: user.ID, + SourceID: source.ID, + AccountUsername: username, + AccountID: userID, + } + + if err := db.WithContext(ctx).Create(&userSource).Error; err != nil { + log.WithFields(log.Fields{ + "anthrove_user_id": anthroveUserID, + "source_domain": sourceDomain, + "account_username": username, + "account_id": userID, + }).Error("database: failed to create user-source relationship") + return err + } + + log.WithFields(log.Fields{ + "anthrove_user_id": anthroveUserID, + "source_domain": sourceDomain, + "account_username": username, + "account_id": userID, + }).Trace("database: created user-source relationship") + + return nil +} diff --git a/pkg/database/postgres.go b/pkg/database/postgres.go index a37c2e0..13fe10d 100644 --- a/pkg/database/postgres.go +++ b/pkg/database/postgres.go @@ -54,8 +54,7 @@ func (p *postgresqlConnection) Connect(_ context.Context, endpoint string, usern } func (p *postgresqlConnection) AddUserWithRelationToSource(ctx context.Context, anthroveUserID models.AnthroveUserID, sourceDomain string, userID string, username string) error { - //TODO implement me - panic("implement me") + return postgres.CreateUserNodeWithSourceRelation(ctx, p.db, anthroveUserID, userID, sourceDomain, userID) } func (p *postgresqlConnection) AddSource(ctx context.Context, anthroveSource *graphModels.AnthroveSource) error {