In this lesson we learn how to make sure the data directory exists so gatsby-source-filesystem doesn't throw an error.
Within the gatsby-theme-events folder, create a file named gatsby-node.js
In our gatsby-node.js, we need to
- Make sure the data directory exists
We need to do this so gatsby-source-filesystem
doesn't throw an error.
- Define the event type
If we don't have any events defined, we should get back an empty array, not an error.
- Define resolvers for any custom fields (slug)
We are going to have a custom slug
field. We want to be able to query this along with all of the other event data.
- Query for events and create pages
gatsby-source-filesystem will throw an error if you fire up your theme and the “data” directory doesn’t exist. To guard against this, you’ll use the onPreBootstrap API hook to check if the data directory exists, and, if not, create it:
const fs = require('fs');
exports.onPreBootstrap = ({ reporter }) => {
const contentPath = 'data';
if (!fs.existsSync(contentPath)) {
reporter.info(`creating the ${contentPath} directory`);
fs.mkdirSync(contentPath);
}
};
With this code, if the data directory doesn't exist, it will create it. Now we have ensured that the data directory exists.