package com.remy.graphql.resolvers.dataloader;

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 UserDataLoaderResolver implements GraphQLResolver<UserDTO> {

    public CompletableFuture<List<OrderDTO>> orders(UserDTO userDTO, DataFetchingEnvironment env) {
        DataLoaderRegistry registry = ((GraphQLContext) env.getContext()).getDataLoaderRegistry();
        DataLoader<Long, List<OrderDTO>> orderUserDataLoader = registry.getDataLoader("orderUserDataLoader");
        if (orderUserDataLoader != null) {
            return orderUserDataLoader.load(userDTO.getId());
        }
        throw new IllegalStateException("No goods data loader found");
    }

}
