Em Ae
Em Ae

Reputation: 8704

How to read custom types from datastore

I have a datastore table, which is like that

Name/ID  |  UserEmail  |  UserRole  |  UserPermissions 
------------------------------------------------------

The UserRole attribute in json is a string. However, in Go code, it's a type

type UserDetails struct {
    NameID string
    UserEmail string
    UserRole UserType
    UserPermissions string //json??
}

type UserType string

const (
    UnknownUserRole UserType = "UNKNOWN"
    SiteAdmin       UserType = "SITE_ADMIN"
    SiteHR UserType = "SITE_HR"
)

func (ut *UserType) String() string {
    return string(*ut)
}

func UserTypeFromString(userType string) UserType {
    switch userType {
    case "SITE_ADMIN":
        return SiteAdmin
    case "SITE_HR":
        return SiteHR
    default:
        return UnknownRole
    }
}

Now, I have to read all users for given org. I am using this code to do so

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
}

How can i read UserType from datastore using above code into UserDetails.UserType enum?

Upvotes: 0

Views: 223

Answers (3)

Brandon Jones
Brandon Jones

Reputation: 11

The code in the question works as is. There's no need to implement PropertyLoadSaver or loop over returned entities as suggested in other answers.

The custom data type is a string. The datastore package marshals all string types to and from datastore strings. It just works.

Upvotes: 1

Siva
Siva

Reputation: 1148

If you make your struct implement PropertyLoadSaver interface

https://godoc.org/cloud.google.com/go/datastore#hdr-The_PropertyLoadSaver_Interface

then you can handle these special requirements. You wouldn't have to remember to post process with every get/query.

Upvotes: 0

Burak Serdar
Burak Serdar

Reputation: 51497

What you're essentially doing with UserType is that you have two valid values, and you're mapping all other values to a common unknown value. The following should work:

for i, key := range keys {
        userDetails[i].NameID = key.Name
        userDetails[i].UserRole = UserTypeFromString( string(userDetails[i].UserRole))
}

Upvotes: 0

Related Questions