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 ); | |
} ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Yeah, that's it.
We also released a real caching plugin
https://github.com/valu-digital/wp-graphql-cache