Dataloader is using only recent context

109 views Asked by At

I have defined a custom context as below

@Component
public class MyContextBuilder implements DgsCustomContextBuilder<MyContexttBuilder.MyContext> {
    @Override
    public MyContext build() {
        return new MyContext();
    }

    public static class MyContext {
        private  String customState = "Custom CID!";

        public String getCustomState() {
            return customState;
        }
        public void setCustomState(String state) {
            customState = state;
        }
    }

}

Datafetcher:

    @DgsData(
            parentType = DgsConstants.SOMEOBJ.TYPE_NAME,
            field = DgsConstants.SOMEOBJ.Name)
    public CompletableFuture<String> getMyInfo(
            @RequestHeader(value = "cid", required = false) String customId,
            DgsDataFetchingEnvironment dfe) {
        final DataLoader<String, String> dataLoader =
                dfe.getDataLoader("my_dataloader");
        log.warn("calledget getMyInfo");
        final SomeObj obj = dfe.getSource();
        MyContexttBuilder.MyContext callCtx =  DgsContext.getCustomContext(dfe);
        callCtx.setCustomState(obj.getId()+customId);
        return dataLoader.load(obj.getField(),callCtx);
    }

Dataloader look like below

@DgsDataLoader(name = "my_dataloader")
@Slf4j
public class MyDataLoader implements BatchLoaderWithContext<String, String> {

    @Override
    public CompletionStage<List<String>> load(List<String> fields, BatchLoaderEnvironment environment) {

        var usersContext = DgsContext.Companion.getCustomContext(environment);
        log.warn("fields size {} - {}", fields.size(),usersContext.getClass());

         MyContexttBuilder.MyContext callCtx = DgsContext.getCustomContext(environment);
        log.warn("callcontext {}", callCtx.getCustomState());


        return CompletableFuture.supplyAsync(
            () -> fields.stream()
                  .map(field -> "abc"+field)
                  .collect(Collectors.toList()));
    }
}

Now the issue is log.warn("callcontext {}", callCtx.getCustomState()); will always print customstate of the field which is passed recently. If Datafetcher is called 2 times dataloader will get a single call with size 2 and customstate will be set to the value set by a recent call to datafetcher. I want the dataloader to make batches based on the value of customstate. Imagine batching based on the tenantId. How to achieve this?

0

There are 0 answers