diff --git a/pages/api/comments.js b/pages/api/comments.js index d17a7b22fd..923eaa6d28 100644 --- a/pages/api/comments.js +++ b/pages/api/comments.js @@ -1,8 +1,11 @@ import Cors from 'micro-cors' import request from 'request' +import { BLOG_URL, FORUM_URL } from '../../src/consts' + const cors = Cors({ - allowedMethods: ['GET', 'HEAD'] + allowedMethods: ['GET', 'HEAD'], + origin: BLOG_URL }) const getCommentCount = (req, res) => { @@ -10,15 +13,31 @@ const getCommentCount = (req, res) => { query: { url } } = req + if (!url.startsWith(FORUM_URL)) { + res.status(404).json({ error: `URL should starts with '${FORUM_URL}'` }) + + return + } + request(`${url}.json`, (error, response, body) => { if (error || response.statusCode !== 200) { - res.status(404).json({ error }) - } else { - // post_count return all posts including topic itself - const count = JSON.parse(body).posts_count - 1 + res.status(404).json({ error: 'Forum returned incorrect response' }) - res.status(200).json({ count }) + return } + + const json = JSON.parse(body) + + if (!json.posts_count) { + res.status(404).json({ error: "Forum's don't have 'posts_count' field" }) + + return + } + + // post_count return all posts including topic itself + const count = json.posts_count - 1 + + res.status(200).json({ count }) }) } diff --git a/src/consts.js b/src/consts.js index 2005763cc1..1324d1dcd7 100644 --- a/src/consts.js +++ b/src/consts.js @@ -8,3 +8,6 @@ export const META_DESCRIPTION = export const META_KEYWORDS = 'data version control machine learning models management' export const META_SOCIAL_IMAGE = 'https://dvc.org/static/social-share.png' + +export const FORUM_URL = 'https://discuss.dvc.org' +export const BLOG_URL = 'https://blog.dvc.org'