Skip to content

Instantly share code, notes, and snippets.

@esamattis
Last active May 11, 2020 10:43
Show Gist options
  • Save esamattis/12dc3e4cf0ceb2cd30e55833c9c95d12 to your computer and use it in GitHub Desktop.
Save esamattis/12dc3e4cf0ceb2cd30e55833c9c95d12 to your computer and use it in GitHub Desktop.
wp-graphql cache
<?php
// UPDATE! Checkout this plugin https://github.com/valu-digital/wp-graphql-cache
// Requires some persistent object cache such as wp-redis.
define( 'WP_GRAPHQL_CACHE_AGE', 10 ); // in seconds
add_action( 'do_graphql_request', function () {
if ( ! isset( $_SERVER['HTTP_X_GRAPHQL_CACHE'] ) ) {
return;
}
$key = $_SERVER['HTTP_X_GRAPHQL_CACHE'];
$data = wp_cache_get( $key, 'wpgraphql' );
if ( $data ) {
header( 'Content-Type: application/json' );
header( 'x-graphql-cache-status: hit' );
echo $data;
die();
}
// TODO: How detect missing query and send nice error message?
header( 'x-graphql-cache-status: miss' );
} );
add_action( 'graphql_return_response', function( $res ) {
if ( ! isset( $_SERVER['HTTP_X_GRAPHQL_CACHE'] ) ) {
return;
}
$key = $_SERVER['HTTP_X_GRAPHQL_CACHE'];
wp_cache_add( $key, wp_json_encode( $res->toArray() ), 'wpgraphql', WP_GRAPHQL_CACHE_AGE );
} );
@esamattis
Copy link
Author

esamattis commented Aug 31, 2018

Adds simple caching layer to wp-graphql. The client must add a x-graphql-cache header with a unique key identifying the graphql query and it's variables.

Example

curl http://wp.test/graphql -v -d {"query": "{postBy(postId: 415) {title}}"}' -H "content-type: application/json" -H "x-graphql-cache: 1234"

Once cached it's possible to omit the query and send only the cache key

curl http://wp.test/graphql -v -d '{}' -H "content-type: application/json" -H "x-graphql-cache: 1234"

@jkhaui
Copy link

jkhaui commented Jan 17, 2019

Hey @epeli, this looks real cool. I assume this is the WP GraphQL plugin it's meant to work with? https://github.com/wp-graphql/wp-graphql/

Do you have a written tutorial/documentation which provides more detail on how to implement this

@esamattis
Copy link
Author

Yeah, that's it.

We also released a real caching plugin

https://github.com/valu-digital/wp-graphql-cache

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment