GraphQL Filter on Enum Column - graphql

Below is my GraphQL Query to Fetch Posts from Strapi backend.
Please note I am running this on my Nuxt app.
Now I want to bring only those posts which have post_status = "Publish"
post_status is a ENUM field with two option as Draft and Publish
query GetPosts{
posts {
id
post_title
post_excerpt
post_featured_image{url}
post_content
post_category{category_name}
postingredients{ingredient{ingredient_name}, ingredient_unit}
updated_at
post_author{username}
post_slug
}
}
I did not understand how can I get
How to bring post_status values on my original Query
How to filter on the post_status where I can get only Published posts.
query GetStatusEnum{
__type(name: "ENUM_POST_POST_STATUS") {
name
enumValues {
name
} } }
Result of the above:
{
"data": {
"__type": {
"name": "ENUM_POST_POST_STATUS",
"enumValues": [
{
"name": "Publish"
},
{
"name": "Draft"
}
]
}
}
}

To add your post_status in your original request you just have to add it in the list of the attributes you want to fetch.
{
posts {
id
post_title
post_status <- here /!\
}
}
Here is the query to fetch Posts that have Publish as post_status
{
posts(where: { post_status: "Publish" }) {
id
post_title,
post_status
}
}
You can play with GraphQL playground in your strapi application:
http://localhost:1337/graphql
You will see in the right of you page a docs button that will show you all the information you need to create your GraphQL request.

I had a similar scenario (though I'm using a Prisma layer as well so keep that in mind) and i'm not sure that you can filter for enum values on the call but you can filter what it returns.
const posts = [the array of all posts]
const isPublished = (post) => {
if (post.post_status.includes('Publish')) {
return post;
}
}
let publishedPosts = posts.filter(isPublished);
return publishedPosts;

Related

Contentful graphql one too many relationship

I am trying to achieve this: getArticleBySlugWithFilteredTags('tag1', 'tag2', 'tag3') using 1 query ( 1 request ) and avoid clientside filtering ( grab many and filter out with javascript ).
I have content type Article that has an entry type as list: Tag ( another custom content type ).
So there is a one too many relationship: an Article can have multiple Tags.
Now getting back to this: getArticleBySlugWithFilteredTags('tag1', 'tag2', 'tag3').
Attempt using custom content type: Tag
Query:
data: articleCollection(limit: 1, where: {
slug: "article-unique-1",
}) {
items {
title
tagsCollection(limit: 5) { // here it would be nice if I can use "where": {name: "tag1"}
items {
name
value
linkedFrom {
relatedArticles: articleCollection(limit: 7) { // other related articles that has the same tag as parent Article
items {
slug
title
category
}
}
}
}
}
}
}
}
The only thing that is missing here is the that I need to filter out the tagsCollection ( based on some property: name or value ).
I see that I am limited to use "where" on tagsCollection.
Attempt using contentfulMetadata tags
Query
{
data: articleCollection(where:
{
slug: "article-unique-1",
contentfulMetadata: {
tags_exists: true,
tags: {
id_contains_some: ["tag1", "tag2"]
}
}
}) {
items {
contentfulMetadata {
tags {
id
name
linkedFrom { // I can't use this here
relatedArticles: articleCollection(limit: 7) {
items {
slug
title
category
}
}
}
}
}
slug
title
publicationDate
}
}
}
With this approach I am not able to use the linkedFrom in order to get also other related articles that have the same contentfulMetadata tags. What should I do in other to achieve this making 1 query and no clientside filtering with javascript ?

Shopify Admin API, graphQL, create draft order - add products

This is my fist time creating an order. From what I understand you need to create a draft order - add products, price, email, notes etc. I am just creating a test query now to see how it works and it tells me "Add at least 1 product". I am trying to add a product, but I dont know how. I have been messing around and reading and cant figure it out.
This is my query:
mutation draftOrderCreate {
draftOrderCreate(input: {email: "123abc#hotmail.com"}) {
draftOrder {
id
order {
id
}
status
}
userErrors {
field
message
}
}
}
If anyone can give me an example on how to add products to this would be great. Thanks.
You can create an draft order like so:
mutation draftOrderCreate($items: DraftOrderInput!) {
draftOrderCreate(input: $items) {
draftOrder {
id
order {
id
}
status
}
userErrors {
field
message
}
}
}
query variables:
{
"items": {
"email": "123abc#hotmail.com",
"lineItems": [
{
"variantId": "gid://shopify/ProductVariant/32231002996788",
"quantity": 1
}
]
}
}
Or if you don't want to use query variables you can pass the whole object as the input:
mutation draftOrderCreate {
draftOrderCreate(input: {email: "123abc#hotmail.com", lineItems: [{variantId: "gid://shopify/ProductVariant/32231002996788", quantity: 1}]}) {
draftOrder {
id
order {
id
}
status
}
userErrors {
field
message
}
}
}

