Skip to content

Instantly share code, notes, and snippets.

@arikfr
Created August 18, 2019 11:14
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arikfr/ab39499738976a61855f98cc62d39e52 to your computer and use it in GitHub Desktop.
Save arikfr/ab39499738976a61855f98cc62d39e52 to your computer and use it in GitHub Desktop.
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