diff options
Diffstat (limited to 'repository')
-rw-r--r-- | repository/node.go | 58 | ||||
-rw-r--r-- | repository/user.go | 54 |
2 files changed, 112 insertions, 0 deletions
diff --git a/repository/node.go b/repository/node.go new file mode 100644 index 0000000..d5794b6 --- /dev/null +++ b/repository/node.go @@ -0,0 +1,58 @@ +package repository + +import ( + "context" + + "github.com/uptrace/bun" + "gitrepo.ru/neonxp/gorum/models" +) + +type Node struct { + db *bun.DB +} + +func NewNode(db *bun.DB) *Node { + return &Node{ + db: db, + } +} + +func (t *Node) Create( + ctx context.Context, + ntype models.NodeType, + text string, + authorID int, + parentID int, +) (int, error) { + post := &models.Node{ + Type: ntype, + Text: text, + AuthorID: authorID, + ParentID: parentID, + } + _, err := t.db.NewInsert().Model(post).Returning("id").Exec(ctx) + + return post.ID, err +} + +func (t *Node) Get(ctx context.Context, topicID int) (*models.Node, error) { + node := new(models.Node) + + return node, t.db.NewSelect(). + Model(node). + Where(`n.id = ?`, topicID). + Relation("Author"). + Scan(ctx) +} + +func (t *Node) List(ctx context.Context, topicID int) ([]*models.Node, int, error) { + posts := make([]*models.Node, 0) + + count, err := t.db.NewSelect(). + Model(&posts). + Where(`parent_id = ?`, topicID). + Relation("Author"). + ScanAndCount(ctx) + + return posts, count, err +} diff --git a/repository/user.go b/repository/user.go new file mode 100644 index 0000000..ec3b702 --- /dev/null +++ b/repository/user.go @@ -0,0 +1,54 @@ +package repository + +import ( + "context" + "fmt" + + "github.com/uptrace/bun" + "gitrepo.ru/neonxp/gorum/models" + "golang.org/x/crypto/bcrypt" +) + +type User struct { + db *bun.DB +} + +func NewUser(db *bun.DB) *User { + return &User{ + db: db, + } +} + +func (u *User) Create(ctx context.Context, email, password, username string) (int, error) { + + hpassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost) + if err != nil { + return 0, models.ErrInvalidPassword + } + + user := &models.User{ + Email: email, + Password: string(hpassword), + Username: username, + } + + if _, err := u.db.NewInsert().Model(user).Returning("id").Exec(ctx); err != nil { + return 0, models.ErrUserAlreadyExists + } + + return user.ID, nil +} + +func (u *User) Login(ctx context.Context, email, password string) (*models.User, error) { + user := new(models.User) + + if err := u.db.NewSelect().Model(user).Where("email = ?", email).Scan(ctx); err != nil { + return nil, fmt.Errorf("user not found: %w", models.ErrInvalidUserOrPassword) + } + + if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password)); err != nil { + return nil, fmt.Errorf("invalid password: %w", models.ErrInvalidUserOrPassword) + } + + return user, nil +} |