gatsby-node.js (2806B)
1 const path = require('path'); 2 const tagData = require('./src/tagData'); 3 4 const createTagPages = (createPage, posts) => { 5 const allTagsIndexTemplate = path.resolve('src/templates/allTagsIndex.js'); 6 const singleTagIndexTemplate = path.resolve( 7 'src/templates/singleTagIndex.js' 8 ); 9 10 const postsByTag = {}; 11 posts.forEach(({ node }) => { 12 if (node.frontmatter.tags) { 13 node.frontmatter.tags.forEach(tag => { 14 if (!postsByTag[tag]) { 15 postsByTag[tag] = []; 16 } 17 postsByTag[tag].push(node); 18 }); 19 } 20 }); 21 22 const tags = Object.keys(postsByTag); 23 24 createPage({ 25 path: '/tags', 26 component: allTagsIndexTemplate, 27 context: { 28 tags: tags.sort(), 29 }, 30 }); 31 32 tags.forEach(tag => { 33 const posts = postsByTag[tag]; 34 const cover = tagData.filter(el => el.tag == tag); 35 createPage({ 36 path: `/tags/${tag}`, 37 component: singleTagIndexTemplate, 38 context: { 39 cover, 40 posts, 41 tag, 42 }, 43 }); 44 }); 45 }; 46 47 exports.createPages = ({ graphql, actions }) => { 48 const { createPage } = actions; 49 return new Promise((resolve, reject) => { 50 const BlogPostTemplate = path.resolve('src/templates/blogPost.js'); 51 resolve( 52 graphql( 53 ` 54 query { 55 site { 56 siteMetadata { 57 author 58 description 59 name 60 photo 61 } 62 } 63 allMarkdownRemark( 64 sort: { order: DESC, fields: [frontmatter___date] } 65 ) { 66 edges { 67 node { 68 frontmatter { 69 cover 70 date 71 excerpt 72 path 73 tags 74 title 75 } 76 } 77 } 78 } 79 } 80 ` 81 ).then(result => { 82 const { 83 author, 84 description, 85 name, 86 photo, 87 } = result.data.site.siteMetadata; 88 const posts = result.data.allMarkdownRemark.edges; 89 createTagPages(createPage, posts); 90 91 posts.forEach(({ node }, index) => { 92 createPage({ 93 path: node.frontmatter.path, 94 component: BlogPostTemplate, 95 context: { 96 author, 97 cover: node.frontmatter.cover, 98 date: node.frontmatter.date, 99 description, 100 name, 101 next: index === posts.length - 1 ? null : posts[index + 1].node, 102 pathSlug: node.frontmatter.path, 103 photo, 104 prev: index === 0 ? null : posts[index - 1].node, 105 tags: node.frontmatter.tags, 106 }, 107 }); 108 resolve(); 109 }); 110 }) 111 ); 112 }); 113 };