GraphQL filters in GatsbyJS - graphql

I'm having trouble understanding how to write filters for GraphQL queries in GatsbyJS.
This works:
filter: { contentType: { in: ["post", "page"] }
I basically need the reverse of that, like:
filter: { "post" in: { contentTypes } } // where contentTypes is array
That doesn't work because "NAME is expected" (where "post" is in my example).
After going through GatsbyJS docs I found this:
elemMatch: short for element match, this indicates that the field you are filtering will return an array of elements, on which you can apply a filter using the previous operators
filter:{
packageJson:{
dependencies:{
elemMatch:{
name:{
eq:"chokidar"
}
}
}
}
}
Great! That's what I need! So I try that, and I get:
error GraphQL Error Field "elemMatch" is not defined by type markdownRemarkConnectionFrontmatterTagsQueryList_2.
Keywords defined in markdownRemarkConnectionFrontmatterTagsQueryList_2 are:
eq: string | null;
ne: string | null;
regex: string | null;
glob: string | null;
in: Array | null;
Why am I limited to these keywords when more keywords such as elemMatch are mentioned in docs? Why am I not allowed to use the filter structure "element in: { array }"?
How can I create this filter?

Filter by value in an array
Let's say you have a markdown blog with categories as an array of string, you can filter posts with "historical" in categories like this:
{
allMarkdownRemark(filter:{
frontmatter:{
categories: {
in: ["historical"]
}
}
}) {
edges {
node {
id
frontmatter {
categories
}
}
}
}
}
You can try this query out in any of the graphiq blocks in Gatsby.js docs.
ElemMatch
I think elemMatch is only 'turned on' for fields with array of objects; something like comments: [{ id: "1", content: "" }, { id: "2", content: ""}]. This way, you can apply further filters on the fields of each comment:
comments: { elemMatch: { id: { eq: "1" } } }
Here's an example you can try out in the graphiq blocks in gatsby docs:
// only show plugins which have "#babel/runtime" as a dependency
{
allSitePlugin (filter:{
packageJson:{
dependencies: {
elemMatch: {
name: {
eq: "#babel/runtime"
}
}
}
}
}) {
edges {
node {
name
version
packageJson {
dependencies {
name
}
}
}
}
}
}

Related

How to cast into a type in GraphQL

For example, through GitHub explorer one can retrieve different types of time line items for a pull request (in this example PULL_REQUEST_COMMIT and PULL_REQUEST_REVIEW):
{
repository(name: "react", owner: "facebook") {
pullRequests(last: 10) {
nodes {
number
timelineItems(last: 10, itemTypes: [PULL_REQUEST_COMMIT, PULL_REQUEST_REVIEW]) {
nodes {
__typename
}
}
}
}
}
}
How can I now access different fields of the types PullRequestEvent or PullRequestReviewEvent? In other words, is there a cast or an if-then-else in GraphQL?
nodes returns an array of PullRequestTimelineItems and a PullRequestTimelineItemsis a GraphQL union type. You can use the ...on notation to query for fields of a specific member in the union type:
{
repository(name: "react", owner: "facebook") {
pullRequests(last: 10) {
nodes {
number
timelineItems(last: 10, itemTypes: [PULL_REQUEST_COMMIT, PULL_REQUEST_REVIEW]) {
nodes {
...on PullRequestReview {
body
}
...on PullRequestCommit {
url
}
}
}
}
}
}
}

Attempting to query with graphql where id is

I need to get a query using graphql in strapi/gatsby where id is {id}.
According to the documentation found here you query all like so:
{
allStrapiArticle {
edges {
node {
id
title
content
}
}
}
}
This works and I'm able to query however I'd like to get only one Article where id is {id};
I have tried:
{
allStrapiArticle(id: "4") {
edges {
node {
id
title
content
}
}
}
}
And also:
{
allStrapiArticle {
edges {
node(id: "4") {
id
title
content
}
}
}
}
Both of the above give me an error. Any idea how I can achieve this?
Use:
{
allStrapiArticle(filter: {id: {eq: "4" }}) {
edges {
node {
id
title
content
}
}
}
}
elemMatch filter might be useful for your use case as well.
Check the localhost:8000/___graphql playground to test your queries and filters.
More references:
https://www.gatsbyjs.com/docs/query-filters/
https://www.gatsbyjs.com/docs/graphql-reference/

How to work around GraphQL error, field "x" must not have a selection since type "String" has no subfields

I am using Gatsby and GraphQL, and I am new to GraphQL.
I have the following schema definition:
exports.createSchemaCustomization = ({ actions }) => {
const { createTypes } = actions;
const typeDefs = `
type MarkdownRemark implements Node {
frontmatter: Frontmatter
}
type Frontmatter {
title: String!
products: [Product]
}
type Product #dontInfer {
name: String!
price(price: Int = 1): Float
description: String
images: [ProductImage]
}
type ProductImage {
url: String
}
`;
createTypes(typeDefs);
};
Then on my page I use the following query:
query {
markdownRemark(fileRelativePath: { eq: "/content/pages/products.md" }) {
...TinaRemark
frontmatter {
title
products {
name
price
description
images {
url {
childImageSharp {
fluid(maxWidth: 1920) {
...GatsbyImageSharpFluid_withWebp
}
}
}
}
}
}
html
}
}
I then receive the following error:
Field "url" must not have a selection since type "String" has no subfields.
Does anyone have any suggestions on how to work around this error?
Also, what is childImageSharp? I'm wondering what the terminology is to define it. Is it a GraphQL "selector" or "function"?
It should be
query {
markdownRemark(fileRelativePath: { eq: "/content/pages/products.md" }) {
...TinaRemark
frontmatter {
title
products {
name
price
description
images {
url
}
}
}
html
}
}
Because you definition is
type ProductImage {
url: String
}
The url apparently has no sub fields.
For what it's worth (I don't know if this is related to your specific issue.) If your markdown path for the image file is invalid, GraphQL will return this error, interpreting the path as a string. I had this problem and it went away when I realized I had misspelled the path in the markdown.
productImage {
childImageSharp {
gatsbyImageData(width: 200)
}
}
I had a similar problem with returning a boolean. For me, instead of something like this
mutation {
someFunc(
memo: "test memo"
) {
success
}
}
I needed this
mutation {
someFunc(
memo: "test memo"
)
}

