Edits history of script submission #23720 for ' Update Article (shopify)'

  • bunnative
    One script reply has been approved by the moderators
    Ap­pro­ved
    //native
    
    /**
     * Update Article
     * Update an article. Empty fields are left unchanged; tags, when given, replace the existing list. Visibility only changes when published is set to publish or unpublish. Accepts a numeric ID or a GID. Needs the write_content scope.
     */
    export async function main(
      auth: RT.Shopify,
      article_id: string,
      title: string | undefined,
      author_name: string | undefined,
      body_html: string | undefined,
      summary_html: string | undefined,
      tags: string[] | undefined,
      image_url: string | undefined,
      image_alt_text: string | undefined,
      published: "keep" | "publish" | "unpublish" = "keep",
      publish_date: string | undefined
    ) {
      const id = article_id.startsWith("gid://")
        ? article_id
        : `gid://shopify/Article/${article_id}`
    
      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 ($id: ID!, $article: ArticleUpdateInput!) { articleUpdate(id: $id, article: $article) { article { id title handle isPublished publishedAt author { name } blog { id title } tags summary image { url altText } createdAt updatedAt } userErrors { field message } } }`,
            variables: {
              id,
              article: {
                title: title || undefined,
                author: author_name ? { name: author_name } : undefined,
                body: body_html || undefined,
                summary: summary_html || undefined,
                tags: tags?.length ? tags : undefined,
                image: image_url
                  ? { url: image_url, altText: image_alt_text || undefined }
                  : undefined,
                isPublished:
                  published === "publish"
                    ? true
                    : published === "unpublish"
                      ? false
                      : undefined,
                publishDate: publish_date || 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.articleUpdate.userErrors.length) {
        throw new Error(JSON.stringify(data.articleUpdate.userErrors))
      }
    
      return data.articleUpdate
    }
    

    Submitted by hugo989 3 hours ago