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.

57 lines
1.4 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 NewUserLoaderContext(ctx context.Context, userRepo repositories.UserRepository) context.Context {
  12. return context.WithValue(ctx, userLoaderCtxKey, NewUserLoader(ctx, userRepo))
  13. }
  14. func UserLoaderFromContext(ctx context.Context) *UserLoader {
  15. return ctx.Value(userLoaderCtxKey).(*UserLoader)
  16. }
  17. func NewUserLoader(ctx context.Context, userRepo repositories.UserRepository) *UserLoader {
  18. return &UserLoader{
  19. wait: 2 * time.Millisecond,
  20. maxBatch: 100,
  21. fetch: func(keys []string) ([]*models.User, []error) {
  22. results := make([]*models.User, len(keys))
  23. errors := make([]error, len(keys))
  24. users, err := userRepo.List(ctx, models.UserFilter{UserIDs: keys})
  25. if err != nil {
  26. for i := range errors {
  27. errors[i] = err
  28. }
  29. return results, errors
  30. }
  31. userMap := make(map[string]*models.User, len(users))
  32. for _, user := range users {
  33. userMap[user.ID] = user
  34. }
  35. for i, id := range keys {
  36. user := userMap[id]
  37. if user != nil {
  38. results[i] = user
  39. } else {
  40. errors[i] = slerrors.NotFound("User")
  41. }
  42. }
  43. return results, errors
  44. },
  45. }
  46. }