The Node.js® Website
at main 1.7 kB view raw
1import { 2 ENABLE_STATIC_EXPORT, 3 IS_DEVELOPMENT, 4 NEXT_DATA_URL, 5 VERCEL_ENV, 6} from '@/next.constants.mjs'; 7import type { BlogPostsRSC } from '@/types'; 8 9// Prevents React from throwing an Error when not able to fulfil a request 10// due to missing category or internal processing errors 11const parseBlogDataResponse = (data: string): BlogPostsRSC => 12 data.startsWith('{') ? JSON.parse(data) : { posts: [], pagination: {} }; 13 14const getBlogData = (cat: string, page?: number): Promise<BlogPostsRSC> => { 15 // When we're using Static Exports the Next.js Server is not running (during build-time) 16 // hence the self-ingestion APIs will not be available. In this case we want to load 17 // the data directly within the current thread, which will anyways be loaded only once 18 // We use lazy-imports to prevent `provideBlogData` from executing on import 19 if (ENABLE_STATIC_EXPORT || (!IS_DEVELOPMENT && !VERCEL_ENV)) { 20 return import('@/next-data/providers/blogData').then( 21 ({ provideBlogPosts, providePaginatedBlogPosts }) => 22 page ? providePaginatedBlogPosts(cat, page) : provideBlogPosts(cat) 23 ); 24 } 25 26 const fetchURL = page 27 ? // Provides a conditional fetch URL based on the given function parameters 28 `${NEXT_DATA_URL}blog-data/${cat}/${page}` 29 : `${NEXT_DATA_URL}blog-data/${cat}/0`; 30 31 // When we're on RSC with Server capabilities we prefer using Next.js Data Fetching 32 // as this will load cached data from the server instead of generating data on the fly 33 // this is extremely useful for ISR and SSG as it will not generate this data on every request 34 return fetch(fetchURL).then(r => r.text().then(parseBlogDataResponse)); 35}; 36 37export default getBlogData;