Search code examples
gogoogle-cloud-platformgoogle-cloud-datastore

how to fetch name/key in from datastore


Couldn't find any existing Go specific answer so creating a new one.

Our datastore consist of following columns/attributes

Name/ID Email UserID UserName

Now, I want to retrieve these values into my Go struct. Here is what i have written

type UserDetails struct {
    NameID    string
    Email     string `datastore:"Email"`
    UserID    string `datastore:"UserID"`
    UserName  string `datastore:UserName`
}

Now, when i am fetching this entity (based on kind), I am manually setting the NameID i.e.,

func (c DataStoreClient) GetUserDetailsByOrg(ctx context.Context, orgName string) ([]*UserDetails, error) {
    var userDetails []*UserDetails
    q := datastore.NewQuery(userDetailsKind).
        Namespace(orgName)
    keys, err := c.client.GetAll(ctx, q, &userDetails)
    for i, key := range keys {
        userDetails[i].NameID = key.Name
    }
    return userDetails, err
}

Now, the question that i want to ask that is this the correct approach to retrieve Name/ID or can i retrieve it by specifying datastore:Name/ID in struct?


Solution

  • Implement the KeyLoader interface to set the field during entity load.

    type UserDetails struct {
        NameID   string `datastore:"-"`
        Email    string `datastore:"Email"`
        UserID   string `datastore:"UserID"`
        UserName string `datastore:UserName`
    }
    
    func (ud *UserDetails) LoadKey(k *datastore.Key) error {
        ud.NameID = k.Name
        return nil
    }
    
    func (ud *UserDetails) Load(ps []datastore.Property) error {
        return datastore.LoadStruct(ud, ps)
    }
    
    func (ud *UserDetails) Save() ([]datastore.Property, error) {
        return datastore.SaveStruct(ud)
    }
    

    Use it like this:

    func (c DataStoreClient) GetUserDetailsByOrg(ctx context.Context, orgName string) ([]*UserDetails, error) {
        var userDetails []*UserDetails
        q := datastore.NewQuery(userDetailsKind).
            Namespace(orgName)
        _, err := c.client.GetAll(ctx, q, &userDetails)
        return userDetails, err
    }
    

    The approach in the question works. The advantage of the KeyLoader implementation is that it saves a couple of lines of code wherever the application queries for or gets an entity.

    Set the NameID datastore name to "-" so that the property loader and saver ignores the field.