Skip to content

Instantly share code, notes, and snippets.

@rosd89
Created July 30, 2020 05:56
Show Gist options
  • Save rosd89/8671f925b841593e2d4e251ffbb704b7 to your computer and use it in GitHub Desktop.
Save rosd89/8671f925b841593e2d4e251ffbb704b7 to your computer and use it in GitHub Desktop.
import axios from 'axios';
const tr = p => (throw new Error(`Oops, you are missing a required field: "${p}"`));
const api = async function* ({path = tr('url'), params = {page: 1, pageSize: 10}}) {
let page = -1;
do {
try {
const {page: nextPage, pageSize, total, items} = await axios.get(path, {params});
page = nextPage;
if (items.length === 0) {
page = -1;
break;
}
yield {page, pageSize, total, items};
} catch (e) {
page = -1;
throw new Error(e);
}
} while (page !== -1);
};
(async () => {
const surveys = api({path: '/manage/survey'});
// 1 page
const {value, done} = await surveys.next();
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment