doubushi0031 2019-09-13 02:15
浏览 32
已采纳

如何从数据存储中获取名称/密钥

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?

  • 写回答

2条回答 默认 最新

  • dpp66953 2019-09-13 02:48
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog