mirror of
https://github.com/discourse/discourse.git
synced 2025-05-31 08:17:56 +08:00
FEATURE: topic_view_stats table with daily fidelity (#27197)
This gives us daily fidelity of topic view stats New table stores a row per topic viewed per day tracking anonymous and logged on views We also have a new endpoint `/t/ID/views-stats.json` to get the statistics for the topic.
This commit is contained in:
35
app/controllers/topic_view_stats_controller.rb
Normal file
35
app/controllers/topic_view_stats_controller.rb
Normal file
@ -0,0 +1,35 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
class TopicViewStatsController < ApplicationController
|
||||
MAX_STATS_PER_API_REQUEST = 300
|
||||
|
||||
def index
|
||||
topic = Topic.find(params[:topic_id].to_i)
|
||||
guardian.ensure_can_see!(topic)
|
||||
|
||||
from = 30.days.ago.to_date
|
||||
to = Date.today
|
||||
|
||||
begin
|
||||
from = params[:from].to_date if params[:from].present?
|
||||
to = params[:to].to_date if params[:to].present?
|
||||
rescue Date::Error
|
||||
render_json_error(I18n.t("topic_view_stats.invalid_date"), status: 422)
|
||||
return
|
||||
end
|
||||
|
||||
stats =
|
||||
TopicViewStat
|
||||
.where(topic_id: topic.id, viewed_at: from..to)
|
||||
.order(viewed_at: :desc)
|
||||
.limit(MAX_STATS_PER_API_REQUEST)
|
||||
|
||||
rows = []
|
||||
|
||||
stats.each do |stat|
|
||||
rows << { viewed_at: stat.viewed_at, views: stat.anonymous_views + stat.logged_in_views }
|
||||
end
|
||||
|
||||
render json: { topic_id: topic.id, stats: rows.reverse }
|
||||
end
|
||||
end
|
Reference in New Issue
Block a user