homebox/backend/internal/repo/repo_users.go

84 lines
1.8 KiB
Go
Raw Normal View History

2022-08-30 02:30:36 +00:00
package repo
import (
"context"
"github.com/google/uuid"
"github.com/hay-kot/homebox/backend/ent"
"github.com/hay-kot/homebox/backend/ent/user"
"github.com/hay-kot/homebox/backend/internal/types"
2022-08-30 02:30:36 +00:00
)
type UserRepository struct {
2022-08-30 02:30:36 +00:00
db *ent.Client
}
func (e *UserRepository) GetOneId(ctx context.Context, id uuid.UUID) (*ent.User, error) {
2022-09-04 02:42:03 +00:00
return e.db.User.Query().
Where(user.ID(id)).
WithGroup().
Only(ctx)
2022-08-30 02:30:36 +00:00
}
func (e *UserRepository) GetOneEmail(ctx context.Context, email string) (*ent.User, error) {
2022-09-04 02:42:03 +00:00
return e.db.User.Query().
Where(user.Email(email)).
WithGroup().
Only(ctx)
2022-08-30 02:30:36 +00:00
}
func (e *UserRepository) GetAll(ctx context.Context) ([]*ent.User, error) {
2022-09-04 03:17:56 +00:00
return e.db.User.Query().WithGroup().All(ctx)
2022-08-30 02:30:36 +00:00
}
func (e *UserRepository) Create(ctx context.Context, usr types.UserCreate) (*ent.User, error) {
2022-08-30 02:30:36 +00:00
err := usr.Validate()
if err != nil {
2022-08-30 18:05:11 +00:00
return &ent.User{}, err
2022-08-30 02:30:36 +00:00
}
entUser, err := e.db.User.
Create().
SetName(usr.Name).
SetEmail(usr.Email).
SetPassword(usr.Password).
SetIsSuperuser(usr.IsSuperuser).
2022-08-30 18:05:11 +00:00
SetGroupID(usr.GroupID).
2022-08-30 02:30:36 +00:00
Save(ctx)
2022-09-04 02:42:03 +00:00
if err != nil {
return entUser, err
}
return e.GetOneId(ctx, entUser.ID)
2022-08-30 02:30:36 +00:00
}
func (e *UserRepository) Update(ctx context.Context, ID uuid.UUID, data types.UserUpdate) error {
q := e.db.User.Update().
Where(user.ID(ID)).
SetName(data.Name).
SetEmail(data.Email)
2022-08-30 02:30:36 +00:00
_, err := q.Save(ctx)
2022-08-30 02:30:36 +00:00
return err
}
func (e *UserRepository) Delete(ctx context.Context, id uuid.UUID) error {
2022-08-30 02:30:36 +00:00
_, err := e.db.User.Delete().Where(user.ID(id)).Exec(ctx)
return err
}
func (e *UserRepository) DeleteAll(ctx context.Context) error {
2022-08-30 02:30:36 +00:00
_, err := e.db.User.Delete().Exec(ctx)
return err
}
func (e *UserRepository) GetSuperusers(ctx context.Context) ([]*ent.User, error) {
2022-08-30 02:30:36 +00:00
users, err := e.db.User.Query().Where(user.IsSuperuser(true)).All(ctx)
if err != nil {
return nil, err
}
2022-08-30 18:05:11 +00:00
return users, nil
2022-08-30 02:30:36 +00:00
}