How can I query my data by published date (newest first) using Apollo and Graphql? - sorting

I have React page that is fetching data via Graphql.
I'm using Strapi as backend and queries are already generated.
I´m querying my data in the frontend like this
query GetData{
datas(limit:3){
id
published_at
}
}
In the documentation I found this example about how to sort my queries by some especific order
GET /users?_sort=email:ASC,dateField:DESC
but is not really clear how to use it with the query structure.
I tried something like this and other variations
query GetPodcasts{
podcasts?_sort=published_at:DESC(limit:3){
id
published_at
}
}
but it didn't work.
I may need some help understanding this.

In a forum some nice people also gave me an answer.
When using graphql in frontend and want to sort or filter the data, just have to use "" to specify the sort or filter.
In my case it just had to be:
query GetData{
datas(limit:3, sort:"published_at:desc"){
id
published_at
}
}

Graphql is like an Rest Api but with one end point to the server ,
this query with name GetData , point to datas query but you should define this query in the backend.
please watch some tutorials that will guide you step by step.
you can learn more about graphql here
https://graphql.org/learn/
try this:
query GetData{
datas(input:{
sort:{id:"asc"},
data:{limit:3}
}){
id
published_at
}
}
for more info
https://strapi.io/documentation/developer-docs/latest/development/plugins/graphql.html#query-api

