如何从数据存储区返回的对象中检索关键对象

如何从数据存储区返回的对象中检索关键对象

本文介绍了如何从数据存储区返回的对象中检索关键对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一种方法,该方法可以检索用户给定订单ID的所有订单

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
}

此方法将 * [] domain.Order 返回给我的服务方法.现在服务方法想要获取给定订单的访问 key 对象(以删除订单).一种方法是根据订单ID为每个订单重新创建密钥,但这听起来像是代码冗余(我也在 FindOrders 中这样做,因此也必须在中这样做以及DeleteOrders ).有没有一种方法可以从 order object 中访问给定订单的 datastore.key 对象?

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?

推荐答案

假设 Order 具有一个 ID 字段,只需在元素上循环并设置该字段即可.

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
}

这篇关于如何从数据存储区返回的对象中检索关键对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 20:08