Created
August 3, 2017 12:53
-
-
Save unders/05e6fe3e25c688a48beebb2491df3d83 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
No tested yet... only a scrapbook item