我正在与盖茨比建立一个网站。 我有几个Mdx页面。其中某些页面彼此“相关”(通过 slug )。 例如:
pageone.mdx
-- frontmatter --
image: "team.jpg"
pagetwo.mdx
-- frontmatter --
image: "second.jpg"
relateds:
- pagetwo
我的gatsby-node.js的摘录
const path = require(`path`)
const { createFilePath } = require(`gatsby-source-filesystem`)
exports.onCreateWebpackConfig = ({
stage,
rules,
loaders,
plugins,
actions, }) => {
actions.setWebpackConfig({
module: {
},
plugins: [
plugins.define({
__DEVELOPMENT__: stage === `develop` || stage === `develop-html`,
}),
],
node: {
fs: "empty",
},
})
}
exports.onCreateNode = ({ node, getNode, actions }) => {
const { createNodeField } = actions
if (node.internal.type === `Mdx`) {
const value = createFilePath({ node, getNode })
const image = node.frontmatter.image
createNodeField({
node,
name: `slug`,
value: value,
})
createNodeField({
node,
name: `image`,
value: image,
})
}
}
exports.createPages = async ({ graphql, actions , reporter}) => {
const { createPage } = actions
const result = await graphql(`
query {
allMdx {
edges {
node {
id
fields {
slug
image
}
}
}
}
}
`)
if (result.errors) {
reporter.panicOnBuild('? ERROR: Loading "createPages" query')
}
const pages = result.data.allMdx.edges
pages.forEach(({ node }, index) => {
createPage({
path: node.fields.slug,
component: path.resolve(`./src/templates/mdTemplate.js`),
context: { id: node.id,
image: node.fields.image },
})
})
}
exports.createSchemaCustomization = ({ actions }) => {
const { createTypes } = actions
const typeDefs = `
type Mdx implements Node {
image: String,
relateds: [Mdx] @link(by: "slug", from: "relateds")
}
`
createTypes(typeDefs)
}
我的目标是为每个节点获取他的“相关内容”。
将上面的代码添加为白色,对于每个mdx节点,我都有一个“ relateds”字段,但是如果使用graphql客户端进行浏览,则会得到: null
答案 0 :(得分:1)
使用“解析器”解决:
exports.createResolvers = ({ createResolvers }) => {
const resolvers = {
Mdx: {
// To transform the Frontmatter relateds to Mdx nodes
relateds: {
resolve: (source, args, context, info) => {
const relpages = ('relateds' in source.frontmatter) ? context.nodeModel.runQuery({
type: `Mdx`,
query: {
filter : {
slug: {
in: source.frontmatter.relateds
}
}
}
}) : []
return relpages
}
}
}
}
createResolvers(resolvers)
}