Skip to content

Instantly share code, notes, and snippets.

@timakin
Created December 2, 2018 06:22
Show Gist options
  • Save timakin/75355fab08b0052a7dbacbe035097eb4 to your computer and use it in GitHub Desktop.
Save timakin/75355fab08b0052a7dbacbe035097eb4 to your computer and use it in GitHub Desktop.
func (repo videoRepository) getVideosByPublishedAt(ctx context.Context, so *entity.SearchOptions) ([]*entity.Video, string, error) {
g, err := infrastructure.BoomFromContext(ctx)
if err != nil {
return nil, "", err
}
query := g.Client.NewQuery("Video").Filter("Enabled = ", true).Limit(so.Paging.Limit).Order("-PublishedAt").KeysOnly()
if so.Paging.Cursor != "" {
cursor, err := g.DecodeCursor(so.Paging.Cursor)
if err != nil {
return nil, "", err
}
query = query.Start(cursor)
}
co, err := g.Count(query)
if co == 0 || err != nil {
return nil, "", err
}
var keys []datastore.Key
var ierr error
it := g.Run(query)
for {
key, err := it.Next(nil)
if err != nil {
ierr = err
break
}
keys = append(keys, key)
}
if ierr != iterator.Done {
return nil, "", ierr
}
// Get the cursor for the next page of results.
nc, err := it.Cursor()
if err != nil {
return nil, "", err
}
var vIDs []int64
for _, k := range keys {
vIDs = append(vIDs, k.ID())
}
vs, err := repo.GetVideosByIDs(ctx, vIDs)
if err != nil {
return nil, "", err
}
return vs, nc.String(), nil
}
func (repo videoRepository) GetVideosByIDs(ctx context.Context, vIDs []int64) ([]*entity.Video, error) {
var vs []*entity.Video
g, err := infrastructure.BoomFromContext(ctx)
if err != nil {
return nil, err
}
for i := range vIDs {
vID := vIDs[i]
vs = append(vs, &entity.Video{
ID: vID,
})
}
if err := g.GetMulti(vs); err != nil {
mErr, ok := err.(datastore.MultiError)
if !ok {
return nil, err
}
var missingIndexes []int
for i, e := range mErr {
if e == nil {
continue
}
if e == datastore.ErrNoSuchEntity {
missingIndexes = append(missingIndexes, i)
continue
} else {
return nil, err
}
}
subvs := []*entity.Video{}
for i, v := range vs {
if isIDxInSlice(i, missingIndexes) {
continue
}
if !v.Enabled {
continue
}
subvs = append(subvs, v)
}
vs = subvs
}
return vs, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment