Skip to content

Commit 6077c2a

Browse files
committed
Allow caching some API responses that change rarely
1 parent 243853d commit 6077c2a

File tree

3 files changed

+30
-2
lines changed

3 files changed

+30
-2
lines changed

api/api_common.inc

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,3 +24,25 @@ function get_flag_value(array $query_params, string $flagname)
2424
return $bool;
2525
}
2626
}
27+
28+
/**
29+
* Send headers telling the client it's OK to cache the page
30+
*/
31+
function send_cache_header(int $cache_time, ?string $cache_type = "private", bool $immutable = true): void
32+
{
33+
if ($cache_type && !in_array($cache_type, ["public", "private"])) {
34+
throw new ValueError("Invalid value for 'cache_type'");
35+
}
36+
37+
$cache_settings = ["max-age=$cache_time"];
38+
39+
if ($cache_type) {
40+
$cache_settings[] = $cache_type;
41+
}
42+
43+
if ($immutable) {
44+
$cache_settings[] = "immutable";
45+
}
46+
47+
header("Cache-Control: " . join(", ", $cache_settings));
48+
}

api/v1_docs.inc

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
<?php
22
include_once($relPath.'faq.inc');
3+
include_once("api_common.inc");
34

45
/** @param array<string, string|string[]> $query_params */
56
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
1415
$docs_with_lang[] = $doc;
1516
}
1617
}
17-
return $docs_with_lang;
18+
$docs = $docs_with_lang;
1819
} else {
19-
return array_keys($external_faq_overrides);
20+
$docs = array_keys($external_faq_overrides);
2021
}
22+
send_cache_header(60 * 60 * 24, "public");
23+
return $docs;
2124
}
2225

2326
/** @param array<string, string|string[]> $query_params */
@@ -29,6 +32,7 @@ function api_v1_document(string $method, array $data, array $query_params): stri
2932
if ("" === $faq_url) {
3033
throw new NotFoundError("$document is not available in language code '$lang_code'");
3134
}
35+
send_cache_header(60 * 60 * 24, "public");
3236
return $faq_url;
3337
}
3438

@@ -37,5 +41,6 @@ function api_v1_dictionaries(string $method, array $data, array $query_params):
3741
{
3842
$dict_list = get_languages_with_dictionaries();
3943
asort($dict_list);
44+
send_cache_header(60 * 60 * 24, "public");
4045
return $dict_list;
4146
}

api/v1_projects.inc

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -887,6 +887,7 @@ function api_v1_project_wordcheck(string $method, array $data, array $query_para
887887
function api_v1_project_pickersets(string $method, array $data, array $query_params): array
888888
{
889889
$project = $data[":projectid"];
890+
send_cache_header(60 * 60, "public");
890891
return $project->get_verbose_pickersets();
891892
}
892893

0 commit comments

Comments
 (0)