apollographql / apollo-cache-control

A GraphQL extension for cache control
146 stars 6 forks source link

Archival

This repo was archived by the Apollo Security team on 2023-05-26

Please reach out at security@apollographql.com with questions.

⚠️ Deprecation Notice

This specification is no longer supported by Apollo. Please see our documentation for alternative approaches.


Apollo Cache Control Specification

Apollo Cache Control is a GraphQL extension for fine-grained cache control that can inform server-side or client-side GraphQL caches. It describes a format for a GraphQL API to return information about cache expiration and scope, as well as controls that a client can use to override caching.

This data can inform Apollo Studio or other tools of the cache policies that are in effect for a particular request.

Supported GraphQL Servers

Know of other GraphQL servers which implement this specification? Open a PR to this README to add it to the list!

Response Format

The GraphQL specification allows servers to include additional information as part of the response under an extensions key:

The response map may also contain an entry with key extensions. This entry, if set, must have a map as its value. This entry is reserved for implementors to extend the protocol however they see fit, and hence there are no additional restrictions on its contents.

Apollo Cache Control exposes cache control hints for an individual request under a cacheControl key in extensions:

{
  "data": ...,
  "errors": ...,
  "extensions": {
    "cacheControl": {
      "version": 1,
      "hints: [
        {
          "path": [...],
          "maxAge": <seconds>,
          "scope": <PUBLIC or PRIVATE>
        },
        ...
      ]
    }
  }
}

Example

query {
  post(id: 1) {
    title
    votes
    readByCurrentUser
  }
}
"cacheControl": {
  "version": 1,
  "hints": [
    {
      "path": [
        "post"
      ],
      "maxAge": 240
    },
    {
      "path": [
        "post",
        "votes"
      ],
      "maxAge": 30
    },
    {
      "path": [
        "post",
        "readByCurrentUser"
      ],
      "scope": "PRIVATE"
    }
  ]
}

Request Format

Apollo Cache Control also allows clients to include cache control instructions in a request. For now, the only specified field is noCache, which forces the proxy never to return a cached response, but always fetch the query from the origin.

"extensions": {
  "cacheControl": {
    "version": 1,
    "noCache": true
  }
}