Using multiple mutations in one call - graphql

I have written my first script that utilises GraphQL (Still a learning curve)
Currently i am making 3 calls using GraphQL,
First is a product lookup,
Second is a Price Update,
Third is a Inventory Update.
To reduce the number of calls to the end point i wanted to merge both Price update and Inventory, But i am having 0 luck, i dont know if its bad formatting.
Here is my GraphQL Code (I am using Postman to help ensure the schema is correct before taking it to PHP)
mutation productVariantUpdate($input: ProductVariantInput!) {
productVariantUpdate(input: $input) {
product {
id
}
productVariant {
id
price
}
userErrors {
field
message
}}
second: inventoryActivate($inventoryItemId: ID!, $locationId: ID!, $available: Int) {
inventoryActivate(inventoryItemId: $inventoryItemId, locationId: $locationId, available: $available) {
inventoryLevel {
id
available
}
userErrors {
field
message
}
}
}
}
Variables:
{
"inventoryItemId": "gid://shopify/InventoryItem/XXXXXXXXXXX",
"locationId": "gid://shopify/Location/XXXXXXXXXX",
"available": 11 ,
"input": {
"id": "gid://shopify/ProductVariant/XXXXXXXXX",
"price": 55
}
}
Error i keep getting:
{
"errors": [
{
"message": "Parse error on \"$\" (VAR_SIGN) at [29, 29]",
"locations": [
{
"line": 29,
"column": 29
}
]
}
]
}

The way that you'd go about this is by specifying all your arguments at the root of your mutation, just like you did for ProductVariantInput:
mutation batchProductUpdates(
$input: ProductVariantInput!
$inventoryItemId: ID!
$locationId: ID!
$available: Int
) {
productVariantUpdate(input: $input) {
product { id }
productVariant { id price }
...
}
inventoryActivate(
inventoryItemId: $inventoryItemId
locationId: $locationId
available: $available
) {
inventoryLevel { id available }
...
}
}
Here's an example how this would work if you were to use fetch in JavaScript:
fetch("https://example.com/graphql", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
query: `
mutation MyMutation($firstId: Int, $secondId: Int) {
m1: ToggleLike(id: $firstId) {
id
}
m2: ToggleLike(id: $secondId) {
id
}
}
`,
variables: {
firstId: 1,
secondId: 2
}
})
})
Hope this helps.

Related

Customize AWS-Appsync subscription response data

In my case, I have an app that users can subscript to some in-app events.
I want to call a mutation from one of my microservices and send several user ids as a list to the mutation, and then all clients that subscript to that mutation receive '[1]'.
schema
type Mutation {
setUsersAlarm(user_id: [Int]): UserIDList
}
type Subscription {
subscripesetUsersAlarm: UserIDList
#aws_subscribe(mutations: ["setUsersAlarm"])
}
type UserIDList {
id_list: [Int]
}
schema {
query: Query
mutation: Mutation
subscription: Subscription
}
Mutation Resolver
request template
{
"version": "2017-02-28",
"payload":$util.toJson($context.args["user_id"])
}
response template
{
"id_list":$util.toJson($context.result)
}
Subscription Resolver
request template
{
"version": "2017-02-28",
"payload": {
"hello": "local",
}
}
response template
$extensions.setSubscriptionFilter({
"filterGroup": [
{
"filters" : [
{
"fieldName" : "id_list",
"operator" : "contains",
#* I can get the value from cognito or from
user input arguments*#
"value" : 10
}
]
}
]
})
#set ($myList = [1])
#set( $ctx.result.id_list =$myList)
$util.toJson($ctx.result)
Query
subscription MySubscription {
subscripesetUsersAlarm {
id_list
}
}
mutation MyMutation {
setUserRefreshToken(user_id: [10, 12]) {
id_list
flg
}
}
Output of mutation
{
"data": {
"setUsersAlarm": {
"id_list": [
10,
12
]
}
}
}
Output of subscription
I want to receive the below result in subscription:
{
"data": {
"subscripesetUsersAlarm": {
"id_list": [1]
}
}
}
but I receive this:
{
"data": {
"subscripesetUsersAlarm": {
"id_list": [
10,
12
]
}
}
}
I want to customize the subscription response depending on my clients

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.

Query to get top 10 users from MongoDb in Spring

So basically I have a collection that looks like this(other fields omitted):
[{
user: mail1#test.com
},
{
user: mail1#test.com
},
{
user: mail1#test.com
},
{
user: mail2#test.com
},
{
user: mail2#test.com
},
{
user: mail3#test.com
}
]
I'm looking for a way to query MongoDB in order to get the top 10 active users(those with the most records in DB). Is there an easy way to get this, perhaps just using the interface?
perhaps a simple group aggregation will give you the needed result?
db.Users.aggregate(
[
{
$group: {
_id: "$user",
count: { $sum: 1 }
}
},
{
$sort: { count: -1 }
},
{
$limit: 10
},
{
$project: {
user: "$_id",
_id: 0
}
}
])
There is something called $sortByCount for aggregation.
List<UserCount> getTop10UserCount() {
return mongoTemplate.aggregate(
newAggregation(
User.class,
sortByCount("user"),
limit(10),
project("_id", "count")
),
UserCount.class
);
}
static class UserCount {
String _id;
Integer count;
// constructors, getters or setters..
}

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
}
]
}

Issues with GraphQL Nested Mutation

I am trying to achieve nesting mutation by adding player name in Team (Parent) and struggling trying to fetch list of player name...
Inside GraphiQL tool (localhost:4000/graphiql), this is the Add Mutation variable that I have included...
mutation AddPlayerToTeam($name: String!, $teamId: ID!){
addPlayerToTeam(player: $name, teamId: $teamId){
id
players{
name
}
}
}
The query variables, adding teamID and name...
{
"teamId": "5aff545371fc930a4c43b2b9",
"name": "John Doe"
}
The result shown...
{
"data": {
"addPlayerToTeam": {
"id": "5b072774e385740c38483111",
"players": []
}
}
}
But I was expecting for player name to show up like this....
{
"data": {
"addPlayerToTeam": {
"id": "5b072774e385740c38483111",
"players": [
{
"name": "John Doe"
}
]
}
}
}
The mutation code...
AddPlayerToTeam: {
type: TeamType,
args: {
name: { type: new GraphQLNonNull(GraphQLString) },
teamId: { type: new GraphQLNonNull(GraphQLID) }
},
resolve(parent, { name, teamId }) {
let addPlayer = new Player({ name, teamId });
return addPlayer.save();
}
},
I've struggled to find reason why I am getting "players": [] instead of "players": [ {"name": "John Doe" } ].
Need I include .then(...) after .save() to get result? Any examples? Your help is appreciated.
BTW, I using mongoDB/mongoose method. Saving them in local mongoDB.
Found solution for this... Thank #andrewingram from graphql.slack for helping. Just include .then(...) to return result.
AddPlayerToTeam: {
type: TeamType,
args: {
name: { type: new GraphQLNonNull(GraphQLString) },
teamId: { type: new GraphQLNonNull(GraphQLID) }
},
async resolve(parent, { name, teamId }) {
let addPlayer = new Player({ name, teamId });
await addPlayer.save();
return Team.findById(teamId);
}
},
or in promise version
resolve(parent, { name, teamId }) {
let addPlayer = new Player({ name, teamId });
return addPlayer.save().then(() => Team.findById(teamId));
}
Hope that help.

Resources