Display stats for organization article (#3232)

There was a bug where the frontend was not passing the organization id to the backend, and thus the fetching of the stats failed for organization articles.

This also adds a bit of error handling for `fetch` API
This commit is contained in:
rhymes 2019-06-19 15:17:35 +02:00 committed by Ben Halpern
parent 6ce6b265df
commit 55634ad68f
6 changed files with 33 additions and 5 deletions

View file

@ -185,6 +185,7 @@ class ArticlesController < ApplicationController
def stats
authorize current_user, :pro_user?
authorize @article
@organization_id = @article.organization_id
end
private

View file

@ -1,4 +1,5 @@
import Chart from 'chart.js';
import handleFetchAPIErrors from '../src/utils/errors';
function resetActive(activeButton) {
const buttons = document.getElementsByClassName('timerange-button');
@ -177,11 +178,14 @@ function callAnalyticsApi(date, timeRangeLabel, { organizationId, articleId }) {
}
fetch(url)
.then(data => data.json())
.then(handleFetchAPIErrors)
.then(response => response.json())
.then(data => {
drawCharts(data, timeRangeLabel);
writeCards(data, timeRangeLabel);
});
})
// eslint-disable-next-line no-console
.catch(error => console.error(error)); // we should come up with better error handling
}
function drawWeekCharts({ organizationId, articleId }) {

View file

@ -2,7 +2,8 @@ import initCharts from '../analytics/dashboard';
function initDashboardArticle() {
const article = document.getElementById('article');
initCharts({ articleId: article.dataset.articleId });
const { articleId, organizationId } = article.dataset;
initCharts({ articleId, organizationId });
}
window.InstantClick.on('change', () => {

View file

@ -0,0 +1,21 @@
// eslint-disable-next-line consistent-return
export default function handleFetchAPIErrors(response) {
// pass along a correct response
if (response.ok) {
return response;
}
// API errors contain the error message in {"error": "error message"}
// but they could be unhandled 500 errors
try {
response.json().then(data => {
throw new Error(data.error);
});
} catch (e) {
if (e instanceof SyntaxError) {
throw new Error(response.statusText);
} else {
throw e;
}
}
}

View file

@ -62,7 +62,7 @@ class AnalyticsService
@article_data = @article_data.where(id: @article_id)
# check article_id is published and belongs to the user/org
raise ArgumentError unless @article_data.exists?
raise ArgumentError, "You can't view this article's stats" unless @article_data.exists?
article_ids = [@article_id]
else

View file

@ -5,7 +5,8 @@
href="<%= @article.current_state_path %>"
class="rounded-btn rounded-btn--transparent"
id="article"
data-article-id="<%= @article.id %>">
data-article-id="<%= @article.id %>"
data-organization-id="<%= @organization_id %>">
👈 Back to the article
</a>