how can I supply a a variable to a query that can be used to specify a field to sort a returned array by? - graphql

I have built this query to request data from the Pokeapi graphQL server here https://beta.pokeapi.co/graphql/console/
query getOrderedPokemon (
$sortOrder: order_by,
) {
pokemon_v2_pokemon(
limit: 20,
order_by: {
name : $sortOrder
}
) {
id
name
height
weight
}
}
With this request, I can modify the order of returned items by changing the variable $sortOrder to either 'asc' or 'desc'. What can I do if I want to sort the returned items by a different property, like height or weight? Do I have to create a new query?
If the server does not accept a variable for specifying which field to sort by, is it impossible to create a flexible query that can be sorted by variable properties?
From what I can tell, it does look like this server doesn't have any variables I can use to specify which field to sort by.
Thank you

The pokeapi gives you quite a few options which you can see from the GraphiQL interface
To select by height in descending order for example:
query getOrderedPokemon {
pokemon_v2_pokemon(limit: 20, order_by: {height: desc}) {
id
name
height
weight
}
}
You can even order by multiple criteria, here is an example of ordering by both height and weight:
query getOrderedPokemon {
pokemon_v2_pokemon(limit: 20, order_by: {height: desc, weight: asc}) {
id
name
height
weight
}
}

Related

How can I modify a graphQL query based off of the variable passed to it?

I have built this query to request data from the Pokeapi graphQL server here
https://beta.pokeapi.co/graphql/console/
query getPokemon (
$typesList: [Int!],
) {
pokemon_v2_pokemon(
where: {
pokemon_v2_pokemontypes: { type_id: { _in: $typesList } }
}
) {
id
name
pokemon_v2_pokemontypes {
type_id
pokemon_v2_type {
name
}
}
}
}
How can I modify the query to return all results when the $typesList list is empty? I would like the query to return a filtered results list when $typesList has a list of ids, but it should return all values when the $typesList list is empty.
Is this something that is possible in graphQL?
Thank you
If you controlled the server you could write the resolver to function in the manner you're looking for but since you don't your only option is to wrap your use of the query with something that sets the default typesList variable to all possible types.

How to create/Fetch data dynamically by filters and order in GraphQL?

I am creating a query in graphql + apollo client whose filters and orders can change depending on what the customer selects in the frontend. For example:
query (
$orderPart: String!
$wherePart: String!
) {
getProductInfo(
order {$orderPart}
where {$wherePart}
) {
productID
description
size
model
cathegoryNumber
}
Where $orderPart will be equal to "description: DESC" or "productID: ASC" (depending what the customer selected in a momento or another). And $wherePart will be equal to "cathegoryNumber: {eq: 12}" or "productID: {eq: 111111}".
I need to pass the order/filter clause completely as a parameter.
But it doesn't work. Syntax is error "Syntax Error: Expected name, found $".
So my question is...
Is there any way to implement these dynamic filters/orders? How could this functionality be implemented? Is there any other way to implement this dynamic filters and orders?
Thanks.
Note:
In the official documentation, I found that only values can be passed as a parameters:
query (
$orderValue: sortEnumType! = DESC
$whereValue: String! = "description1"
) {
getProductInfo(
order {productID: $orderValue}
where {description: {eq: $whereValue} }
) {
productID
description
size
model
cathegoryNumber
}
But that is not what I need because always filters/orders couldn't be changed. And they could be completely different each time (prodyuct:ASC) first time, (cathegoryNumber:DESC) second time, etc...
Thanks for your help, I found a solution. Using apollo client and variables when the template is created:
let orderValue = 'order {productID: ASC}'; // built dynamically
let whereValue = 'description: {eq: "description1"}'; // built dynamically
document = gql`
query {
getProductInfo(
${orderValue}
${whereValue}
) {
productID
description
size
model
categoryNumber
}
`;

Get Product Metafields Data with GraphQL / BigCommerce

I'm trying to retrieve product metafields on BigCommmerce via GraphQL. The below code throws an error
query {
site {
product(entityId:639) {
sku
path
metafields(namespace: "App_Namespace", keys: "color_key") {
edges {
node {
id
value
}
}
}
}
}
}
Meta field information
Namespace App_Namespace
Key color_key
Description Colour
Value Blue | Grey | Yellow
Would appreciate any help on above. Thanks
The "keys" argument expects an array of keys. So even if you just want one key, submit it as an array of one:
query {
site {
product(entityId: 639) {
sku
path
metafields(namespace: "App_Namespace", keys: ["color_key"]) {
edges {
node {
id
value
}
}
}
}
}
}
Check out this link for more examples:
https://developer.bigcommerce.com/changelog#posts/graph-ql-storefront-api-updates-metafields-on-product-category-brand-variant
You also need to make sure that these requirements are met,
otherwise, even if the query is correct, you won't be able to get the metafields in the query:
The metafield must be marked with a permission_set of read_and_sf_access or write_and_sf_access in order to be exposed to the API. Metafields with any other permission value will be hidden.

How to sort on nested field in graphql ruby?

How do I sort on a nested field (or a virtual attribute) in graphql-ruby?
ExampleType = GraphQL::ObjectType.define do
name 'Example'
description '...'
field :nested_field, NestedType, 'some nested field' do
// some result that is virtually calculated and returns
OpenStruct.new(a: 123//some random number, b: 'some string')
end
end
QueryType = GraphQL::ObjectType.define do
name 'query'
field: example, ExampleType do
resolve -> (_obj, args,_ctx) {
Example.find(args['id']) //Example is an active record
}
end
field: examples, types[ExampleType] do
resolve -> (_obj, args,_ctx) {
// NOTE: How to order by nested field here?
Example.where(args['id'])
}
end
end
And if I am trying to get a list of examples ordered by nested_field.a:
query getExamples {
examples(ids: ["1","2"], order: 'nested_field.a desc') {
nested_field {
a
}
}
}
You can not order Active record by virtual attribute, because Active record can not match this virtual attribute to SQL/NoSQL query. You can avoid limitation, by creating view at DB layer. In GraphQL, sorting/pagination should be implemented at DB layer. Without that sorting/pagination implementation queries all data from DB to application memory.
Also, I want to recommend you switching from order argument with string type to sort argument with [SearchSort!] type based on enums. GraphQL schema will looks like that:
input SearchSort {
sorting: Sorting!
order: Order = DESC
}
enum Sorting {
FieldName1
FieldName2
}
enum Order {
DESC
ASC
}
It helps you implement mapping from GraphQL subquery to DataBase query.

OrderBy used with LINQ returns no rows in DOcumentDb

I have been trying to use OrderBy in LINQ i have changed several fields but it always returns null (no rows) while my documents are present in the collection.
Here's my simple query-
var rests = _client.CreateDocumentQuery<Restraunt>(_collectionUri)
.OrderBy(x => x.RestName);
You have to create an indexing policy with a range index on the type of the property you use in the order by (here I assume a string).
If you let the default policy, the order by return no result.
You need a sorting policy like that :
restrauntsCollection.IndexingPolicy.IncludedPaths.Add(
new IncludedPath {
Path = "/RestName/?",
Indexes = new Collection<Index> {
new RangeIndex(DataType.String) { Precision = -1 } }
});
See this page for more information: https://azure.microsoft.com/en-us/documentation/articles/documentdb-orderby/
Hope this helps

Resources