Get All WordPress Posts from REST API with Axios and RxJS

node v8.17.0
version: master
endpointsharetweet
// Import Axios const axios = require('axios') // Import the necessary RxJS dependencies const { Observable, switchMap, concatMap, from, range } = require('rxjs') // Setup an endpoint to hit const endpoint = 'http://demo.wp-api.org/wp-json/wp/v2/posts' // This sets up the initial request and starts the Observable chain // In the return from the endpoint, the Axios request headers will have x-wp-totalpages, // which gives us... the total pages of posts ;) const posts$ = Observable.from(axios.get(endpoint)) // We now know the total number of pages, // so we'll switch to a new Observable that is just a range of numbers // We'll start with 1, and end with whatever the total number of pages is // This gives us a stream of 1--n--n--n... (example: 1, 2, 3, 4...) .switchMap(({ headers }) => Observable.range(1, Number(headers['x-wp-totalpages'])), ) // We can now paginate through all posts, getting 10/page // concatMap will fire off a request, wait until it completes, and then fire the next one // In each subsequent firing, we ask for the next page of posts .concatMap(page => Observable.from( axios.get(endpoint, { params: { page, }, }), ), ) .subscribe( // data here is an Array of WordPress Posts, tacking .length shows us how many per page we are getting ({ data }) => console.log(data.length), err => console.log('Oh no, an error!', err), )
Loading…

no comments

    sign in to comment