GQL scheme to accept multiple data structure for same key

I'm currently using GQL Modules in my app.
In the below data structure, content will have either object or array
var A = {
content: {
text: "Hello"
}
}
var B = {
content: {
banner: [{
text: "Hello"
}]
}
}
How do I make content to accept dynamic schema ?
Below is what I tired, but not working. Please help
type body {
content: TextContent | [Banner]
}
type Banner {
text: TextContent
}
type TextContent {
text: String
}
GraphQL requires that a field always resolves to either a single value or a list -- it cannot resolve to either. A field can however, return different types altogether at runtime using an abstract type (either a union or an interface). So you can restructure your schema like this:
type Body {
content: Content
}
union Content = TextContent | BannerContent
type TextContent {
text: String
}
type BannerContent {
banners: [Banner]
}
You would then query content using fragments:
query {
someField {
body {
content: {
...on TextContent {
text
}
...on BannerContent {
banners
}
}
}
}
}

Drupal GraphQL - Query Single Entity from URL

Is it possible to get an article(single entity) using the Url Alias (entityUrl.path)?
I am using https://github.com/drupal-graphql/graphql
I can do a bulk query for all the articles, do I then filter those results?
Thanks
query GetArticles {
nodeQuery(filter: {conditions: [{field: "type", value: "article"}]}) {
Articles: entities {
entityId
entityLabel
entityUrl {
path
routed
}
}
}
}
Figured it out
query ($path: String!) {
route:route(path: $path) {
... on EntityCanonicalUrl {
entity {
... on Node {
nid
entityLabel
body{
value
}
}
}
}
}
}

Resources