hw_17_02_swapi links.html 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. <header>
  2. SWAPI Links
  3. </header>
  4. <body>
  5. <script>
  6. const improovedFetch = async (url) => {
  7. let lukeRes = await fetch(url);
  8. let luke = await lukeRes.json();
  9. let result = {};
  10. let retrievers = [];
  11. let valueArr = [];
  12. for (let key in luke) {
  13. let value = luke[key];
  14. let isArray = Array.isArray(value);
  15. if (typeof value == "string") {
  16. valueArr.push(value);
  17. }
  18. else if (isArray) {
  19. valueArr = value.filter(val => typeof val == "string");
  20. }
  21. valueArr = valueArr.filter(val => val.startsWith("https://swapi.dev/api/"));
  22. if (valueArr.length > 0) {
  23. for (let urlStr of valueArr) {
  24. retrievers.push(fetch(urlStr)
  25. .then(res => res.json())
  26. .then(
  27. res => {
  28. let result =
  29. {
  30. key: key,
  31. val: res,
  32. isArray: isArray
  33. };
  34. return result;
  35. }));
  36. }
  37. }
  38. else {
  39. result[key] = value;
  40. }
  41. }
  42. let results = [result, ...await Promise.all(retrievers)];
  43. results.reduce((a, v) => {
  44. let { key, val, isArray } = v;
  45. if (isArray) {
  46. let aVal = a[key];
  47. if (!aVal)
  48. a[key] = aVal = [];
  49. aVal.push(val);
  50. }
  51. else {
  52. a[key] = val;
  53. }
  54. return a;
  55. });
  56. return result;
  57. }
  58. improovedFetch('https://swapi.dev/api/people/20/').then(
  59. res => res
  60. )
  61. .then(
  62. res => console.log(JSON.stringify(res,null,4))
  63. );
  64. </script>
  65. </body>