问题
Here is a method, which retrieves all orders for given order id of the user
func (r *DatastoreRepository) FindOrders(ctx context.Context, userID string, orderIDs []string) ([]*domain.Order, interface{}) {
keys := make([]*datastore.Key, len(orderIDs))
for i, orderID := range orderIDs {
key := datastore.NameKey(kindOrder, orderID, nil)
key.Namespace = userID
keys[i] = key
}
orders := make([]*domain.Order, len(keys))
multiErrors := r.client.GetMulti(ctx, keys, orders)
return orders, multiErrors
}
This method returns *[]domain.Order
to my service method. Now service method wants to get access key
object of a given order (in order to delete an order). One way to do it is re-create key for every order based on order id but this sounds like a code redundancy (i am doing it in FindOrders
as well and would have to do it in DeleteOrders
as well). Is there a way that i can access datastore.key
object for a given order from order object
?
回答1:
Assuming that an Order
has an ID
field, simply loop over the elements and set the field.
func (r *DatastoreRepository) FindOrders(ctx context.Context, userID string, orderIDs []string) ([]*domain.Order, interface{}) {
keys := make([]*datastore.Key, len(orderIDs))
for i, orderID := range orderIDs {
key := datastore.NameKey(kindOrder, orderID, nil)
key.Namespace = userID
keys[i] = key
}
orders := make([]*domain.Order, len(keys))
multiErrors := r.client.GetMulti(ctx, keys, orders)
// Add this for loop...
for i, order := range orders {
order.ID = orderIDs[i]
}
return orders, multiErrors
}
来源:https://stackoverflow.com/questions/59901038/how-to-retrieve-key-object-from-datastore-returned-object