normalize-paginated-list-response.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. /**
  2. * Some “list” response that can be paginated have a different response structure
  3. *
  4. * They have a `total_count` key in the response (search also has `incomplete_results`,
  5. * /installation/repositories also has `repository_selection`), as well as a key with
  6. * the list of the items which name varies from endpoint to endpoint.
  7. *
  8. * Octokit normalizes these responses so that paginated results are always returned following
  9. * the same structure. One challenge is that if the list response has only one page, no Link
  10. * header is provided, so this header alone is not sufficient to check wether a response is
  11. * paginated or not.
  12. *
  13. * We check if a "total_count" key is present in the response data, but also make sure that
  14. * a "url" property is not, as the "Get the combined status for a specific ref" endpoint would
  15. * otherwise match: https://developer.github.com/v3/repos/statuses/#get-the-combined-status-for-a-specific-ref
  16. */
  17. export function normalizePaginatedListResponse(response) {
  18. // endpoints can respond with 204 if repository is empty
  19. if (!response.data) {
  20. return {
  21. ...response,
  22. data: [],
  23. };
  24. }
  25. const responseNeedsNormalization = "total_count" in response.data && !("url" in response.data);
  26. if (!responseNeedsNormalization)
  27. return response;
  28. // keep the additional properties intact as there is currently no other way
  29. // to retrieve the same information.
  30. const incompleteResults = response.data.incomplete_results;
  31. const repositorySelection = response.data.repository_selection;
  32. const totalCount = response.data.total_count;
  33. delete response.data.incomplete_results;
  34. delete response.data.repository_selection;
  35. delete response.data.total_count;
  36. const namespaceKey = Object.keys(response.data)[0];
  37. const data = response.data[namespaceKey];
  38. response.data = data;
  39. if (typeof incompleteResults !== "undefined") {
  40. response.data.incomplete_results = incompleteResults;
  41. }
  42. if (typeof repositorySelection !== "undefined") {
  43. response.data.repository_selection = repositorySelection;
  44. }
  45. response.data.total_count = totalCount;
  46. return response;
  47. }