1
0
mirror of https://github.com/kremalicious/gatsby-redirect-from.git synced 2024-06-29 00:57:42 +02:00
gatsby-redirect-from/src/gatsby-node.js

68 lines
1.7 KiB
JavaScript
Raw Normal View History

2018-08-30 13:12:47 +02:00
import chalk from 'chalk'
2018-08-30 01:11:52 +02:00
2019-01-08 13:33:46 +01:00
export function createPages({ graphql, actions }, pluginOptions) {
2018-08-30 01:11:52 +02:00
const { createRedirect } = actions
2019-01-08 13:33:46 +01:00
const markdownQuery = pluginOptions.query || 'allMarkdownRemark'
2018-08-30 01:11:52 +02:00
return new Promise((resolve, reject) => {
resolve(
graphql(
`
{
2019-01-08 13:33:46 +01:00
${markdownQuery}(
2018-08-30 01:11:52 +02:00
filter: { frontmatter: { redirect_from: { ne: null } } }
) {
edges {
node {
fields {
slug
}
frontmatter {
redirect_from
}
}
}
}
}
`
).then(result => {
if (result.errors) {
console.log(result.errors) // eslint-disable-line no-console
reject(result.errors)
}
const allPosts = result.data.allMarkdownRemark.edges
const redirects = []
// For all posts with redirect_from frontmatter,
// extract all values and push to redirects array
allPosts.forEach(post => {
redirects.push({
from: post.node.frontmatter.redirect_from,
to: post.node.fields.slug
})
})
// Create redirects from the just constructed array
redirects.forEach(({ from, to }) => {
// iterate through all `from` array items
from.forEach(from => {
createRedirect({
fromPath: from,
toPath: to,
isPermanent: true,
redirectInBrowser: true
})
})
})
resolve(
2018-08-30 13:12:47 +02:00
console.log(`${chalk.green('success')} create redirects`) // eslint-disable-line no-console
2018-08-30 01:11:52 +02:00
)
})
)
})
}