|
| 1 | +const { createFilePath } = require('gatsby-source-filesystem') |
| 2 | +const path = require('path') |
| 3 | + |
| 4 | +// Here we're adding extra stuff to the "node" (like the slug) |
| 5 | +// so we can query later for all blogs and get their slug |
| 6 | +exports.onCreateNode = ({ node, actions, getNode }) => { |
| 7 | + const { createNodeField } = actions |
| 8 | + if (node.internal.type === 'Mdx') { |
| 9 | + const value = createFilePath({ node, getNode }) |
| 10 | + createNodeField({ |
| 11 | + // Name of the field you are adding |
| 12 | + name: 'slug', |
| 13 | + // Individual MDX node |
| 14 | + node, |
| 15 | + // Generated value based on filepath with "blog" prefix |
| 16 | + value: `/blog${value}` |
| 17 | + }) |
| 18 | + } |
| 19 | +} |
| 20 | + |
| 21 | +// Programmatically create the pages for browsing blog posts |
| 22 | +exports.createPages = ({ graphql, actions }) => { |
| 23 | + const { createPage } = actions |
| 24 | + return graphql(` |
| 25 | + query { |
| 26 | + allMdx(sort: { order: DESC, fields: [frontmatter___date] }) { |
| 27 | + edges { |
| 28 | + node { |
| 29 | + id |
| 30 | + excerpt(pruneLength: 250) |
| 31 | + fields { |
| 32 | + slug |
| 33 | + } |
| 34 | + frontmatter { |
| 35 | + author |
| 36 | + title |
| 37 | + } |
| 38 | + } |
| 39 | + } |
| 40 | + } |
| 41 | + } |
| 42 | + `).then((results, errors) => { |
| 43 | + if (errors) return Promise.reject(errors) |
| 44 | + const posts = results.data.allMdx.edges |
| 45 | + |
| 46 | + // This little algo takes the array of posts and groups |
| 47 | + // them based on this `size`. I used a small number just |
| 48 | + // for testing since there are only three posts |
| 49 | + let size = 2 |
| 50 | + let start = 0 |
| 51 | + let groupedPosts = Array.from(Array(Math.ceil(posts.length / size))) |
| 52 | + groupedPosts = groupedPosts.map(() => { |
| 53 | + const group = posts.slice(start, start + size) |
| 54 | + start += size |
| 55 | + return group |
| 56 | + }) |
| 57 | + |
| 58 | + groupedPosts.forEach((group, index) => { |
| 59 | + const page = index + 1 |
| 60 | + createPage({ |
| 61 | + path: `/blog/${page}`, |
| 62 | + component: path.resolve('./src/components/browse-blog-posts.js'), |
| 63 | + context: { groupedPosts, group, page } |
| 64 | + }) |
| 65 | + }) |
| 66 | + }) |
| 67 | +} |
0 commit comments