How to retrieve key object from datastore returned object

孤者浪人 提交于 2020-02-03 02:14:06

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!