Exploring directory organization in GraphQL Queries using GatsbyJS

In my portfolio, I have organized my work into categories, pieces, and pictures in a cascading order similar to a child-parent relationship. The folder structure reflects this hierarchy, with the main problem being explained in more detail below.

Folder structure:

work
├── drawing
│   ├── drawing-1
│   │   ├── image.1.jpg
│   │   ├── image.2.jpg
│   │   ├── image.3.jpg
│   │   ├── image.jpg
│   │   └── index.md
│   └── index.md
├── sculpture
│   ├── gaehnschreier
│   │   ├── image.1.JPG
│   │   ├── image.2.jpg
│   │   ├── image.3.JPEG
│   │   ├── image.4.png
│   │   ├── image.PNG
│   │   └── index.md
│   └── index.md
└── watercolor
    ├── index.md
    ├── portrait-1
    │   ├── image.jpg
    │   └── index.md
    └── portrait-2
        ├── image.jpg
        └── index.md

This hierarchical structure is used for the portfolio, starting with the root folder work containing different categories like drawing. Each category has specific pieces represented by folders, each with an index.md file providing detailed information and multiple image files.


gatsby-config.js:

// ...
{
  resolve: 'gatsby-source-filesystem',
  options: {
    name: 'work',
    path: `${__dirname}/work/`,
  },
},
// ...

The gatsby-source-filesystem plugin is used to source and query the work folder specifically with

sourceInstanceName: { eq: "work" }
.


gatsby-node.js:

exports.onCreateNode = ({ node, getNode, actions }) => {

  const { createNodeField } = actions

  if (node.internal.type === `Directory`) {

    if (node.sourceInstanceName === `work`) {

      if (!node.relativeDirectory) {
        createNodeField({
          node,   
          name: `workCategory`,
          value: true,  
        })
      }
    }
  }
}

This code helps flagging categories for future use, such as displaying a list of categories on an overview page.


Example Queries:

{
  allDirectory(
    filter: {
      sourceInstanceName: { eq: "work" }
      relativeDirectory: { eq: "" }
    }
  ) {
    edges {
      node {
        dir
        name
        extension
        relativeDirectory
        relativePath
      }
    }
  }
}

Querying all categories.


{
  allDirectory(
    filter: {
      sourceInstanceName: { eq: "work" }
      relativeDirectory: { eq: "drawing" }
    }
  ) {
    edges {
      node {
        dir
        name
        extension
        relativeDirectory
        relativePath
      }
    }
  }
}

Querying all pieces of the category drawing.


{
  allFile(
    filter: {
      sourceInstanceName: { eq: "work" }
      extension: { in: ["jpg", "jpeg", "png"] }
        relativeDirectory: { eq: "drawing/drawing-1" }
    }
  ) {
    edges {
      node {
        dir
        name
        extension
        relativeDirectory
        relativePath
      }
    }
  }
}

Querying all pictures of the piece drawing-1 within the category drawing.


The issue:

I am looking to iterate through each category to display the works along with their images and descriptions from the index.md file. How can I extract and query the categories separately to retrieve the pieces? How should I map these components together using Gatsby? Are there any suggestions on how to achieve this goal effectively?

EDIT:

I am currently experimenting with using sourceNodes() and creating abstract nodes based on the folder structure. The desired JSON output could resemble the following structure:

{
  "data": {
    "allWorkCategory": {
      "edges": [
        {
          "node": {
            "path": "work/scuplture",
            "children": [
              {
                "node": {
                  "internal": {
                    "type": "WorkItem",
                    "name": "Drawing 1",
                    "pictures": {
                       // ...
                    }
                  }
                }
              }
            ],
            "internal": {
              "type": "WorkCategory"
            }
          }
        },
        {
          "node": {
            "path": "work/drawing",
            "children": [],
            "internal": {
              "type": "WorkCategory"
            }
          }
        },
        {
          "node": {
            "path": "work/watercolor",
            "children": [],
            "internal": {
              "type": "WorkCategory"
            }
          }
        }
      ]
    }
  }
}

Answer №1

If you want to establish a parent / child relationship between gatsby nodes, you can utilize the createParentChildLink method. To locate the parent node, you can make use of the getNodesByType undocumented method.

const path = require('path')
exports.onCreateNode = ({
    node,
    getNodesByType,
    actions
}) => {
    const {
        createParentChildLink
    } = actions

    if (node.internal.type === 'Directory') {
        if (node.sourceInstanceName === 'work') {
            // in some case the trailing slash is missing.
            // Always add it and normalize the path to remove duplication
            const parentDirectory = path.normalize(node.dir + '/')
            const parent = getNodesByType('Directory').find(
                n => path.normalize(n.absolutePath + '/') === parentDirectory
            )
            if (parent) {
                node.parent = parent.id
                createParentChildLink({
                    child: node,
                    parent: parent
                })
            }
        }
    }
}

This is how the corresponding query may look:

    {
      allDirectory(
        filter: {
          sourceInstanceName: { eq: "work" }
            relativeDirectory: { eq: "" }
        }
      ) {
        edges {
          node {
            name
            relativePath
            children {
              __typename ... on Directory {
                name
                relativePath
              }
            }
          }
        }
      }
    }

