Last active
May 11, 2020 10:43
-
-
Save esamattis/12dc3e4cf0ceb2cd30e55833c9c95d12 to your computer and use it in GitHub Desktop.
wp-graphql cache
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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 ); | |
} ); |
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
Yeah, that's it.
We also released a real caching plugin
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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
Once cached it's possible to omit the query and send only the cache key