Skip to content

Instantly share code, notes, and snippets.

@unders
Created August 3, 2017 12:53
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 unders/05e6fe3e25c688a48beebb2491df3d83 to your computer and use it in GitHub Desktop.
Save unders/05e6fe3e25c688a48beebb2491df3d83 to your computer and use it in GitHub Desktop.
func (d *Datastore) GetStuff(userKey, currentAccountKey, defaultAccountKey *cdatastore.Key) (*data.User, error) {
errCh := make(chan error, 3)
retCh := make(chan bool, 2)
done := make(chan bool)
u := &dbdata.User{}
a := &data.Account{}
// Fetch user
go func() {
if err := d.DB.Read(userKey, u); err != nil {
const msg = "Read failed"
errCh <- errors.Wrap(err, msg)
return
}
retCh <- true
}()
// Fetch account
go func() {
var err error
if a, _, err = d.GetAccount(userKey, currentAccountKey); err == nil {
retCh <- true
return
}
if a, _, err = d.GetAccount(u.Key, defaultAccountKey); err != nil {
errCh <- errors.WithStack(err)
return
}
retCh <- true
if serr := d.setUsersCurrentAccountToDefault(userKey); serr != nil {
const msg = "setUsersCurrentAccountToDefault() failed"
d.LogError(errors.Wrapf(err, msg))
}
}()
// wait for the results
go func() {
timeout := time.After(4 * time.Second)
for i := 0; i < 2; i++ {
select {
case <-retCh:
case <-timeout:
const msg = "request took to long"
errCh <- errs.Expired(msg)
return
}
}
close(done)
}()
select {
case <-done:
return u.ToUser(a), nil
case err := <-errCh:
return nil, errors.WithStack(err)
}
}
@unders
Copy link
Author

unders commented Aug 3, 2017

No tested yet... only a scrapbook item

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment