Skip to content

Instantly share code, notes, and snippets.

@pzsprog
Created January 19, 2024 14:41
Show Gist options
  • Save pzsprog/1a368c35a0f000c1fd9b632a14e6e4a5 to your computer and use it in GitHub Desktop.
Save pzsprog/1a368c35a0f000c1fd9b632a14e6e4a5 to your computer and use it in GitHub Desktop.
const URL = 'https://rickandmortyapi.com/api/episode';
async function recursion(url) {
const response = await fetch(url);
const data = await response.json();
if (data && data.info && data.info.next) {
let d2 = await recursion(data.info.next);
return await [...data.results, ...d2];
}
return [...data.results];
}
(async () => console.log(await recursion(URL)))();
const URL = 'https://rickandmortyapi.com/api/episode';
const findProperty = (obj, arr) => arr.reduce((a, key) => (a ? a[key] : undefined), obj);
const getProp = (arr) => (obj) => findProperty(obj, arr);
async function hateoas(url, fnNextUrl, fnGetData) {
const res = await fetch(url);
const json = await res.json();
if (fnNextUrl(json)) {
let nextData = await hateoas(fnNextUrl(json), fnNextUrl, fnGetData);
return [...fnGetData(json), ...nextData];
}
return [...fnGetData(json)];
}
(async () => console.log(await hateoas(URL, getProp(['info', 'next']), getProp(['results']))))();
import { expand, reduce, EMPTY, Observable } from 'rxjs';
function getObservableFromFetch(url) {
//Create and return an Observable.
return new Observable(observer => {
//Make use of Fetch API to get data from URL
fetch(url)
.then(res => {
/*The response.json() doesn't return json, it returns a "readable stream" which is a promise which needs to be resolved to get the actual data.*/
return res.json();
})
.then(body => {
observer.next(body);
/*Complete the Observable as it won't produce any more event */
observer.complete();
})
//Handle error
.catch(err => observer.error(err));
})
};
const URL = 'https://rickandmortyapi.com/api/episode';
getObservableFromFetch(URL).pipe(
expand(response => response.info.next ? getObservableFromFetch(response.info.next) : EMPTY),
reduce((acc, current) => acc.concat(current.results), [])
).subscribe({
next: result => console.log(result)
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment