From 06ae356c41a3ebceb00a4c7370d3cd5e3129dca5 Mon Sep 17 00:00:00 2001 From: James Shiffer Date: Fri, 12 Jun 2020 09:16:31 -0700 Subject: [PATCH] added commenting --- src/routes/a/[slug].svelte | 63 ++++++++++++++++++++++++++++++++++ src/routes/a/[slug]/comment.js | 51 +++++++++++++++++++++++++++ 2 files changed, 114 insertions(+) create mode 100644 src/routes/a/[slug]/comment.js diff --git a/src/routes/a/[slug].svelte b/src/routes/a/[slug].svelte index 4f04292..bc12f4d 100644 --- a/src/routes/a/[slug].svelte +++ b/src/routes/a/[slug].svelte @@ -15,6 +15,27 @@ @@ -88,4 +131,24 @@

Views: {article.views}

{@html article.html} +
+

Comments

+
+ {#each article.comments as comment} +
+

+ {comment.author} - {new Date(comment.created_at).toLocaleString()} +

+
{comment.content}
+
+ {:else} +

No comments.

+ {/each} +
+

Add a Comment

+
+

Name:

+

+

+
diff --git a/src/routes/a/[slug]/comment.js b/src/routes/a/[slug]/comment.js new file mode 100644 index 0000000..81cb360 --- /dev/null +++ b/src/routes/a/[slug]/comment.js @@ -0,0 +1,51 @@ +import Article from '../../../models/article.js'; + +export async function post(req, res) { + const { slug } = req.params; + const article = await Article.findOne({ slug }); + + if (article) { + let { author, content } = req.body; + author = author || 'Anonymous'; + if (!content) { + res.writeHead(422, { + 'Content-Type': 'application/json' + }); + res.end(JSON.stringify({ + message: `You must supply a comment.` + })); + return; + } + if (author.length > 100) { + res.writeHead(422, { + 'Content-Type': 'application/json' + }); + res.end(JSON.stringify({ + message: `Your username cannot be longer than 100 characters.` + })); + return; + } + if (content.length > 5000) { + res.writeHead(422, { + 'Content-Type': 'application/json' + }); + res.end(JSON.stringify({ + message: `Shorten your god damn comment you pedant` + })); + return; + } + article.comments.push({ author, content }); + article.save(); + res.writeHead(200, { + 'Content-Type': 'application/json' + }); + res.end(JSON.stringify(article.comments)); + } else { + res.writeHead(404, { + 'Content-Type': 'application/json' + }); + res.end(JSON.stringify({ + message: `Not found` + })); + } +}