Facing problem with active storage and graphql

Viewed 121

We are using graphql for the API. For file upload we are using the active storage. For saving picture, we have two arguments, filename, base64_content and attach it to the record.

While exposing the uploaded file, we are facing some problem, that we need to write a method always.

Ex:

field :profile_picture,     Base::AttachmentType, null: true

Even we say it is null, if the file is not uploaded, it throws error Attachment.url cannot be null. The error comes though it is not attached, the object is not null and it goes into the AttachmentType.

We avoid the error by writing the following. So null is returned and it does not go into the attachment type.

def profile_picture
  object.profile_picture if object.profile_picture.attached?
end

Our attachment type looks like this.

module Types::Objects::Base
  class AttachmentType < Types::BaseObject
    field :id,          Int,      nil, null: false
    field :filename,    String,   nil, null: false
    field :url,         String,   nil, null: false

    def id
      if object.class.eql?(ActiveStorage::Variant)
        object.blob.id
      else
        object.id
      end
    end

    def filename
      if object.class.eql?(ActiveStorage::Variant)
        object.blob.filename.to_s + "-" + object.variation.transformations[:resize]
      else
        object.filename.to_s
      end
    end

    def url
      if object.class.eql?(ActiveStorage::Variant)
        Rails.application.routes.url_helpers.rails_representation_url(object)
      else
        object.service_url
      end
    end
  end
end

Is there a way where we can avoid writing the profile_picture method everytime?

We tried over writing the initialize method inside AttachmentType, we cannot get out, still all methods are being called.

0 Answers
Related