Using dynamic variables within GraphQL queries

I’m trying to figure out how to use values from one part of a GraphQL query as variables in another part of the same query. This doesn’t seem to be supported natively in GraphQL.

I have a scenario where I need to fetch sensor data from a manufacturing process. I want to get temperature readings during specific time periods, but the start and end times come from the same query.

Here’s what I wish I could do in a single query:

{
    items {
        id,
        process(category:"heating") {
            title,
            $startTime: beginTimestamp,
            $endTime: finishTimestamp,
            sensorData(startDate:$startTime, endDate:$endTime){
                recorded,
                reading
            }
        }
    }
}

Right now I have to split this into two separate queries. First I get the timestamps:

{
    items {
        id,
        process(category:"heating") {
            title,
            beginTimestamp,
            finishTimestamp
        }
    }
}

Then I make another query for each item using those values:

{
    item(id:"{ITEM_ID}") {
        id
        process(title:"{PROCESS_NAME}") {
            sensorData(startDate:"{BEGIN_TIME}", endDate:"{FINISH_TIME}"){
                recorded,
                reading
            }
        }
    }
}

This defeats the purpose of GraphQL’s single query approach. Is there any way to accomplish this with one query instead of multiple round trips?

I feel u on this one! GraphQL variables can be a real pain. I ended up creating a resolver that handles timestamp filtering directly - saves u from making multiple requests and keeps everything clean. Should solve ur problem!

You’re right - GraphQL doesn’t let you use dynamic variables like that within a single query. All variables have to be declared at the operation level and passed from the client.

I hit the same problem with a logistics system where I needed shipment dates to filter tracking events. Fixed it by moving the logic server-side instead of fighting with the query structure.

You could restructure your schema so the process type automatically includes filtered sensor data. Add a filteredSensorData field that uses beginTimestamp and finishTimestamp internally. Your resolver handles the filtering instead of trying to pass values around in the query.

There’s also GraphQL fragments with multiple queries in one request, but that’s still multiple network round trips. The schema approach keeps it as a true single query and puts the complexity where it belongs - on the server.