Skip to content

A platform for community discussion. Free, open, simple.

2.4 KB
Raw Blame
# frozen_string_literal: true

module DiscourseWorkflows
  class PostSerializer < ApplicationSerializer
    attributes :id,
               :topic_id,
               :topic_title,
               :topic_slug,
               :post_number,
               :post_type,
               :reply_to_post_number,
               :reply_to_post_id,
               :reply_to_username,
               :post_url,
               :url,
               :username,
               :user_id,
               :created_at,
               :updated_at,
               :excerpt,
               :like_count,
               :reply_count,
               :score,
               :category_id,
               :category_name,
               :category_slug,
               :tags,
               :upload_ids,
               :locale,
               :raw,
               :cooked

    def initialize(object, opts)
      super
      @include_raw = opts.fetch(:include_raw, true)
      @include_cooked = opts.fetch(:include_cooked, false)
    end

    def topic_title
      topic&.title
    end

    def topic_slug
      topic&.slug
    end

    def post_url
      return "/404" if topic.blank?

      ::Post.url(topic.slug, topic.id, object.post_number)
    end

    def url
      "#{Discourse.base_url}#{post_url}"
    end

    def reply_to_post_id
      if object.has_attribute?(:reply_to_post_id)
        object[:reply_to_post_id]
      else
        object.reply_to_post&.id
      end
    end

    def reply_to_username
      object.reply_to_user&.username
    end

    def username
      object.user&.username
    end

    def created_at
      object.created_at&.utc&.iso8601
    end

    def updated_at
      object.updated_at&.utc&.iso8601
    end

    def excerpt
      object.excerpt(300, strip_links: true, text_entities: true)
    end

    def category_id
      topic&.category_id
    end

    def category_name
      topic&.category&.name
    end

    def category_slug
      topic&.category&.slug_for_url
    end

    def tags
      return [] if topic.blank? || !SiteSetting.tagging_enabled

      topic.visible_tags(scope).map(&:name)
    end

    def upload_ids
      object.upload_ids
    end

    def include_raw?
      @include_raw
    end

    def include_cooked?
      @include_cooked
    end

    private

    def topic
      return @topic if defined?(@topic)

      @topic =
        object.topic || (::Topic.with_deleted.find_by(id: object.topic_id) if scope.is_staff?)
    end
  end
end