Extend a Repository
To add methods to a repository that are not supported out of the box, embed the repository and implement your missing methods.
user.inmemoery.repository.go
package main
import (
"context"
"errors"
"fmt"
"github.com/go-arrower/arrower/repository"
)
type UserID int
type User struct {
ID UserID
Login string
}
func main() {
repo := NewUserMemoryRepository()
_, err := repo.FindByLogin(context.Background(), "hello@arrower.org")
if err != nil && !errors.Is(err, repository.ErrNotFound) {
panic(err)
}
}
func NewUserMemoryRepository() *UserMemoryRepository {
return &UserMemoryRepository{
MemoryRepository: repository.NewMemoryRepository[User, UserID](),
}
}
type UserMemoryRepository struct {
*repository.MemoryRepository[User, UserID]
}
// FindByLogin implements a custom method, that is not supported by the Repository out of the box.
func (repo *UserMemoryRepository) FindByLogin(ctx context.Context, login string) (User, error) {
all, err := repo.All(ctx)
if err != nil {
return User{}, fmt.Errorf("could not get users: %w", err)
}
for _, u := range all {
if u.Login == login {
return u, nil
}
}
return User{}, repository.ErrNotFound
}