1
0
mirror of https://github.com/kremalicious/gatsby-redirect-from.git synced 2024-06-26 03:06:40 +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(
`
{
q: ${markdownQuery}(
2018-08-30 01:11:52 +02:00
filter: { frontmatter: { redirect_from: { ne: null } } }
) {
edges {
node {
fields {
slug
}
frontmatter {
redirect_from
}
}
}
}
}
`
2020-05-17 01:58:03 +02:00
).then((result) => {
2018-08-30 01:11:52 +02:00
if (result.errors) {
console.log(result.errors) // eslint-disable-line no-console
reject(result.errors)
}
const allPosts = result.data.q.edges
2018-08-30 01:11:52 +02:00
const redirects = []
// For all posts with redirect_from frontmatter,
// extract all values and push to redirects array
2020-05-17 01:58:03 +02:00
allPosts.forEach((post) => {
2018-08-30 01:11:52 +02:00
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
2020-05-17 01:58:03 +02:00
from.forEach((from) => {
2018-08-30 01:11:52 +02:00
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
)
})
)
})
}