Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 17 additions & 2 deletions lib/shopify_toolkit/metafield_statements.rb
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,12 @@ def self.log_time(method_name)
def create_metafield(owner_type, key, type, namespace: :custom, name:, **options)
ownerType = owner_type.to_s.singularize.upcase # Eg. "PRODUCT"

# Skip creation if metafield already exists
if get_metafield_gid(owner_type, key, namespace: namespace)
say "Metafield #{namespace}:#{key} already exists for #{owner_type}, skipping creation"
return
end

# https://shopify.dev/docs/api/admin-graphql/2024-10/mutations/metafieldDefinitionCreate
query =
"# GraphQL
Expand Down Expand Up @@ -68,8 +74,7 @@ def get_metafield_gid(owner_type, key, namespace: :custom)
.tap { handle_shopify_admin_client_errors(_1) }
.body

result.dig("data", "metafieldDefinitions", "nodes", 0, "id") or
raise "Metafield not found for #{owner_type}##{namespace}:#{key}"
result.dig("data", "metafieldDefinitions", "nodes", 0, "id")
end

log_time \
Expand All @@ -79,6 +84,11 @@ def remove_metafield(owner_type, key, namespace: :custom, delete_associated_meta
"For reserved namespaces, you must delete all associated metafields (delete_associated_metafields: true)"
end

unless get_metafield_gid(owner_type, key, namespace: namespace)
say "Metafield #{namespace}:#{key} not found for #{owner_type}, skipping deletion"
return
end

shopify_admin_client
.query(
# Documentation: https://shopify.dev/docs/api/admin-graphql/2024-10/mutations/metafieldDefinitionDelete
Expand All @@ -104,6 +114,11 @@ def remove_metafield(owner_type, key, namespace: :custom, delete_associated_meta

log_time \
def update_metafield(owner_type, key, namespace: :custom, **options)
unless get_metafield_gid(owner_type, key, namespace: namespace)
say "Metafield #{namespace}:#{key} not found for #{owner_type}, skipping update"
return
end

shopify_admin_client
.query(
# Documentation: https://shopify.dev/docs/api/admin-graphql/2024-10/mutations/metafieldDefinitionUpdate
Expand Down