Skip to content

Commit

Permalink
feat: Programatically create pages for all components/apis
Browse files Browse the repository at this point in the history
jerelmiller committed Jun 28, 2020
1 parent 541f9bd commit 1858e28
Showing 1 changed file with 72 additions and 12 deletions.
84 changes: 72 additions & 12 deletions gatsby-node.js
Original file line number Diff line number Diff line change
@@ -3,11 +3,35 @@ const path = require(`path`);
const getFileRelativePath = (absolutePath) =>
absolutePath.replace(`${process.cwd()}/`, '');

const kebabCase = (string) =>
string
.replace(/([a-z])([A-Z])/g, '$1-$2')
.replace(/\s+/g, '-')
.toLowerCase();

exports.createPages = async ({ actions, graphql, reporter }) => {
const { createPage, createRedirect } = actions;

const result = await graphql(`
{
allNewRelicSdkApi {
edges {
node {
fields {
slug
}
}
}
}
allNewRelicSdkComponent {
edges {
node {
fields {
slug
}
}
}
}
allMdx(limit: 1000) {
edges {
node {
@@ -29,7 +53,23 @@ exports.createPages = async ({ actions, graphql, reporter }) => {
return;
}

result.data.allMdx.edges.forEach(({ node }) => {
const { allMdx, allNewRelicSdkApi, allNewRelicSdkComponent } = result.data;

allNewRelicSdkApi.edges.forEach(({ node }) => {
createPage({
path: node.fields.slug,
component: path.resolve('./src/templates/ApiReferenceTemplate.js'),
});
});

allNewRelicSdkComponent.edges.forEach(({ node }) => {
createPage({
path: node.fields.slug,
component: path.resolve('src/templates/ComponentReferenceTemplate.js'),
});
});

allMdx.edges.forEach(({ node }) => {
const { frontmatter } = node;

if (frontmatter.redirects) {
@@ -43,21 +83,25 @@ exports.createPages = async ({ actions, graphql, reporter }) => {
});
}

createPage({
path: frontmatter.path,
component: path.resolve(`src/templates/${frontmatter.template}.js`),
context: {
fileRelativePath: getFileRelativePath(node.fileAbsolutePath),
guidesFilter:
frontmatter.template === 'OverviewTemplate'
? `${frontmatter.path}/*`
: undefined,
},
});
if (node.template !== 'ComponentReferenceTemplate') {
createPage({
path: frontmatter.path,
component: path.resolve(`src/templates/${frontmatter.template}.js`),
context: {
fileRelativePath: getFileRelativePath(node.fileAbsolutePath),
guidesFilter:
frontmatter.template === 'OverviewTemplate'
? `${frontmatter.path}/*`
: undefined,
},
});
}
});
};

exports.onCreateNode = ({ node, actions }) => {
const { createNodeField } = actions;

// if we don't have a relative path, attempt to get one
if (node.context && !node.context.fileRelativePath) {
const { createPage } = actions;
@@ -71,4 +115,20 @@ exports.onCreateNode = ({ node, actions }) => {
},
});
}

if (node.internal.type === 'NewRelicSdkComponent') {
createNodeField({
node,
name: 'slug',
value: `/components/${kebabCase(node.name)}`,
});
}

if (node.internal.type === 'NewRelicSdkApi') {
createNodeField({
node,
name: 'slug',
value: `/apis/${kebabCase(node.name)}`,
});
}
};

0 comments on commit 1858e28

Please sign in to comment.