How to reformat result in graphql? - graphql

I have a query like this:
query GetProductsBySlug {
categories(
where:{slug: "pianos"}
) {
products (first: 2) {
id,
slug,
name,
price,
images(first: 1) {
url
}
}
}
}
Results from this query:
{
"data": {
"categories": [
{
"products": [
{
...
]
}
]
}
}
I want to remove "data":...", "categories":..., and only get this result:
{
"products": [
{
...
}]
}
How I can do it?
I want that result only include {"products": ...} without data and categories.

You can use just [destructuring assignment][1] and get just the categories like
const {data:{categories}} = queryResult;
and then map this categories array like
categories.map(category=> category.products)
[1]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

Related

Shopify Discounts GraphQL API

I have two queries, one for fetching automatic discounts and other for fetching code discounts of a shopify store.
So is there a way that I can fetch both the discounts on a single query. Also we are letting users search for their discounts by title, so is there any query that returns data based on discount title because I have seen that in products or collections inside the query we can use:
products(first: 10, query: "title:*searched_text*")
These are my queries:
# for code discounts
query_1 = '''
{
codeDiscountNodes (first:10,query:"status:active"){
edges {
node {
id
codeDiscount {
__typename
... on DiscountCodeBxgy {
status
title
}
... on DiscountCodeBasic {
status
title
}
}
}
}
}
}
'''
# for automatic discounts
query_2 = '''
{
automaticDiscountNodes (first: 10) {
edges {
node {
id
automaticDiscount {
__typename
... on DiscountAutomaticBxgy {
status
title
}
... on DiscountAutomaticBasic {
status
title
}
}
}
}
}
}
'''
Welcome to Stack Overflow!
...is there a way that I can fetch both the discounts on a single query?
Yes, and there are two ways to do this:
First, in GraphQL you can bundle queries together into a single string like so:
{
codeDiscountNodes(first:10) {
edges {
node { id }
}
}
automaticDiscountNodes(first:10) {
edges {
node { id }
}
}
}
Results in:
{
"data": {
"codeDiscountNodes": {
"edges": [
{
"node": { "id": "gid://shopify/DiscountCodeNode/10..." }
}
]
},
"automaticDiscountNodes": {
"edges": [
{
"node": { "id": "gid://shopify/DiscountAutomaticNode/10..." }
}
]
}
}
}
Alternatively, the shopify API provides a general discountNodes endpoint which you can use to request all your discounts together.
{
discountNodes(first:10) {
edges {
node {
id
}
}
}
}
This approach is more efficient than combining the two queries (check out the extensions.cost.actualQueryCost for each of these solutions).
...is there any query that returns data based on discount title?
No, it does not appear like this API allows you to search by title. You can find the list of query filter parameters in the documentation..

Spring Boot Mongo update nested array of documents

I'm trying to set an attribute of a document inside an array to uppercase.
This is a document example
{
"_id": ObjectId("5e786a078bc3b3333627341e"),
"test": [
{
"itemName": "alpha305102992",
"itemNumber": ""
},
{
"itemName": "beta305102630",
"itemNumber": "P5000"
},
{
"itemName": "gamma305102633 ",
"itemNumber": ""
}]
}
I already tried a lot of thing.
private void NameElementsToUpper() {
AggregationUpdate update = AggregationUpdate.update();
//This one does not work
update.set("test.itemName").toValue(StringOperators.valueOf(test.itemName).toUpper());
//This one also
update.set(SetOperation.set("test.$[].itemName").withValueOfExpression("test.#this.itemName"));
//And every variant in between these two.
// ...
Query query = new Query();
UpdateResult result = mongoTemplate.updateMulti(query, update, aClass.class);
log.info("updated {} records", result.getModifiedCount());
}
I see that Fields class in spring data is hooking into the "$" char and behaving special if you mention it. Do not seem to find the correct documentation.
EDIT: Following update seems to work but I do not seem to get it translated into spring-batch-mongo code
db.collection.update({},
[
{
$set: {
"test": {
$map: {
input: "$test",
in: {
$mergeObjects: [
"$$this",
{
itemName: {
$toUpper: "$$this.itemName"
}
}
]
}
}
}
}
}
])
Any solutions?
Thanks!
For now I'm using which does what i need. But a spring data way would be cleaner.
mongoTemplate.getDb().getCollection(mongoTemplate.getCollectionName(Application.class)).updateMany(
new BasicDBObject(),
Collections.singletonList(BasicDBObject.parse("""
{
$set: {
"test": {
$map: {
input: "$test",
in: {
$mergeObjects: [
"$$this",
{
itemName: { $toUpper: "$$this.itemName" }
}
]
}
}
}
}
}
"""))
);

Unknown Type of Strapi/Gatsby Graphql Query Fragment

I'm trying to query data within a Strapi Dynamic Zone in Gatsby. In the Graphql Playground I can get this to work, but using the same query in Gatsby I receive the following error in the terminal:
error Unknown type "ComponentTextArticleCopy" graphql/template-strings
And my query in article.js
export const query = graphql`
query ArticleTemplate($id: String!) {
strapiArticle(id: { eq: $id }) {
articleHeader {
articleTitle
articleSnippet
}
articleContent {
__typename
... on ComponentTextArticleCopy {
contentCopy
}
... on ComponentImageContentImg {
imgCaption
}
... on ComponentTextArticleQuote {
contentQuote
}
}
}
}
`
According to the Graphql docs, Inline Fragment would seem to be the right approach but clearly I've got something wrong somewhere.
The following query 'works' on Gatsby but tries to resolve for all components:
query MyQuery {
allStrapiArticle {
edges {
node {
__typename
articleContent {
contentCopy
contentQuote
}
}
}
}
}
{
"data": {
"allStrapiArticle": {
"edges": [
{
"node": {
"__typename": "StrapiArticle",
"articleContent": [
{
"contentCopy": null,
"contentQuote": null
},
{
"contentCopy": "What a great city Gothenburg is. We even took a trip out to the archipelago. ",
"contentQuote": null
},
{
"contentCopy": null,
"contentQuote": null
},
{
"contentCopy": null,
"contentQuote": "You must visit at have fika"
}
]
}
}
]
}
},
Deleting Cache folder and running again worked for me.

graphql get query shows this error "variables are not allowed in scalars"

query describeNotesByNameSpaace($id:bigint!) {
notes(where: {object_meta: {_contains: {owner_references: [{uid:$id}]}}}) {
id
}
}
Use below code
query describeNotesByNameSpace($jsonFilter: jsonb) {
notes(where: {object_meta: {_contains: $jsonFilter}}) {
id
}
}
And query variable is
{
"jsonFilter": {
"owner_references": [
{
"uid": "1719430910876008448"
}
]
}
}

How do i connect two types in GraphQL?

So I have two types in GraphQL:
article.mdx
---
title: "Post n.1"
category: "Category"
---
Post Content
categories.json
[
{
"name": "Category",
"description": "This is a description",
"order": 1
}
]
I want to query my post type in order to have this kind of result:
{
"node": {
"title": Post n.1
"category": {
"name": "Category",
"description": "This is a description",
"order": 1
}
}
}
How can i do this? I'm currently using GatsbyJS! Thanks.
its pretty easy as you know you should use gatsby-transformer-remark to read md files , so for the json files you should use gatsby-transformer-json , add it in the gatsby-config.js file under plugins. then you need to query your data , unfortunatly i realy dont think you can combile two files to get data as you ask , but you can try this
first in gatsby-node.js file you need to reference the variables you gonna use for filter the query data , pass those fields in to the context
exports.createPages = async function({ actions, graphql }) {
const { data } = await graphql(`
query {
allMarkdownRemark {
edges {
node {
fields {
slug
}
}
}
}
}
`)
data.allMarkdownRemark.edges.forEach(edge => {
const slug = edge.node.fields.slug
actions.createPage({
path: slug,
component: require.resolve(`./src/templates/article.js`),
context: { category: category},
})
})
}
then in your page query you can accesss the filterd query by this read more in Creating Pages from Data Pro grammatically
export const pageQuery = graphql`
query MyQuery($category: String!) {
allMarkdownRemark(filter: {frontmatter: {category: {eq: $category}}}) {
edges {
node {
frontmatter {
title
}
}
}
}
allDataJson(filter: {name: {eq: $category}}) {
edges {
node {
nodes {
name,
description,
order
}
}
}
}
}`
then access you can access the your data by const {allMarkdownRemark , allDataJson} = data
then combine those two data as you prefer
const item = {node : { title: allMarkdownRemark.edges.node[0].frontmatter }};
item.node.category = allDataJson.edges.node[0].nodes
note this was assuming that edges.node is an array so we need to exact the 1st element of your data by node[0] , please check whether this method is working .
and the structure for the json data was
{ "nodes": [ {
"name": "Category",
"description": "This is a description",
"order": 1
}
]
}

Resources