Back to Examples

GraphQL service - Field-level caching

The Ballerina graphql module provides the capability to enable GraphQL caching, which can be applied at either the field or operation level. To enable caching at the field level, the cacheConfig field in the graphql:ResourceConfig annotation can be used on a resource method within a graphql:Service. By setting this configuration, caching is enabled for the specified GraphQL field, and it can override the cache configurations set at the operation level.

import ballerina/graphql;

// Defines a `record` type to use as an object in the GraphQL service.
type User readonly & record {|
    int id;
    string name;
    int age;
|};

// Defines an in-memory table to store the users.
table<User> key(id) users = table [
    {id: 1, name: "Walter White", age: 50},
    {id: 2, name: "Jesse Pinkman", age: 25}
];

service /graphql on new graphql:Listener(9090) {

    // The `cacheConfig` in the `graphql:ResourceConfig` annotation is used to
    // configure the cache for a specific field in the GraphQL service.
    // (default: {enabled: true, maxAge: 60, maxSize: 120})
    @graphql:ResourceConfig {
        cacheConfig: {}
    }
    resource function get name(int id) returns string|error {
        if users.hasKey(id) {
            return users.get(id).name;
        }
        return error(string `User with the ${id} not found`);
    }
}

Run the service by executing the following command.

$ bal run graphql_service_field_level_caching.bal

Send the following document to the GraphQL endpoint to test the service.

{
    name(id: 1)
}

To send the document, execute the following cURL command.

$ curl -X POST -H "Content-type: application/json" -d '{ "query": "{ name(id: 1) }" }' 'http://localhost:9090/graphql'{"data":{"name":"Walter White"}}

Tip: You can invoke the above service via the GraphQL client.

Related links

PreviousOperation-level caching
NextCache invalidation