stufflog graphql server
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

99 lines
2.2 KiB

package mysqldriver
import (
"context"
"database/sql"
"errors"
"git.aiterp.net/stufflog/server/internal/slerrors"
"git.aiterp.net/stufflog/server/models"
sq "github.com/Masterminds/squirrel"
"github.com/jmoiron/sqlx"
)
type userRepository struct {
db *sqlx.DB
}
func (r *userRepository) Find(ctx context.Context, id string) (*models.User, error) {
user := models.User{}
err := r.db.GetContext(ctx, &user, "SELECT * FROM user WHERE user_id=?", id)
if err != nil {
if err == sql.ErrNoRows {
return nil, slerrors.NotFound("User")
}
return nil, err
}
return &user, nil
}
func (r *userRepository) List(ctx context.Context, filter models.UserFilter) ([]*models.User, error) {
q := sq.Select("user.*").From("user").OrderBy("user_id")
if len(filter.UserIDs) > 0 {
q = q.Where(sq.Eq{"user_id": filter.UserIDs})
}
if filter.Active != nil {
q = q.Where(sq.Eq{"active": *filter.Active})
}
if filter.Admin != nil {
q = q.Where(sq.Eq{"admin": *filter.Admin})
}
if filter.Limit != nil && *filter.Limit > 0 {
q = q.Limit(uint64(*filter.Limit))
}
query, args, err := q.ToSql()
if err != nil {
return nil, err
}
results := make([]*models.User, 0, 16)
err = r.db.SelectContext(ctx, &results, query, args...)
if err != nil {
if err == sql.ErrNoRows {
return []*models.User{}, nil
}
return nil, err
}
return results, nil
}
func (r *userRepository) Insert(ctx context.Context, user models.User) (*models.User, error) {
if len(user.Name) < 1 || len([]byte(user.Name)) > 32 {
return nil, errors.New("user id is not valid")
}
_, err := r.db.NamedExecContext(ctx, `
INSERT INTO user (
user_id, name, active, admin, hash
) VALUES (
:user_id, :name, :active, :admin, :hash
)
`, user)
if err != nil {
return nil, err
}
return &user, nil
}
func (r *userRepository) Save(ctx context.Context, user models.User) error {
_, err := r.db.NamedExecContext(ctx, `
UPDATE user
SET name=:name,
hash=:hash,
admin=:admin,
active=:active
WHERE user_id=:user_id
`, user)
return err
}
func (r *userRepository) Delete(ctx context.Context, user models.User) error {
_, err := r.db.ExecContext(ctx, "DELETE FROM user WHERE user_id=?", user.ID)
return err
}