Skip to content

Instantly share code, notes, and snippets.

@sulmanweb
Last active February 29, 2024 12:25

Revisions

  1. sulmanweb revised this gist Oct 6, 2021. 1 changed file with 24 additions and 0 deletions.
    24 changes: 24 additions & 0 deletions create_document.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,24 @@
    # app/graphql/types/objects/document_type.rb

    module Mutations
    class CreateDocument < BaseMutation

    description "creates a document for the user in the system"

    argument :doc, ApolloUploadServer::Upload, required: true

    field :document, Types::Objects::DocumentType, null: false

    def resolve(doc:)
    authenticate_user
    user = context[:current_user]
    document = user.documents.build(doc: doc)
    if document.save
    return {document: document}
    else
    raise GraphQL::ExecutionError.new(document.errors.full_messages.join(', '))
    end
    end

    end
    end
  2. sulmanweb revised this gist Oct 6, 2021. 1 changed file with 31 additions and 0 deletions.
    31 changes: 31 additions & 0 deletions document_type.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,31 @@
    # app/graphql/types/objects/document_type.rb

    module Types
    module Objects
    class DocumentType < Types::BaseObject
    field :id, Integer, null: false
    field :documentable_type, String, null: true
    field :documentable_id, Integer, null: true
    field :content_type, String, null: true
    field :url, String, null: false
    field :created_at, GraphQL::Types::ISO8601DateTime, null: false
    field :updated_at, GraphQL::Types::ISO8601DateTime, null: false

    def url
    if Rails.env.production?
    object.doc.service_url
    else
    Rails.application.routes.url_helpers.rails_blob_url(object.doc)
    end
    end

    def content_type
    if object.doc.present?
    object.doc.content_type
    else
    nil
    end
    end
    end
    end
    end
  3. sulmanweb created this gist Oct 6, 2021.
    19 changes: 19 additions & 0 deletions document.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,19 @@
    # app/models/document.rb

    class Document < ApplicationRecord
    ## RELATIONSHIPS
    has_one_attached :doc
    belongs_to :documentable, polymorphic: true, optional: true
    belongs_to :user, optional: true

    ## VALIDATIONS
    validate :doc_presence, on: :create

    # This validation validates that attachment can be any image of pdf
    def doc_presence
    pattern = %r{^(image|application)/(.)+$}
    unless doc.attached? && pattern.match?(doc.attachment.blob.content_type)
    errors.add(:doc, I18n.t("errors.models.document.file_presence"))
    end
    end
    end