esvapi: fetch all pages of search results

Fixes: https://todo.sr.ht/~jeremy/esv/1
This commit is contained in:
Jeremy Baxter 2024-06-25 09:40:53 +12:00
parent cdabb25f74
commit 77c2c4825a
2 changed files with 40 additions and 18 deletions

View file

@ -326,16 +326,45 @@ class ESVApi
+
+ Example: search("It is finished")
+/
char[]
search(in string query)
string
search(in string query) @trusted
{
return makeRequest("search/?q=" ~ query.tr(" ", "+"));
JSONValue[] pages, results;
JSONValue result;
JSONValue
makeQuery(long page)
=> parseJSON(makeRequest("search/?page-size=100"
~ "&page=" ~ page.to!string()
~ "&q=" ~ query.tr(" ", "+")));
pages ~= makeQuery(1);
if (pages[0]["total_pages"].integer == 1) {
result = JSONValue([
"results": pages[0]["results"],
"total": JSONValue(pages[0]["results"].array.length)
]);
return result.toString();
}
foreach (long i; 2 .. pages[0]["total_pages"].integer + 1) {
pages ~= makeQuery(i);
}
foreach (JSONValue page; pages) {
results ~= page["results"].array;
}
result = JSONValue([
"results": JSONValue(results),
"total": JSONValue(results.length)
]);
return result.toString();
}
/++
+ Calls search() and formats the results nicely as plain text.
+/
char[]
string
searchFormat(alias fmt = "\033[1m%s\033[0m\n %s\n")
(in string query, int lineLength = 0) /* 0 means default */
{
@ -345,7 +374,7 @@ class ESVApi
resp = parseJSON(search(query));
layout = [];
enforce!ESVException(resp["total_results"].integer != 0,
enforce!ESVException(resp["total"].integer != 0,
"No results for search");
lineLength = lineLength == 0 ? 80 : lineLength;
@ -360,7 +389,7 @@ class ESVApi
}
}();
return layout;
return layout.idup();
}
protected char[]