1 | |
2 |
|
3 | |
4 | * Update Metaobject |
5 | * Update a metaobject entry (numeric ID or Metaobject GID). Only the field keys present in fields are changed (e.g. `{ "rating": 4 }`); non-string values are JSON-encoded. status applies only to definitions with the publishable capability. Needs the write_metaobjects scope. |
6 | */ |
7 | export async function main( |
8 | auth: RT.Shopify, |
9 | metaobject_id: string, |
10 | fields: { [key: string]: any } | undefined, |
11 | handle: string | undefined, |
12 | status: "ACTIVE" | "DRAFT" | undefined |
13 | ) { |
14 | const id = metaobject_id.startsWith("gid://") |
15 | ? metaobject_id |
16 | : `gid://shopify/Metaobject/${metaobject_id}` |
17 | const entries = Object.entries(fields ?? {}) |
18 |
|
19 | const response = await fetch( |
20 | `https://${auth.store_name}.myshopify.com/admin/api/2026-10/graphql.json`, |
21 | { |
22 | method: "POST", |
23 | headers: { |
24 | "X-Shopify-Access-Token": auth.token, |
25 | "Content-Type": "application/json", |
26 | Accept: "application/json", |
27 | }, |
28 | body: JSON.stringify({ |
29 | query: `mutation ($id: ID!, $metaobject: MetaobjectUpdateInput!) { metaobjectUpdate(id: $id, metaobject: $metaobject) { metaobject { id handle type displayName updatedAt capabilities { publishable { status } } fields { key type value } } userErrors { field message } } }`, |
30 | variables: { |
31 | id, |
32 | metaobject: { |
33 | handle: handle || undefined, |
34 | fields: entries.length |
35 | ? entries.map(([key, value]) => ({ |
36 | key, |
37 | value: |
38 | typeof value === "string" ? value : JSON.stringify(value), |
39 | })) |
40 | : undefined, |
41 | capabilities: status ? { publishable: { status } } : undefined, |
42 | }, |
43 | }, |
44 | }), |
45 | } |
46 | ) |
47 |
|
48 | if (!response.ok) { |
49 | throw new Error(`${response.status} ${await response.text()}`) |
50 | } |
51 |
|
52 | const { data, errors } = await response.json() |
53 | if (errors) { |
54 | throw new Error(JSON.stringify(errors)) |
55 | } |
56 | if (data.metaobjectUpdate.userErrors.length) { |
57 | throw new Error(JSON.stringify(data.metaobjectUpdate.userErrors)) |
58 | } |
59 |
|
60 | return data.metaobjectUpdate |
61 | } |
62 |
|