//native
/**
* Set Metafield
* Create or update a metafield on any resource (owner GID, e.g. `gid://shopify/Product/123`). value is always a string (JSON-encode lists and objects). type (e.g. single_line_text_field, number_integer, boolean, json, list.single_line_text_field) is required unless a metafield definition exists for the namespace and key, even when updating an existing metafield.
*/
export async function main(
auth: RT.Shopify,
owner_id: string,
namespace: string,
key: string,
value: string,
type: string | undefined
) {
const response = await fetch(
`https://${auth.store_name}.myshopify.com/admin/api/2026-10/graphql.json`,
{
method: "POST",
headers: {
"X-Shopify-Access-Token": auth.token,
"Content-Type": "application/json",
Accept: "application/json",
},
body: JSON.stringify({
query: `mutation ($metafields: [MetafieldsSetInput!]!) { metafieldsSet(metafields: $metafields) { metafields { id namespace key type value jsonValue createdAt updatedAt } userErrors { field message } } }`,
variables: {
metafields: [
{
ownerId: owner_id,
namespace,
key,
value,
type: type || undefined,
},
],
},
}),
}
)
if (!response.ok) {
throw new Error(`${response.status} ${await response.text()}`)
}
const { data, errors } = await response.json()
if (errors) {
throw new Error(JSON.stringify(errors))
}
if (data.metafieldsSet.userErrors.length) {
throw new Error(JSON.stringify(data.metafieldsSet.userErrors))
}
return data.metafieldsSet
}
Submitted by hugo989 3 hours ago