Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
# frozen_string_literal: true
module CoreBy
module FieldExtensions
# GraphQL field extension allows returning URL of Active Storage attachment.
# TODO: Move to `graphql-field_attachment` gem?
class AttachmentUrlField < GraphQL::Schema::FieldExtension
attr_reader :attachment_assoc
def apply
attachment = options.fetch(:attachment) { field.original_name.to_s.sub(/_url$/, "") }
@attachment_assoc = "#{attachment}_attachment"
if (variant = options[:variant])
field.argument(
:variant,
variant.fetch(:enum),
required: variant.fetch(:required),
description: "Attachment variant"
)
end
end
def resolve(object:, arguments:, **rest)
object.preload_association(attachment_assoc => :blob)
end
def after_resolve(value:, arguments:, object:, **rest)
return if value.nil?
return value if value.is_a?(GraphQL::Execution::Interpreter::RawValue)
CoreBy::ActiveStorage.attachment_url(value, variant: arguments[:variant]&.to_sym)
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment