|
| 1 | +const axios = require('axios'); |
| 2 | + |
| 3 | +// From: https://www.storyblok.com/faq/how-to-generate-routes-for-nuxt-js-using-storyblok |
| 4 | +module.exports = function generateStoryblokUrls(token) { |
| 5 | + return { |
| 6 | + routes: function(callback) { |
| 7 | + const per_page = 10; |
| 8 | + const version = 'published'; |
| 9 | + let cache_version = 0; |
| 10 | + |
| 11 | + let page = 1; |
| 12 | + |
| 13 | + // other routes that are not in Storyblok with their slug. |
| 14 | + let routes = ['/']; // adds home directly but with / instead of /home |
| 15 | + |
| 16 | + // Load space and receive latest cache version key to improve performance |
| 17 | + axios |
| 18 | + .get(`https://api.storyblok.com/v1/cdn/spaces/me?token=${token}`) |
| 19 | + .then(space_res => { |
| 20 | + // timestamp of latest publish |
| 21 | + cache_version = space_res.data.space.version; |
| 22 | + |
| 23 | + // Call first Page of the Stories |
| 24 | + axios |
| 25 | + .get( |
| 26 | + `https://api.storyblok.com/v1/cdn/stories?token=${token}&version=${version}&per_page=${per_page}&page=${page}&cv=${cache_version}` |
| 27 | + ) |
| 28 | + .then(res => { |
| 29 | + res.data.stories.forEach(story => { |
| 30 | + if (story.full_slug != 'home') { |
| 31 | + routes.push('/' + story.full_slug); |
| 32 | + } |
| 33 | + }); |
| 34 | + |
| 35 | + // Check if there are more pages available otherwise execute callback with current routes. |
| 36 | + const total = res.headers.total; |
| 37 | + const maxPage = Math.ceil(total / per_page); |
| 38 | + if (maxPage <= 1) { |
| 39 | + callback(null, routes); |
| 40 | + return; |
| 41 | + } |
| 42 | + |
| 43 | + // Since we know the total we now can pregenerate all requests we need to get all stories |
| 44 | + let contentRequests = []; |
| 45 | + for (let page = 2; page <= maxPage; page++) { |
| 46 | + contentRequests.push( |
| 47 | + axios.get( |
| 48 | + `https://api.storyblok.com/v1/cdn/stories?token=${token}&version=${version}&per_page=${per_page}&page=${page}` |
| 49 | + ) |
| 50 | + ); |
| 51 | + } |
| 52 | + |
| 53 | + // Axios allows us to exectue all requests using axios.spread we will than generate our routes and execute the callback |
| 54 | + axios |
| 55 | + .all(contentRequests) |
| 56 | + .then( |
| 57 | + axios.spread((...responses) => { |
| 58 | + responses.forEach(response => { |
| 59 | + response.data.stories.forEach(story => { |
| 60 | + if (story.full_slug != 'home') { |
| 61 | + routes.push('/' + story.full_slug); |
| 62 | + } |
| 63 | + }); |
| 64 | + }); |
| 65 | + |
| 66 | + callback(null, routes); |
| 67 | + }) |
| 68 | + ) |
| 69 | + .catch(callback); |
| 70 | + }); |
| 71 | + }); |
| 72 | + } |
| 73 | + }; |
| 74 | +}; |
0 commit comments