Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gatsby.js - GraphQL Query pdf file in allMarkdownRemark

I am currently building a gatsby site for a school project and came across something I couldn't figure out myself.

Basically I have some markdown files. They contain a frontmatter field called 'file' with the name of another file (for example: "test.pdf") as value. I need to know the public URL of these files.

I tried to write my Query like this:

     query SiteQuery{
           publications: allMarkdownRemark(
               filter: { fileAbsolutePath: {regex : "/publications/"} },
               sort: { order: DESC, fields: [frontmatter___date] },
           ){
             edges {
               node {
                 frontmatter {
                   date(formatString: "MMMM DD, YYYY"),
                   title,
                   file{
                     publicURL                   
                   }
                 }
              }
            }
         }
    }

But it always interpreted the field 'file' as string, which I think is strange since I've already did the same procedure with images like this:

...
    node {
      frontmatter {
        date(formatString: "MMMM DD, YYYY"),
        title,
        picture {
          childImageSharp {
            fluid{
              ...GatsbyImageSharpFluid
            }
          }
        }
      } 
    } 
...

I've already searched for an answer, but the most helpful result I could find was on this site: https://www.gatsbyjs.org/docs/adding-images-fonts-files/

But I couldn't make it work.

Can somebody tell me what I am doing wrong here?

Of course I could always write a second query with 'allFile' and then match the markdown file with the pdf file by absolute paths but I hope there's a better solution than that.

like image 667
Lorenz Killer Avatar asked Oct 28 '22 21:10

Lorenz Killer


1 Answers

This is when you want to use mapping, but it's not well documented for anything that isn't a Markdown or JSON file.

gatsby-config.js - mapping

// NOTE: the frontmatter `file` and property `base` must have unique values
// That is, don't allow any files to have the same name if mapping `base`
mapping: {
    'MarkdownRemark.frontmatter.file' : 'File.base',
}

So now you can successfully do:

query SiteQuery{
    publications: allMarkdownRemark(
        filter: { fileAbsolutePath: {regex : "/publications/"} }
        sort: { order: DESC, fields: [frontmatter___date] }
    ){
       edges {
           node {
               frontmatter {
                   date(formatString: "MMMM DD, YYYY")
                   title
                   file {
                       publicURL                   
                   }
               }
           }
       }
    }
}
like image 103
Flying Katsu Avatar answered Nov 12 '22 12:11

Flying Katsu