iterator.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. import { normalizePaginatedListResponse } from "./normalize-paginated-list-response";
  2. export function iterator(octokit, route, parameters) {
  3. const options = typeof route === "function"
  4. ? route.endpoint(parameters)
  5. : octokit.request.endpoint(route, parameters);
  6. const requestMethod = typeof route === "function" ? route : octokit.request;
  7. const method = options.method;
  8. const headers = options.headers;
  9. let url = options.url;
  10. return {
  11. [Symbol.asyncIterator]: () => ({
  12. async next() {
  13. if (!url)
  14. return { done: true };
  15. try {
  16. const response = await requestMethod({ method, url, headers });
  17. const normalizedResponse = normalizePaginatedListResponse(response);
  18. // `response.headers.link` format:
  19. // '<https://api.github.com/users/aseemk/followers?page=2>; rel="next", <https://api.github.com/users/aseemk/followers?page=2>; rel="last"'
  20. // sets `url` to undefined if "next" URL is not present or `link` header is not set
  21. url = ((normalizedResponse.headers.link || "").match(/<([^>]+)>;\s*rel="next"/) || [])[1];
  22. return { value: normalizedResponse };
  23. }
  24. catch (error) {
  25. if (error.status !== 409)
  26. throw error;
  27. url = "";
  28. return {
  29. value: {
  30. status: 200,
  31. headers: {},
  32. data: [],
  33. },
  34. };
  35. }
  36. },
  37. }),
  38. };
  39. }