And the resulting output could resemble this:

    {
      "data": {
        "allDirectory": {
          "edges": [
            {
              "node": {
                "name": "drawing",
                "relativePath": "drawing",
                "children": [
                  {
                    "__typename": "Directory",
                    "name": "drawing-1",
                    "relativePath": "drawing/drawing-1"
                  }
                ]
              }
            },
            {
              "node": {
                "name": "sculpture",
                "relativePath": "sculpture",
                "children": [
                  {
                    "__typename": "Directory",
                    "name": "gaehnschreier",
                    "relativePath": "sculpture/gaehnschreier"
                  }
                ]
              }
            },
            {
              "node": {
                "name": "watercolor",
                "relativePath": "watercolor",
                "children": [
                  {
                    "__typename": "Directory",
                    "name": "portrait-1",
                    "relativePath": "watercolor/portrait-1"
                  },
                  {
                    "__typename": "Directory",
                    "name": "portrait-2",
                    "relativePath": "watercolor/portrait-2"
                  }
                ]
              }
            }
          ]
        }
      }
    }

The usage of __typename ... on Directory allows for querying the complete node instead of just obtaining its ID. For further insights, refer to:

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

evt.target consistently returns the initial input within the list of inputs

My React file uploader allows users to attach multiple file attachments. Each time a user clicks on an input, I retrieve the data-index to identify the input position. renderFileUploader() { let file_attachment = this.state.file_attachment.map(fun ...

Steps for transferring a value to a different page after it has been selected from a listview

web page layout <!DOCTYPE html> <html lang="en"> <head> <title>Student Information</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="styleshe ...

Utilizing JavaScript to implement a single method across multiple objects

Recently, I encountered a problem while trying to use the prototype method to apply the same function or variable to multiple objects. Despite creating numerous objects in the following manner: var item = { a: { aa: "lalala", ab: 1, somethin ...

Interfacing Node JS with Java Web Services via SOAP

I've been attempting to connect Java web services from a Node.js module, but I'm encountering an error in the wsdl library. Below is my wsdl file: <!-- Published by JAX-WS RI (http://jax-ws.java.net). RI's version is JAX-WS RI 2.2.9-b130 ...

Having trouble with the GitHub publish action as it is unable to locate the package.json file in the root directory, even though it exists. Struggling to publish my node package using this

I've been struggling to set up a publish.yml file for my project. I want it so that when I push to the main branch, the package is published on both npm and GitHub packages. However, I am facing difficulties in achieving this. Here is the content of ...

Convince me otherwise: Utilizing a Sinatra API paired with a comprehensive JS/HTML frontend

As I embark on the journey of designing a social website that needs to support a large number of users, I have come up with an interesting approach: Implementing Sinatra on the backend with a comprehensive REST API to handle all operations on the website ...

JavaScript horizontal slider designed for a seamless user experience

Currently, I am in the process of developing a slideshow that includes thumbnails. While my slideshow is functional, I am facing an issue with limited space to display all thumbnails horizontally. I am considering implementing a horizontal slider for the t ...

jQuery is optimized to work specifically with select id tags

Here is the HTML code snippet I've put together, along with my script. While I admit it might look a bit messy, please bear with me as I'm still in the learning phase. If anyone could offer some assistance on this matter, I would be extremely gra ...

Adjusting the dimensions of the canvas leads to a loss of sharpness

When I click to change the size of the graph for a better view of my data in the PDF, the canvas element becomes blurry and fuzzy. Even though I am using $('canvas').css("width","811"); to resize the canvas, it still results in a blurry graph. I ...

Reveal the table only once a search has been completed

Currently, I am in the process of developing a small project and my aim is to have the table with the results appear only upon clicking the button or initiating a search. If you are interested, you can view it at this link: . My objective is to keep the t ...

comparing multiple values separated by commas with JavaScript

I need validation using a comma-separated value format. Within the illustration, there are two fields: "Saloon Price" (value: 10,10,10,10) and "Saloon Offer Price" (value: 11,11,11,11). The first value must be less than the second. Saloon price Value & ...

Attempting to implement form validation on my website

Recently watched a tutorial on basic form validation on YouTube, but I'm encountering an issue where the error messages from my JavaScript file are not displaying on the website during testing. I have set up the code to show error messages above the l ...

Do you need assistance with downloading files and disconnecting from clients?

When looking at the code snippet below: async function (req, res, next) { const fd = await fs.open("myfile.txt") fs.createReadStream(null, { fd, autoClose: false }) .on('error', next) .on('end', () => fs.close(fd)) . ...

Error: Failed to locate package "package-name" in the "npm" registry during yarn installation

While working on a large project with numerous sub-projects, I attempted to install two new packages. However, YARN was unable to locate the packages despite the .npmrc being present in the main directory. ...

What is the best way to extract a JSON object from a website search using getJSON or similar techniques?

Can anyone provide guidance on utilizing .getJSON() to access JSON-encoded information from a website that is being searched? I've implemented a Google Custom Search API for my site with the aim of retrieving the JSON file from the search results. Fo ...

Updating the component's state based on the server response

Injecting the props into the initial state of a component is something I'm working on. The goal is to update the state and have the data reflected immediately when a button inside the component is clicked. The eventData object contains two attributes ...

Utilizing v-model alongside various JavaScript plugins within a single select element

I've incorporated the jQuery plugins select2 and datepicker into my project, utilizing custom directives for them. Everything was functioning smoothly until I attempted to retrieve the selected value using v-model, which resulted in a failure to bind ...

`Express.js Controllers: The Key to Context Binding`

I'm currently working on a project in Express.js that involves a UserController class with methods like getAllUsers and findUserById. When using these methods in my User router, I have to bind each method when creating an instance of the UserControlle ...

Enhancing user input with multiple values in a textarea using JSTL

I'm having trouble inputting multiple values into a textarea using JSTL. Here is the coding snippet I am using: <label>Resources</label> : <c:forEach items="${MEETING_ENTITY}" var="resource"> <textarea id ...

Save the language code (ISO 639) as a numerical value

Currently, I'm working with a MongoDB database and have made the decision to store certain information as Numbers instead of Strings for what I thought would be efficiency reasons. For instance, I am storing countries based on the ISO 3166-1 numeric s ...