package com.remy.graphql.resolvers.dataloader;

import com.remy.common.module.GoodsDTO;
import com.remy.common.module.OrderDTO;
import com.remy.common.module.UserDTO;
import graphql.kickstart.execution.context.GraphQLContext;
import graphql.kickstart.tools.GraphQLResolver;
import graphql.schema.DataFetchingEnvironment;
import org.dataloader.DataLoader;
import org.dataloader.DataLoaderRegistry;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.CompletableFuture;

@Component
public class GoodsDataLoaderResolver implements GraphQLResolver<GoodsDTO> {

    public CompletableFuture<List<OrderDTO>> orders(GoodsDTO goodsDTO, DataFetchingEnvironment env){
        DataLoaderRegistry registry = ((GraphQLContext) env.getContext()).getDataLoaderRegistry();
        DataLoader<String, List<OrderDTO>> orderGoodsDataLoader = registry.getDataLoader("orderGoodsDataLoader");
        if (orderGoodsDataLoader != null) {
            return orderGoodsDataLoader.load(goodsDTO.getSerialNo());
        }
        throw new IllegalStateException("No order data loader found");
    }
}
