Reputation: 111
I was trying to use the metafieldsSet
mutation to update metafields in Shopify
with the following code:
const client = new Shopify.Clients.Graphql(
process.env.SHOP,
process.env.PASSWORD
)
try {
const metafields = await client.query({
data: `mutation metafieldsSet($metafields: [MetafieldsSetInput!]!) {
metafieldsSet(metafields: $metafields) {
userErrors {
field
message
}
metafields {
key
value
}
}
}
`,
query: {
metafields: [
{
key: 'cb_inventory',
namespace: 'my_fields',
ownerId: 'gid://shopify/ProductVariant/40576138313890',
type: 'number_integer',
value: '25',
},
],
},
})
console.log(metafields)
res.status(200).json({ values: metafields })
} catch (error) {
console.log(error)
res.status(500).json(error)
}
However, the above mutation returns the following error:
Expected value to not be null
Variable $metafields of type [MetafieldsSetInput!]! was provided invalid value
I assume the variable metafields
failed to pass into the mutation because when I run the exact same mutation in the Shopify Admin API GraphiQL explorer
, there was no error
Shopify Admin API GraphiQL explorer mutation result
I have also looked into the github repo of @shopify/shopify-api. In my understanding, variables are added to the query
object.
What am I missing?
Thanks,
Howard
Environment: Next js 11.1.2,
Dependencies: @shopify/shopify-api
1.4.1
Upvotes: 5
Views: 2098
Reputation: 111
Turns out the syntax is incorrect. The variables should be placed inside the variables
object, while the mutation statement should be placed inside the query
object.
The following code works now:
const metafields = await client.query({
data: {
query: `mutation metafieldsSet($metafields: [MetafieldsSetInput!]!) {
metafieldsSet(metafields: $metafields) {
userErrors {
field
message
}
metafields {
key
value
}
}
}`,
variables: {
metafields: [
{
key: 'cb_inventory',
namespace: 'my_fields',
ownerId: 'gid://shopify/ProductVariant/40576138313890',
type: 'number_integer',
value: '25',
},
],
},
},
})
To use the intended API version, you need to first initialise the context with the following code:
Shopify.Context.initialize({
API_KEY,
API_SECRET_KEY,
SCOPES: ['read_products', 'write_products'],
HOST_NAME: HOST,
API_VERSION: '2021-10',
})
Upvotes: 6