123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566 |
- <header>
- SWAPI Links
- </header>
- <body>
- <script>
- const improovedFetch = async (url) => {
- let lukeRes = await fetch(url);
- let luke = await lukeRes.json();
- let result = {};
- let retrievers = [];
- let valueArr = [];
- for (let key in luke) {
- let value = luke[key];
- let isArray = Array.isArray(value);
- if (typeof value == "string") {
- valueArr.push(value);
- }
- else if (isArray) {
- valueArr = value.filter(val => typeof val == "string");
- }
- valueArr = valueArr.filter(val => val.startsWith("https://swapi.dev/api/"));
- if (valueArr.length > 0) {
- for (let urlStr of valueArr) {
- retrievers.push(fetch(urlStr)
- .then(res => res.json())
- .then(
- res => {
- let result =
- {
- key: key,
- val: res,
- isArray: isArray
- };
- return result;
- }));
- }
- }
- else {
- result[key] = value;
- }
- }
- let results = [result, ...await Promise.all(retrievers)];
- results.reduce((a, v) => {
- let { key, val, isArray } = v;
- if (isArray) {
- let aVal = a[key];
- if (!aVal)
- a[key] = aVal = [];
- aVal.push(val);
- }
- else {
- a[key] = val;
- }
- return a;
- });
- return result;
- }
- improovedFetch('https://swapi.dev/api/people/20/').then(
- res => res
- )
- .then(
- res => console.log(JSON.stringify(res,null,4))
- );
- </script>
- </body>
|