Last active
September 15, 2020 09:38
-
-
Save bibendi/e90de02cc282b8bf305fa4b2f71be405 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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