Added enhanced request query building

This commit is contained in:
2022-01-24 13:50:22 +01:00
parent 78fbd0234c
commit cbf5b814fc
3 changed files with 58 additions and 13 deletions

View File

@@ -8,6 +8,21 @@ async function unknownResponse(resp) {
return new Error(`Server sent unknown error: ${await resp.text()} (${resp.status})`);
}
}
function buildQuery(options) {
let query;
options.forEach(element => {
if (element[1] !== undefined) {
if (element[1] instanceof Date) {
element[1] = element[1].getSeconds();
}
else if (element[1] instanceof Array) {
element[1] = JSON.stringify(element[1]);
}
query.push(`${element[0]}&${element[1]}`);
}
});
return query.join("=");
}
async function login(username, password) {
let result = await fetch(`${prefix}/api/login`, {
method: "POST",
@@ -23,7 +38,8 @@ async function login(username, password) {
}
}
async function authors(name, limit) {
let result = await fetch(`${prefix}/api/authors?name=${name}&limit=${limit}`);
let query = [["name", name], ["limit", limit]];
let result = await fetch(`${prefix}/api/authors?${buildQuery(query)}`);
if (result.status == 200) {
return await result.json();
}
@@ -32,7 +48,8 @@ async function authors(name, limit) {
}
}
async function tags(name, limit) {
let result = await fetch(`${prefix}/api/tags?name=${name}&limit=${limit}`);
let query = [["name", name], ["limit", limit]];
let result = await fetch(`${prefix}/api/tags?${buildQuery(query)}`);
if (result.status == 200) {
return await result.json();
}
@@ -41,7 +58,8 @@ async function tags(name, limit) {
}
}
async function recent(limit = 20) {
let result = await fetch(`${prefix}/api/recent?limit=${limit}`);
let query = [["limit", limit]];
let result = await fetch(`${prefix}/api/recent?limit=${buildQuery(query)}`);
if (result.status == 200) {
return await result.json();
}
@@ -49,8 +67,9 @@ async function recent(limit = 20) {
throw await unknownResponse(result);
}
}
async function search(query) {
let result = await fetch(`${prefix}/api/search?q=${query.query}&from=${query.from.getSeconds()}&to=${query.to.getSeconds()}&authors=${JSON.stringify(query.authors)}&tags=${JSON.stringify(query.tags)}&limit=${query.limit}`);
async function search(q) {
let query = [["q", q.query], ["from", q.from], ["to", q.to], ["authors", q.authors], ["tags", q.tags], ["limit", q.limit]];
let result = await fetch(`${prefix}/api/search?${buildQuery(query)}`);
if (result.status == 200) {
return await result.json();
}
@@ -110,7 +129,8 @@ async function deleteArticle(id) {
}
}
async function getAssets(name, limit = 20) {
let result = await fetch(`${prefix}/api/assets?q=${name}&limit=${limit}`, {
let query = [["q", name], ["limit", limit]];
let result = await fetch(`${prefix}/api/assets?${buildQuery(query)}`, {
method: "GET",
});
switch (result.status) {