Skip to content

Instantly share code, notes, and snippets.

@dpawluk
Created August 8, 2020 01:19
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dpawluk/ccad0be596446a5a819fd52171e2862b to your computer and use it in GitHub Desktop.
Save dpawluk/ccad0be596446a5a819fd52171e2862b to your computer and use it in GitHub Desktop.
Get all users on app start, async promise based
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<!-- See Using Zendesk Garden:
https://developer.zendesk.com/apps/docs/developer-guide/setup#using-zendesk-garden
https://garden.zendesk.com/css-components/bedrock/
https://garden.zendesk.com/css-components/utilities/typography/
-->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/combine/npm/@zendeskgarden/css-bedrock@7.0.21,npm/@zendeskgarden/css-utilities@4.3.0">
</head>
<body>
<h2 class="u-semibold u-fs-xl">Hello, World!</h2>
<script src="https://static.zdassets.com/zendesk_app_framework_sdk/2.0/zaf_sdk.min.js"></script>
<script>
// Initialise Apps framework client. See also:
// https://developer.zendesk.com/apps/docs/developer-guide/getting_started
var client = ZAFClient.init();
client.invoke('resize', { width: '100%', height: '200px' });
client.on('app.registered', init);
function init(){
console.log("started");
getAllUsers().then(function(data){
console.log(data); // at the end of getAllUsers we return a promise so we can call .done here when
});
}
function getAllUsers(){
var results = [];
var first_page = client.request({
url: "/api/v2/users.json",
type: "GET"
});
all_pages = first_page.then(function(response){
results.push(response.users);
var page_count = Math.ceil(response.count / 100);
// if page count is insanely high we can just default to a reasonable number and return a message saying there are too many results to fetch at one time
var next_pages = [];
for(x=2;x <= page_count; x++){ //already got the first page to see if we actually want to paginate them all, just loop from second through last
url = `/api/v2/users.json?page=${x}`;
next_pages.push(client.request({url: url, type: "GET"}))
}
return Promise.all(next_pages).then(function(response){
response.forEach(function(r){
results.push(r.users);
});
var flat = results.flat(); //results is an array of user arrays, lets flatten it out to clean it up
return flat;
});
});
return all_pages; //return the initial promise, that returns more promises, I know its dumb but it is Friday
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment