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

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