Skip to content

Instantly share code, notes, and snippets.

@dpacmittal
Last active December 5, 2020 05:36
Show Gist options
  • Save dpacmittal/e837e2a36714c6d1a279fbd5999debd0 to your computer and use it in GitHub Desktop.
Save dpacmittal/e837e2a36714c6d1a279fbd5999debd0 to your computer and use it in GitHub Desktop.
WP Graphql Stale-While-Revalidate Caching With Redis Object Cache
<?php
function get_request_hash($query, $vars)
{
return md5($query . json_encode($vars));
}
function should_cache($query, $op, $vars)
{
global $wp_object_cache;
if (!method_exists($wp_object_cache, 'redis_instance')) {
return false;
}
if (in_array($op, ['ProductsQuery', 'MenuQuery'])) {
return true;
}
return false;
}
add_action(
'do_graphql_request',
function ($query, $op, $vars, $params) {
global $wp_object_cache;
if (!should_cache($query, $op, $vars)) {
return;
}
$key = get_request_hash($query, $vars);
$redis = $wp_object_cache->redis_instance();
$data = $redis->get($key);
if ($data) {
$data_age = time() - $redis->get($key . '_time');
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
if ($data_age >= 120) {
header('x-tw-cache-status: stale');
define('TW_CACHE_STATUS', 'stale');
} else {
header('x-tw-cache-status: hit');
}
echo $data;
if (is_callable('fastcgi_finish_request')) {
// Response is sent, so finish the request.
fastcgi_finish_request();
}
if ($data_age <= 120) {
// Cache is fresh, less than 120 seconds old. No updating is necessary, so end the process
die();
}
} else {
header('x-tw-cache-status: miss');
}
},
10,
4
);
add_action(
'graphql_return_response',
function ($res, $unfiltered_res, $schema, $op, $query, $vars, $obj) {
global $wp_object_cache;
if (!should_cache($query, $op, $vars)) {
return;
}
$key = get_request_hash($query, $vars);
$redis = $wp_object_cache->redis_instance();
$redis->set($key, wp_json_encode($res->toArray()));
$redis->set($key . '_time', time());
if (TW_CACHE_STATUS == 'stale') {
// Stale response was already sent, so after updating cache, end the process
die();
}
},
10,
7
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment