Edits history of script submission #23770 for ' Create Metaobject (shopify)'

  • bunnative
    One script reply has been approved by the moderators
    Ap­pro­ved
    //native
    
    export type DynSelect_type = string
    
    export async function type(auth: RT.Shopify) {
      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: `query { metaobjectDefinitions(first: 250) { nodes { type name fieldDefinitions { key } } } }`,
          }),
        }
      )
      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))
      }
      return data.metaobjectDefinitions.nodes.map(
        (d: {
          type: string
          name: string
          fieldDefinitions: { key: string }[]
        }) => ({
          value: d.type,
          label: `${d.name} (${d.type}): ${d.fieldDefinitions.map((f) => f.key).join(", ")}`,
        })
      )
    }
    
    /**
     * Create Metaobject
     * Create a metaobject entry of a definition. On definitions with the publishable capability, new entries are DRAFT unless status is set. fields maps field keys to values (e.g. `{ "title": "Hello", "rating": 5 }`); non-string values are JSON-encoded. Needs the write_metaobjects scope.
     */
    export async function main(
      auth: RT.Shopify,
      type: DynSelect_type,
      fields: { [key: string]: any },
      handle: string | undefined,
      status: "ACTIVE" | "DRAFT" | 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 ($metaobject: MetaobjectCreateInput!) { metaobjectCreate(metaobject: $metaobject) { metaobject { id handle type displayName updatedAt capabilities { publishable { status } } fields { key type value } } userErrors { field message } } }`,
            variables: {
              metaobject: {
                type,
                handle: handle || undefined,
                fields: Object.entries(fields).map(([key, value]) => ({
                  key,
                  value: typeof value === "string" ? value : JSON.stringify(value),
                })),
                capabilities: status ? { publishable: { status } } : 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.metaobjectCreate.userErrors.length) {
        throw new Error(JSON.stringify(data.metaobjectCreate.userErrors))
      }
    
      return data.metaobjectCreate
    }
    

    Submitted by hugo989 3 hours ago