0

I have a example DgsQuery:

@DgsQuery
public List<Sensor> sensors(DgsDataFetchingEnvironment dfe) {
     
    SensorType sensorType = SensorType.newBuilder()
            .id(UUID.randomUUID().toString())
            .build();
    

    Sensor sensor = new Sensor();
    sensor.setId(UUID.randomUUID().toString());
    sensor.setName("foo");
    sensor.setSensorType(sensorType);

    return Arrays.asList(sensor);
}

And a data fetcher:

@DgsData(parentType = DgsConstants.SENSOR.TYPE_NAME, field = DgsConstants.SENSOR.SensorType)
public CompletableFuture<SensorType> sensorType(DgsDataFetchingEnvironment dfe) {
    Sensor sensor = dfe.getSource();
    UUID sensorTypeId = UUID.fromString(sensor.getSensorType().getId());

    // fetch sensorType by ID from DB, map to generated class and return
    LOGGER.info("Would now fetch sensorType with ID {} via RPC or whatever you want ;)", sensorTypeId);

    return null;
}

In the dataFetcher I need to be able to access some additional data / objects that are initialized in the @DgsQuery method. How can I do this?

Example usecase:
In the @DgsQuery there is a Entity that has been loaded from the database, I need to pass this entity to the data fetcher.
Currently I have only access to the Sensor object via

    Sensor sensor = dfe.getSource();

but none of some further data that might be already loaded.

Alex Tbk
  • 2,042
  • 2
  • 20
  • 38

1 Answers1

0

Found it out:

@DgsQuery
public DataFetcherResult<List<Sensor>> sensors(DgsDataFetchingEnvironment dfe) {

    SensorType sensorType = SensorType.newBuilder()
            .id(UUID.randomUUID().toString())
            .build();

    Sensor sensor = new Sensor();
    sensor.setId(UUID.randomUUID().toString());
    sensor.setName("foo");
    sensor.setSensorType(sensorType);

    return DataFetcherResult.<List<Sensor>>newResult()
            .data(Arrays.asList(sensor))
            .localContext("foo")
            .build();
}

and in the data fetcher:

Object localContext = dfe.getLocalContext(); ( --> "foo")
Alex Tbk
  • 2,042
  • 2
  • 20
  • 38