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.

53 lines
1.2 KiB

  1. package loaders
  2. import (
  3. "context"
  4. "git.aiterp.net/stufflog/server/database/repositories"
  5. "git.aiterp.net/stufflog/server/internal/slerrors"
  6. "git.aiterp.net/stufflog/server/models"
  7. "time"
  8. )
  9. // go run github.com/vektah/dataloaden UserLoader string *git.aiterp.net/stufflog/server/models.User
  10. var userLoaderCtxKey = "ctx.stufflog.UserLoader"
  11. func UserLoaderFromContext(ctx context.Context) *UserLoader {
  12. return ctx.Value(userLoaderCtxKey).(*UserLoader)
  13. }
  14. func NewUserLoader(ctx context.Context, userRepo repositories.UserRepository) *UserLoader {
  15. return &UserLoader{
  16. wait: time.Millisecond / 4,
  17. maxBatch: 4,
  18. fetch: func(keys []string) ([]*models.User, []error) {
  19. results := make([]*models.User, len(keys))
  20. errors := make([]error, len(keys))
  21. users, err := userRepo.List(ctx, models.UserFilter{UserIDs: keys})
  22. if err != nil {
  23. for i := range errors {
  24. errors[i] = err
  25. }
  26. return results, errors
  27. }
  28. userMap := make(map[string]*models.User, len(users))
  29. for _, user := range users {
  30. userMap[user.ID] = user
  31. }
  32. for i, id := range keys {
  33. user := userMap[id]
  34. if user != nil {
  35. results[i] = user
  36. } else {
  37. errors[i] = slerrors.NotFound("User")
  38. }
  39. }
  40. return results, errors
  41. },
  42. }
  43. }