I want to create a page that shows all blog posts by a specific category. The category is defined an a frontmatter tag called category.
Previously I used this query:
query BlogPostByCategory($category: String!) {
allMarkdownRemark(filter: {frontmatter: {category: {eq: $category}}}) {
edges {
node {
frontmatter {
title
category
}
}
}
}
}
This works for most cases. But it might happen that someone writes the category case sensitive (eg. Gatsby vs gatsby).
So I wanted to use a regex with the i modifier to prevent this. The following query works in the GraphiQL console:
query BlogPostByCategory($category: String!) {
allMarkdownRemark(filter: {frontmatter: {category: {regex: "/$category/i"}}}) {
edges {
node {
frontmatter {
title
category
}
}
}
}
}
But it returns the following error in GatsbyJS:
GraphQLError: Variable "$category" is never used in operation "BlogPostByCategory".
Does anybody have an idea how to use a variable in a filter using regex?
This currently isn't possible since there's no way of interpolating strings in GraphQL. You can work around this by building the regex in gatsby-node.js and passing the whole regex to the query:
query BlogPostByCategory($categoryRegex: String!) {
allMarkdownRemark(filter: {frontmatter: {category: {regex: $categoryRegex}}}) {
edges {
node {
frontmatter {
title
category
}
}
}
}
}
By the way, based on the sift.js docs the regex should either be a regex (regex: /^f/i), or a string with a separate options parameter (regex: "^f", options: "i"), not a regex wrapped in a string like your regex: "/^f/i".
I'm now building the regex in gatsby-node.js and that works, thanks @jgierer12 !
But in Gatsby you can only use the regex as a string in your query. When using {regex: /category/}, my query is invalid.
Not sure if we should close this ticket since it currently is not possible, or build in this feature?
I think it's best we close this issue since your original question has been resolved. If you want, you can open a new issue specifically about using the /.../ syntax for RegExps.
Most helpful comment
This currently isn't possible since there's no way of interpolating strings in GraphQL. You can work around this by building the regex in
gatsby-node.jsand passing the whole regex to the query:By the way, based on the sift.js docs the regex should either be a regex (
regex: /^f/i), or a string with a separate options parameter (regex: "^f", options: "i"), not a regex wrapped in a string like yourregex: "/^f/i".