Skip to content

Instantly share code, notes, and snippets.

@fwojciec
Created January 20, 2020 16:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fwojciec/216d21bd43bd148574b62878885605be to your computer and use it in GitHub Desktop.
Save fwojciec/216d21bd43bd148574b62878885605be to your computer and use it in GitHub Desktop.
func newAuthorsByBookID(ctx context.Context, repo pg.Repository) *AuthorSliceLoader {
return NewAuthorSliceLoader(AuthorSliceLoaderConfig{
MaxBatch: 100,
Wait: 5 * time.Millisecond,
Fetch: func(bookIDs []int64) ([][]pg.Author, []error) {
// db query
res, err := repo.ListAuthorsByBookIDs(ctx, bookIDs)
if err != nil {
return nil, []error{err}
}
// group
groupByBookID := make(map[int64][]pg.Author, len(bookIDs))
for _, r := range res {
groupByBookID[r.BookID] = append(groupByBookID[r.BookID], pg.Author{
ID: r.ID,
Name: r.Name,
Website: r.Website,
AgentID: r.AgentID,
})
}
// order
result := make([][]pg.Author, len(bookIDs))
for i, bookID := range bookIDs {
result[i] = groupByBookID[bookID]
}
return result, nil
},
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment