From 8b77aa9918f977e008730cd5b86ae749ae077e35 Mon Sep 17 00:00:00 2001 From: Casey Peel Date: Fri, 26 Dec 2025 10:49:15 -0800 Subject: [PATCH] Allow caching some API responses that change rarely --- api/api_common.inc | 22 ++++++++++++++++++++++ api/v1_docs.inc | 9 +++++++-- api/v1_projects.inc | 1 + 3 files changed, 30 insertions(+), 2 deletions(-) diff --git a/api/api_common.inc b/api/api_common.inc index 966b9a902f..1380aa7aed 100644 --- a/api/api_common.inc +++ b/api/api_common.inc @@ -24,3 +24,25 @@ function get_flag_value(array $query_params, string $flagname) return $bool; } } + +/** + * Send headers telling the client it's OK to cache the page + */ +function send_cache_header(int $cache_time, ?string $cache_type = "private", bool $immutable = true): void +{ + if ($cache_type && !in_array($cache_type, ["public", "private"])) { + throw new ValueError("Invalid value for 'cache_type'"); + } + + $cache_settings = ["max-age=$cache_time"]; + + if ($cache_type) { + $cache_settings[] = $cache_type; + } + + if ($immutable) { + $cache_settings[] = "immutable"; + } + + header("Cache-Control: " . join(", ", $cache_settings)); +} diff --git a/api/v1_docs.inc b/api/v1_docs.inc index 25eaea8b45..08998d05f5 100755 --- a/api/v1_docs.inc +++ b/api/v1_docs.inc @@ -1,5 +1,6 @@ $query_params */ function api_v1_documents(string $method, array $data, array $query_params): array @@ -14,10 +15,12 @@ function api_v1_documents(string $method, array $data, array $query_params): arr $docs_with_lang[] = $doc; } } - return $docs_with_lang; + $docs = $docs_with_lang; } else { - return array_keys($external_faq_overrides); + $docs = array_keys($external_faq_overrides); } + send_cache_header(60 * 60 * 24, "public"); + return $docs; } /** @param array $query_params */ @@ -29,6 +32,7 @@ function api_v1_document(string $method, array $data, array $query_params): stri if ("" === $faq_url) { throw new NotFoundError("$document is not available in language code '$lang_code'"); } + send_cache_header(60 * 60 * 24, "public"); return $faq_url; } @@ -37,5 +41,6 @@ function api_v1_dictionaries(string $method, array $data, array $query_params): { $dict_list = get_languages_with_dictionaries(); asort($dict_list); + send_cache_header(60 * 60 * 24, "public"); return $dict_list; } diff --git a/api/v1_projects.inc b/api/v1_projects.inc index 9d123061a4..67b181708c 100644 --- a/api/v1_projects.inc +++ b/api/v1_projects.inc @@ -887,6 +887,7 @@ function api_v1_project_wordcheck(string $method, array $data, array $query_para function api_v1_project_pickersets(string $method, array $data, array $query_params): array { $project = $data[":projectid"]; + send_cache_header(60 * 60, "public"); return $project->get_verbose_pickersets(); }