Skip to content

Commit

Permalink
Add url validation and origin to API handle
Browse files Browse the repository at this point in the history
  • Loading branch information
iAdramelk committed Dec 4, 2019
1 parent 006a32d commit 99bfce2
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 6 deletions.
31 changes: 25 additions & 6 deletions pages/api/comments.js
Original file line number Diff line number Diff line change
@@ -1,24 +1,43 @@
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) => {
const {
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 })
})
}

Expand Down
3 changes: 3 additions & 0 deletions src/consts.js
Original file line number Diff line number Diff line change
Expand Up @@ -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'

0 comments on commit 99bfce2

Please sign in to comment.