Skip to content

Instantly share code, notes, and snippets.

@syafdia
Last active August 15, 2021 15:11
Show Gist options
  • Save syafdia/27212afd45e8cc0a30b4edc7d9ea4dc0 to your computer and use it in GitHub Desktop.
Save syafdia/27212afd45e8cc0a30b4edc7d9ea4dc0 to your computer and use it in GitHub Desktop.
// internal/user/repo.go
package user
import (
"context"
"github.com/jmoiron/sqlx"
)
type UserRepo interface {
Create(ctx context.Context, input CreateUserInput) (User, error)
Update(ctx context.Context, input UpdateUserInput) (User, error)
FindOneByID(ctx context.Context, id int64) (User, error)
Destroy(ctx context.Context, id int64) error
}
type userRepo struct {
db *sqlx.DB
}
func NewUserRepo(db *sqlx.DB) UserRepo {
return &userRepo{db: db}
}
func (u *userRepo) Create(ctx context.Context, input CreateUserInput) (User, error) {
result, err := u.db.ExecContext(ctx,
`INSERT INTO users (email, first_name, last_name, gender) VALUES ($1, $2, $3, $4);`,
input.Email,
input.FirstName,
input.LastName,
input.Gender)
if err != nil {
return User{}, nil
}
userID, err := result.LastInsertId()
if err != nil {
return User{}, err
}
return User{
ID: userID,
Email: input.Email,
FirstName: input.FirstName,
LastName: input.LastName,
Gender: input.Gender,
}, nil
}
// The others implementation
// ...
// ...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment