Как создать несколько сопоставлений между yaml и markdown в gatsby - PullRequest
1 голос
/ 14 февраля 2020

прошло полмесяца с тех пор, как я изучаю гэтсби, к сожалению, мне сложно понять, как соотносятся содержание и структура.

Я пытаюсь создать отображение между frontmatter уценки и yaml , в данном случае тегами author и taxonomy. Для автора мне удалось это сделать, но по какой-то причине, когда я добавил дополнительное сопоставление 'MarkdownRemark.frontmatter.tags': 'TagsYaml' для тегов, результаты стали ошибкой

Моя мотивация заключается в получении динамических c данных для таксономии, чтобы я мог не нужно жестко закодировать в шаблоне. Я искал похожую проблему в github # 10169 и # 16118 , но мне кажется, что я не могу ответить

вот пример моего yaml и уценки

# authors.yaml
- id: JohnDoe
  twitter: "@JohnDoe"
  email: "me@email.com"
  bio: Lorem
  desc: Ipsum
# tags.yaml
- tags: Foo
---
title: Bar
author: ["JohnDoe"]
tags: ["Foo"]
---

результат ошибки

"gatsby-node.js" threw an error while running the createPages lifecycle:

runner.query(...).then is not a function

  43 |     return new Promise((resolve, reject) => {
  44 |         resolve(
> 45 |             graphql(
     |             ^
  46 |                 `
  47 |                 query {
  48 |                   pages: allMarkdownRemark(

File: gatsby-node.js:45:13

Среда

  System:
    OS: Windows 10 10.0.18362
    CPU: (4) x64 Intel(R) Core(TM) i3-3110M CPU @ 2.40GHz
  Binaries:
    Node: 10.16.0 - C:\Program Files\nodejs\node.EXE
    Yarn: 1.19.2 - C:\Program Files (x86)\Yarn\bin\yarn.CMD
    npm: 6.13.7 - C:\Users\Yudy\AppData\Roaming\npm\npm.CMD
  Languages:
    Python: 2.7.16 - /cygdrive/c/Python27/python
  Browsers:
    Edge: 44.18362.449.0
  npmPackages:
    gatsby: ^2.19.5 => 2.19.5
    gatsby-awesome-pagination: ^0.3.5 => 0.3.5
    gatsby-image: ^2.2.39 => 2.2.39
    gatsby-plugin-canonical-urls: ^2.1.20 => 2.1.20
    gatsby-plugin-catch-links: ^2.1.25 => 2.1.25
    gatsby-plugin-draft: 0.0.5 => 0.0.5
    gatsby-plugin-react-helmet: ^3.1.22 => 3.1.22
    gatsby-plugin-react-svg: ^3.0.0 => 3.0.0
    gatsby-plugin-sass: ^2.1.27 => 2.1.27
    gatsby-plugin-sharp: ^2.4.0 => 2.4.0
    gatsby-remark-autolink-headers: ^2.1.24 => 2.1.24
    gatsby-remark-images: ^3.1.42 => 3.1.42
    gatsby-remark-normalize-paths: ^1.0.0 => 1.0.0
    gatsby-remark-prismjs: ^3.3.31 => 3.3.31
    gatsby-remark-relative-images: ^0.2.3 => 0.2.3
    gatsby-source-filesystem: ^2.1.46 => 2.1.46
    gatsby-transformer-remark: ^2.6.50 => 2.6.50
    gatsby-transformer-sharp: ^2.3.13 => 2.3.13
    gatsby-transformer-yaml: ^2.2.24 => 2.2.24

Содержимое файла

├───content
│     ├───data
│     │    ├───authors.js
│     │    └───tags.js
│     ├───images
│     │    └───foo.jpg
│     ├───pages
│     │    └───lorem.md
│     └───posts
│          └───ipsum.md
├───src
│   ├───pages
│   └───templates
│─── static
│─── gatsby-browser.js
│─── gatsby-config.js
│─── gatsby-node.js
└─── package.json

gatsby-config. js

// gatsby-config.js
module.exports = {
    /* Mapping */
    mapping: {
        'MarkdownRemark.frontmatter.tags': `TagsYaml`,
        'MarkdownRemark.frontmatter.author': `AuthorsYaml`,
    },
    plugins: [
        ...
        'gatsby-transformer-yaml',
        {
            resolve: `gatsby-source-filesystem`,
            options: {
                name: `data`,
                path: `${__dirname}/content/data`, // data dir
            },
        },
      ...
    ]
 }

gatsby- node.js

// gatsby-node.js
const path = require('path');
const _ = require('lodash');
const { paginate } = require('gatsby-awesome-pagination');
const { createFilePath } = require(`gatsby-source-filesystem`);
const { fmImagesToRelative } = require('gatsby-remark-relative-images');


exports.onCreateNode = ({ node, getNode, actions }) => {
  fmImagesToRelative(node);
  const { createNodeField } = actions;
  // create fields slug on every markdown
  if (node.internal.type === `MarkdownRemark`) {
    const slug = createFilePath({ node, getNode, basePath: `content` })
    createNodeField({
      node,
      name: `slug`,
      value: slug,
    })
  }
  // create fields slug on every author yaml
  if (node.internal.type === `TagsYaml`) {
    const slug = createFilePath({ node, getNode, basePath: `content` })
    createNodeField({
      node,
      name: `slug`,
      value: slug,
    })
  }
  // create fields slug on every author yaml
  if (node.internal.type === `AuthorsYaml`) {
    const slug = createFilePath({ node, getNode, basePath: `content` })
    createNodeField({
      node,
      name: `slug`,
      value: slug,
    })
  }
}
// Create pages from markdown files
exports.createPages = ({graphql, actions}) => {
    const {createPage} = actions;
    return new Promise((resolve, reject) => {
        resolve(
            graphql(
                `
                query {
                  pages: allMarkdownRemark(
                    filter: { fileAbsolutePath: { regex: "/pages/" } fields: { draft: { eq: false }} }
                    sort: { fields: [frontmatter___title], order: DESC }
                  ) 
                  { 
                    edges {
                      node {
                        id
                        frontmatter {
                          type
                          template
                          title
                          slug
                        }
                      }
                    }
                  }
                  posts: allMarkdownRemark(
                    filter: { fileAbsolutePath: { regex: "/posts/" } fields: { draft: { eq: false }} }
                    sort: { fields: [frontmatter___title], order: DESC }
                  )
                  { 
                    edges {
                      node {
                        id
                        frontmatter {
                          type
                          template
                          title
                          slug
                          tags
                        }
                      }
                    }
                  } 
                  tagsGroup: allMarkdownRemark(
                    filter: {fileAbsolutePath: {regex: "/posts/"}, 
                    fields: {draft: {eq: false}}}, 
                    sort: {fields: [frontmatter___date], 
                    order: DESC}, limit: 2000)
                  {
                    group(field: frontmatter___tags) {
                      fieldValue
                    }
                    edges {
                      node {
                        id
                        frontmatter {
                          type
                          title
                          slug
                          tags
                        }
                      }
                    }
                  }
                  author: allAuthorsYaml 
                  {
                    edges {
                      node {
                        id
                        twitter
                        bio
                        fields {
                          slug
                        }
                      }
                    }
                  }
                }
                `,
            ).then((result) => {
                // Page
                result.data.pages.edges.forEach(({node}) => {
                    //const component = path.resolve({'src/templates/custom/about.js'});
                    createPage({
                      path: node.frontmatter.slug,
                      component: path.resolve(`./src/templates/pages/${node.frontmatter.template}.js`),
                        context: {
                            id: node.id,
                        },
                    });
                });
                // Blog
                result.data.posts.edges.forEach(({node}) => {
                    const component = path.resolve(`./src/templates/posts/${node.frontmatter.template}.js`);
                    createPage({
                        path: `/blog/${node.frontmatter.slug}`,
                        component,
                        context: {
                            id: node.id,
                        },
                    });
                    // Pagination Bloglist
                    const blogPosts = result.data.posts.edges;
                    const pathPrefix = ({ pageNumber, numberOfPages }) => pageNumber === 0 ? '/blog' : '/blog/page'
                    paginate({
                        createPage,
                        items: blogPosts,
                        component: path.resolve('src/templates/posts/list.js'),
                        itemsPerPage: 4,
                        pathPrefix: pathPrefix
                    });
                    // Blog tags
                    const tags = result.data.tagsGroup.group;
                    tags.forEach(tag => {
                      createPage({
                          path: `/blog/tags/${_.kebabCase(tag.fieldValue)}`,
                          component: path.resolve('src/templates/taxonomies/list.js'),
                          context: {
                              tag: tag.fieldValue,
                          },
                      });
                      // Pagination Taglist
                      const tagPrefix = ({ pageNumber, numberOfPages }) => pageNumber === 0 ? `/blog/tags/${_.kebabCase(tag.fieldValue)}` : `/blog/tags/${_.kebabCase(tag.fieldValue)}/page`
                      paginate({
                          createPage,
                          items: tags,
                          component: path.resolve('src/templates/taxonomies/list.js'),
                          itemsPerPage: 4,
                          pathPrefix: tagPrefix,
                          context: {
                              tag: tag.fieldValue,
                          },
                      });
                    })
                    // Author
                    result.data.author.edges.forEach(({ node }) => {
                        createPage({
                        path: `${node.fields.slug}${_.kebabCase(node.id)}`,
                        component: path.resolve(`./src/templates/authors/author.js`),
                        context: {
                            // Data passed to context is available
                            // in page queries as GraphQL variables.
                            slug: node.fields.slug,
                            id: node.id
                        },
                        })
                    });
                });
                resolve();
            }),
        );
    });
};


Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...