Dynamically create pages with Gatsby based on many Contentful references

I am currently using Gatsby's collection routes API to create pages for a simple blog with data coming from Contentful.
For example, creating a page for each blogpost category :
-- src/pages/categories/{contentfulBlogPost.category}.js
export const query = graphql`
query categoriesQuery($category: String = "") {
allContentfulBlogPost(filter: { category: { eq: $category } }) {
edges {
node {
title
category
description {
description
}
...
}
}
}
}
...
[React component mapping all blogposts from each category in a list]
...
This is working fine.
But now I would like to have multiple categories per blogpost, so I switched to Contentful's references, many content-type, which allows to have multiple entries for a field :
Now the result of my graphQL query on field category2 is an array of different categories for each blogpost :
Query :
query categoriesQuery {
allContentfulBlogPost {
edges {
node {
category2 {
id
name
slug
}
}
}
}
}
Output :
{
"data": {
"allContentfulBlogPost": {
"edges": [
{
"node": {
"category2": [
{
"id": "75b89e48-a8c9-54fd-9742-cdf70c416b0e",
"name": "Test",
"slug": "test"
},
{
"id": "568r9e48-t1i8-sx4t8-9742-cdf70c4ed789vtu",
"name": "Test2",
"slug": "test-2"
}
]
}
},
{
"node": {
"category2": [
{
"id": "75b89e48-a8c9-54fd-9742-cdf70c416b0e",
"name": "Test",
"slug": "test"
}
]
}
},
...
Now that categories are inside an array, I don't know how to :
write a query variable to filter categories names ;
use the slug field as a route to dynamically create the page.
For blogposts authors I was doing :
query authorsQuery($author__slug: String = "") {
allContentfulBlogPost(filter: { author: { slug: { eq: $author__slug } } }) {
edges {
node {
id
author {
slug
name
}
...
}
...
}
And creating pages with src/pages/authors/{contentfulBlogPost.author__slug}.js
I guess I'll have to use the createPages API instead.
You can achieve the result using the Filesystem API, something like this may work:
src/pages/category/{contentfulBlogPost.category2__name}.js
In this case, it seems that this approach may lead to some caveats, since you may potentially create duplicated pages with the same URL (slug) because the posts can contain multiple and repeated categories.
However, I think it's more succinct to use the createPages API as you said, keeping in mind that you will need to treat the categories to avoid duplicities because they are in a one-to-many relationship.
exports.createPages = async ({ graphql, actions }) => {
const { createPage } = actions
const result = await graphql(`
query {
allContentfulBlogPost {
edges {
node {
category2 {
id
name
slug
}
}
}
}
}
`)
let categories= { slugs: [], names: [] };
result.data.allContentfulBlogPost.edges.map(({node}))=> {
let { name, slug } = node.category2;
// make some checks if needed here
categories.slugs.push(slug);
categories.names.push(name);
return new Set(categories.slugs) && new Set(categories.names);
});
categories.slugs.forEach((category, index) => {
let name = categories.names[index];
createPage({
path: `category/${category}`,
component: path.resolve(`./src/templates/your-category-template.js`),
context: {
name
}
});
});
}
The code's quite self-explanatory. Basically you are defining an empty object (categories) that contains two arrays, slugs and names:
let categories= { slugs: [], names: [] };
After that, you only need to loop through the result of the query (result) and push the field values (name, slug, and others if needed) to the previous array, making the needed checks if you want (to avoid pushing empty values, or that matches some regular expression, etc) and return a new Set to remove the duplicates.
Then, you only need to loop through the slugs to create pages using createPage API and pass the needed data via context:
context: {
name
}
Because of redundancy, this is the same than doing:
context: {
name: name
}
So, in your template, you will get the name in pageContext props. Replace it with the slug if needed, depending on your situation and your use case, the approach is exactly the same.

How to transform Markdown query to Strapi query on GraphiQL?

I'm trying to get my hands on Gatsby + Strapi development (adding Material for styling), I'm new to both Gatsby and Strapi although I have some basic knowledge of React and it's making the way easier to follow.
I'm using this Gatsby Starter: https://www.gatsbyjs.org/starters/Vagr9K/gatsby-material-starter/ which includes the Material design I'm trying to achieve, but I'm having some trouble changing the Markdown queries to Strapi queries to avoid making a lot of code changes (posts are exactly the same but stored in Strapi). I have three Content Types in Strapi corresponding to the three different pages the original starter provides: Post, Category, and Tag.
This is the original MarkdownRemark graphQL query included in the post.jsx template:
query BlogPostBySlug($slug: String!) {
markdownRemark(fields: { slug: { eq: $slug } }) {
html
timeToRead
excerpt
frontmatter {
title
cover
date
category
tags
}
fields {
slug
date
}
}
}
How can I change it to retrieve the same info from Strapi?
I'm really new to this Strapi world so I'm having a lot of doubts with the GraphQL, as I can't follow the guide from the Markdown query because the Information displayed is not the same.
I'm also having trouble differentiating between allStrapiArticles and StrapiArticle, what's the main purpose of those?
EDIT: I've been testing the existing queries on GraphiQL to check what they are returning and this is what I'm seeing:
For the tag.jsx query:
query TagPage($tag: String) {
allMarkdownRemark(
limit: 1000
sort: { fields: [fields___date], order: DESC }
filter: { frontmatter: { tags: { in: [$tag] } } }
) {
totalCount
edges {
node {
fields {
slug
date
}
excerpt
timeToRead
frontmatter {
title
tags
cover
date
}
}
}
}
}
GraphiQL returns nothing:
{
"data": {
"allMarkdownRemark": {
"totalCount": 0,
"edges": []
}
}
}
For the category.jsx query:
query CategoryPage($category: String) {
allMarkdownRemark(
limit: 1000
sort: { fields: [fields___date], order: DESC }
filter: { frontmatter: { category: { eq: $category } } }
) {
totalCount
edges {
node {
fields {
slug
date
}
excerpt
timeToRead
frontmatter {
title
tags
cover
date
}
}
}
}
}
In this case, everything works fine and it retrieves article data.
And for the case of the query I've added as an example in this post (upper part of the question) I'm getting the following error:
"errors": [
{
"message": "Variable \"$slug\" of required type \"String!\" was not provided."
...
Make sure you are passing your variable in through Query Variables at the bottom of GraphiQL.
First, I would query AllMarkdownRemark to make sure you're getting the nodes from Gatsby. Something like:
query MyQuery {
allMarkdownRemark {
edges {
node {
fields {
slug
}
frontmatter {
title
}
}
}
}
}
If the slug is showing up, then this should work:
Sometimes a slug is not being generated. Which should show up checking allMarkdownRemark.

Is it possible for vue-apollo to return different results from the Playground?

I have a GraphQL query called myAccounts which returns an array of accounts. When I go to the Playground and call the query:
{
accounts {
email
}
}
I get this result:
"data": {
"accounts": [
{
"email": "zach#email-one.com",
},
{
"email": "zach#email-two.com",
}
]
}
However, when I am in my Component, vue-apollo returns two items in the array, but seems to overwrite the second item with the first. Here is the query (in MyAccounts.gql):
query myAccounts {
accounts: myAccounts {
email
}
}
and here is the Apollo query in the component:
import MY_ACCOUNTS_QUERY from '~/apollo/queries/MyAccounts'
...
apollo: {
accounts: {
query: MY_ACCOUNTS_QUERY,
result(data) {
console.log(JSON.stringify(data))
}
}
}
and here is what vue-apollo logs out through the result:
{
"data":{
"accounts":[
{
"email":"zach#email-one.com",
"__typename":"Account"
},
{
"email":"zach#email-one.com",
"__typename":"Account"
}
]
},
"loading":false,
"networkStatus":7,
"stale":false
}
Expected behavior
I would expect the data returned in the Playground to be identical to what vue-apollo is fetching.
Versions
vue: 2.6.10
vue-apollo: #nuxtjs/apollo: 4.0.0-rc18
Additional context
I thought the result hook would be the best way to debug, but any other suggestions gladly welcomed. I assumed that this was a bug in our code, but I cannot figure out what could be causing the repetition (and mismatch).
Apollo normalizes its cache based on the __typename and the id (or _id) field. You need to include an id or _id field in your selection set alongside email. Failing to do so results in both objects being assigned the same key. If you don't have an id field to request, you'll need to provide a custom dataIdFromObject function as shown here.
From Guillaume Chau (https://github.com/Akryum):
This is because the Apollo Client cache can't compute a different ID
for the two items, so you endup with Account:undefined (or similar)
for both. Open the Apollo devtools and look at the myAccounts key in
the cache.
Learn more:
https://www.apollographql.com/docs/react/caching/cache-configuration/

Resources