This seem to work for me in Strapi v4:
sort: "publishedAt:DESC"
...
query GetVideos($page: Int!, $pageSize: Int!) {
videos(
pagination: { page: $page, pageSize: $pageSize }
sort: "publishedAt:DESC"
) {
__typename
data {
__typename
id
attributes {
__typename
createdAt
publishedAt
}
}
}
}
}
`

Related

cant use any filter parameters on graphql in strapi

I have been unable to use any of the filter parameters on graphl query in strapi using the url (http://localhost:1337/graphql). I am using strapi 3.6.8 . I have a collection (Animals) that has an array of Habitat. When I try to limit the number of Habitat returned for each record to 3, it doesn't work with the query below.
query{
Animals {
id
Habitat(limit: 3) {
Feature {
Weight
Height
Lifespan
}
}
}
}
I get the error message: "Unknown argument "limit" on field "Animal.Habitat"."
the limit, where or any other filter does not work. They work however when I use them on the Animals itself. Kindly help
If you are on graphql playground, try pressing CTRL + SPACE and you will see the available parameters that you can use inside your query. In your case, I assume you want to use the pagination feature provided by Strapi. The following query should work.
query {
Animals {
id
Habitat(pagination: { limit: 3 }) {
Feature {
Weight
Height
Lifespan
}
}
}
}

How to query a map of id with graphql?

I am trying to query an array of ids with graphQl. The query works with a single id as a variable. However it doesn't work when I enter an array of ids.
Here is my gql query with variables:
query GetAuthorContent($id: [ID]!, $idType: AuthorIdType) {
expert(id: $id, idType: $idType) {
excerpt
featuredImage {
node {
description
author {
node {
description
}
}
}
}
slug
}
}
{"id": ["author-1", "author-2", "author-3"], "idType": "SLUG" }
You can look at the definition of the graphql endpoint using a client and see if the Arrays are supported with query.
If it's supported, check the mutation signature and pass accordingly. In this case I think the services does not support querying using an Array.
Hi everyone and thank you for your help.
You guys were right, my DB doesn't allow an array of authors if it is per author singular. However it works with authors plural. This is the way my db works.
Hope it can help someone in the same situation.

GraphQL Tag dynamic table name in query (apollo)

In my app every customer has a own table for its data. Depending on which customer was selected I want to dynamically build the tablename for the Graphql query.
For example:
// Query for customer 1
gql`
query overviewQuery {
customer_1 {
aggregate {
count
}
}
}
`
// Query for customer 2
gql`
query overviewQuery {
customer_2 {
aggregate {
count
}
}
}
`
I have the customer id in my vuex store and want to insert a variable into the query like in the following pseudocode which is not working.
const tblUserAggregateName = `customer_${this.$store.state.customer.customerId`
gql`
query overviewQuery {
${this.tblUserAggregateName} {
aggregate {
count
}
}
`
Is there an option how to do this or how can this problem be solved?
It is not an option to hardcode all different customer queries and selected them on runtime.
Thanks!
In the answers it was mentioned, that it is against best practice to dynamically change the table name of GraphQL queries.
As changing the complete database structure for all clients (they each have a separate Database with a own PostgreSQL schema name) is not an option, I found a solution the looks a little bit hacky and definitely not best practice but I thought I might be interesting to share for others with the same problem.
The approach is pretty easy: I write the query as a simple string where I could use variables and convert them later to the gql AST Object with graphql-tag
const query = () => {
const queryString = `
{
${customerId}_table_name {
aggregate {
count
}
}
}`
return gql`${queryString}`
}
Works, but I you have a better solution, I am happy to learn!
You can supply variables, but they should not be used to dynamically infer schema object names. This violates core concepts of GraphQL. Try this instead:
gql`
query overviewQuery ($customerId: ID!) {
customerData (id: $customerId) {
tableName
aggregate {
count
}
}
}`
Apollo provides great documentation on how to supply variables into a query here: https://www.apollographql.com/docs/react/data/queries/
The backend can then use the customerId to determine what table to query. The client making requests does not need to know (nor should it) where that data is or how it's stored. If the client must know the table name, you can add a field (as shown in the example)

Passing variables in GraphQL

I'm trying to run a GraphQL query in the AWS AppSync console:
query MyQuery {
getUserInfoById(id: "1234566789") {
account {
id // need this value for getAvailableCourses
}
}
getAvailableCourses(accountId: "", pageNumber: 0) {
data {
id
name
type
}
}
}
Basically I need the value account.id in getUserInfoById for getAvailableCourses. I'm obviously new to GraphQL. How would I go about this?
To the best of my knowledge, there can be two ways you can do this.
You can handle this in your frontend by getting user's id
from the session info and pass it to the other query.
You can also merge these two queries and make it one. You will also have to change the respective fields. Then attach a resolver with AvailableCourses and use $ctx.source.id in the resolver to get further details. Schema would look something like this
type Account {
id : ID!
availableCourses: AvailableCourses
..
}
type AvailableCourses {
name: String!
type: String!
..
}
type Query {
getUserInfoById(id: ID!): Account
}
Using the returned fields as inputs for a second query into your datasource is precisely what field resolvers are for. I can't say for sure since I don't know your schema or access patterns but it looks like you need to make available courses a sub field of the user.

GraphQL: Is it possible to search nested field?

I am specifically using the shopify graphql admin api to query orders.
I want to do a search for a nested related field.
Below is my query.
export const orderHistoryQuery = gql`
query Order($productsFirst: Int!, $productsAfter: String, $filterQuery: String) {
orders(first: $productsFirst, after: $productsAfter, reverse: true, query:$filterQuery) {
edges {
cursor
node {
id
name
customer {
id
metafields(first: 10) {
edges {
node {
id
key
value
namespace
}
cursor
}
}
}
totalPriceSet {
shopMoney {
amount
currencyCode
}
}
subtotalPriceSet {
shopMoney {
amount
currencyCode
}
}
totalRefundedSet {
shopMoney {
amount
currencyCode
}
}
currencyCode
email
phone
processedAt
totalShippingPriceSet {
shopMoney {
amount
currencyCode
}
}
totalTaxSet {
shopMoney {
amount
currencyCode
}
}
shippingAddress {
firstName
lastName
address1
address2
city
province
zip
country
}
billingAddress {
firstName
lastName
address1
address2
city
province
zip
country
}
customAttributes {
key
value
}
}
}
}
}
`;
I want to query metafields or ANYTHING really but it doesn't seem like it's supported. I am not sure if I just have the wrong query syntax or if it's not supported. The shopify search syntax documenation doesn't really help and this is where my knowledge of graphql falls apart.
Is it possible to do this in graphql? I also tried adding metafields(id: $whateverID) which is not supported by their setup.
Unfortunately, Shopify doesn't support query filters on metafields. The best way to figure this out is by using a graphql explorer like GraphiQL. Shopify dashboard has this built in if you go to Apps > Shopify GraphiQL App.
Using GraphiQL you can see that:
Customers query doesn't have metafields supported:
Orders query doesn't have customers or metafields supported:
And metafields on customers doesn't have a query param:
I think your options are to either query by what you can and filter after you get the results or use a customer tag and query by tag.
You would really help your cause out by simplifying things. My advice to you is to try a simple query. Can you get an order? Since an order has a customer (usually but not always), can you get a metafield associated with that customer?
You have so many obstacles in your attempt to show what you are trying to do, it is almost as if you want a migraine headache in trying to debug anything. GraphQL calls to endpoints are documented fairly well from the GraphQL website perspective, and Shopify is nothing but a vanilla implementation of that, with the caveat that they charge you for calls based on complexity, so you had best be monitoring your credits.
So ya, try simple calls. Get a product and it's Metafields. Get a customer record and it's Metafields. If you can do that, you are not challenging the documentation much, nor the concept of GraphQL queries. Once a basic all works, you can work in variables, cursors, paging, etc... but until a one-off call gives you what you want, debugging should be concentrated on the simplest of calls, not everything and the kitchen sink.
Also, when you screw up a call to the endpoint, Shopify usually returns a response with details about where you screwed up, providing you with a first place to look. We see nothing of your response, so there is little to go on to help you.

Resources