Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Query Redash's API for fresh results from Javascript
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function getQueryResult(slug, queryId, apiKey, options = {}) {
const instance = axios.create({
baseURL: `https://app.redash.io/${slug}`,
headers: {
Authorization: `Key ${apiKey}`
}
});
const url = `/api/queries/${queryId}/results`;
let response = await instance.post(url, options);
if ("job" in response.data) {
const jobUrl = `/api/queries/${queryId}/jobs/${response.data.job.id}`;
// 1 == PENDING (waiting to be executed)
// 2 == STARTED (executing)
// 3 == SUCCESS
// 4 == FAILURE
// 5 == CANCELLED
while (response.data.job.status < 3) {
// While query isn't ready (pending or executing), poll for results every 1second.
// Polling time can be updated if you know that the query might take longer.
response = await instance.get(jobUrl);
await sleep(1000);
}
if (response.data.job.status === 3) {
const { data } = await instance.post(url, options);
return data;
} else {
throw Error("Failed loading result");
}
} else {
return response.data;
}
}
// Execute query and get latest results:
getQueryResult('example', 1234, 'some-secret')
// Execute query and get latest results with parameters:
getQueryResult('example', 4567, 'some-secret', {"parameters": {"my-param": 123}});
// Execute query and get latest results with parameters + specify max-age (bring result which is at most 10 minutes old):
getQueryResult('example', 4567, 'some-secret', {"parameters": {"my-param": 123}, "max_age": 600});
// Note that you can use max_age for queries without parameter as well.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.