Skip to content
Permalink
Browse files
Merge pull request #1 from prosovskyf/test
added comments functionality
  • Loading branch information
prosovskyf committed Sep 30, 2020
2 parents 6aba90e + 9a678cf commit 7f5eb9e1f589fa4809d72f1360af246bd2876f22
Show file tree
Hide file tree
Showing 5 changed files with 199 additions and 2 deletions.
@@ -4,7 +4,7 @@ const articles = require('./routes/articles.js');
const login = require('./routes/login.js');
const signup = require('./routes/signup.js');
// const categories = require('./routes/categoriesController.js')
// const comments = require('./routes/commentsController.js')
const comments = require('./routes/comments.js')
const likes = require('./routes/likes.js');
// const pins = require('./routes/pinsController.js')

@@ -18,6 +18,7 @@ app.use(articles.routes());
app.use(login.routes());
app.use(signup.routes());
app.use(likes.routes());
app.use(comments.routes());


app.listen(3000);
@@ -2,6 +2,9 @@
const db = require('../helpers/db-connection.js')
const Sequelize = require('sequelize');

// query to list all LIKED articles for specific user
// SELECT * FROM articles INNER JOIN likes l on articles.id = l.article_id
// INNER JOIN users u on u.id = l.user_id WHERE u.id=28;

exports.getAll = async function getAll() {
let results = await db.query('SELECT *, views FROM articles, views WHERE views.id = articles.id \
@@ -0,0 +1,90 @@
// DB connection specification + sequelize drive, do db.query to procees with query
const db = require('../helpers/db-connection.js')
const Sequelize = require('sequelize');


exports.getComments = async function getComments(articleId) {
let result = await db.query('SELECT comments.*, articles.id FROM comments,articles \
WHERE (comments.article_id=articles.id) AND (articles.id='+articleId+') ORDER BY comments."modifiedDate";', {
type: Sequelize.QueryTypes.SELECT,
raw: true,
logging: false,
returning: true
})
.then(result => {
return result
});
return result
}

exports.addComment = async function addComment(newComment, articleId, userId) {
let keys = Object.keys(newComment)
let values = Object.values(newComment)
keysQuoted = keys.map(q => `"${q}"`);
if ((keys != null) && (values != null)) {
let sql = `INSERT INTO comments (`+keysQuoted+`, article_id, user_id) \
VALUES(:values, :article_id, :user_id) RETURNING *;`;
let obj = await db.query(sql, {
raw: true,
replacements: { values: values, article_id: articleId, user_id: userId },
returning: true,
logging: console.log,
type: Sequelize.QueryTypes.INSERT
})
.then(obj => {
return obj
});
return obj
}
}

exports.updateComment = async function updateComment(commentId, userId, updatedComment) {
let keys = Object.keys(updatedComment)
let values = Object.values(updatedComment)
keysQuoted = keys.map(q => `"${q}"`);
let i = 0;
for (i; i < keys.length; i++) {
let sql = `UPDATE comments SET `+keysQuoted[i]+`=:values \
WHERE (id=`+ commentId +') AND (user_id='+userId+') RETURNING *;';
var obj = await db.query(sql, {
raw: true,
replacements: { values: values[i] },
returning: true,
logging: console.log,
type: Sequelize.QueryTypes.UPDATE
})
.then(obj => {
return obj;
});
}
return obj;
}

exports.deleteComment = async function deleteComment(commentId,userId) {
let sql = 'DELETE FROM comments WHERE (id='+commentId+') AND (user_id='+userId+');';
let obj = await db.query(sql, {
returning: true,
raw: true,
logging: false,
type: Sequelize.QueryTypes.DELETE
})
.then(obj => {
return obj;
});
return obj;
}

exports.checkCommentOwner = async function checkCommentOwner(commentId,userId) {
let sql = 'SELECT id, user_id FROM comments \
WHERE (user_id='+userId+') AND (id='+commentId+');';
let obj = await db.query(sql, {
type: Sequelize.QueryTypes.SELECT,
raw: true,
logging: false,
returning: true
})
.then(obj => {
return obj
});
return obj
}
@@ -10,7 +10,7 @@ router.get('/', getAll);
router.post('/', bodyParser(), createArticle);
// add view +1 when getById invoked
router.get('/:id([0-9]{1,})', getById);
router.put('/:id([0-9]{1,})', bodyParser(), updateArticle);
router.patch('/:id([0-9]{1,})', bodyParser(), updateArticle);
router.del('/:id([0-9]{1,})', deleteArticle);

//FUNCTIONS DEFINITIONS
@@ -0,0 +1,103 @@
const Router = require('koa-router');
const bodyParser = require('koa-bodyparser');
const router = Router({prefix: '/api/v1/articles/comments'});
const service = require('../models/comments')


// Router methods used - functions
router.post('/:id([0-9]{1,})', bodyParser(), addComment);
router.get('/:id([0-9]{1,})', getComments);
router.put('/:id([0-9]{1,})', bodyParser(), updateComment);
router.del('/:id([0-9]{1,})', deleteComment);

//FUNCTIONS DEFINITIONS
async function getComments(ctx, next) {
let articleId = ctx.params.id;
if ((articleId > 0) && (articleId != NaN)) {
let result = await service.getComments(articleId);
if ((result != null) && (result.length > 0)) {
ctx.status = 200;
ctx.body = JSON.parse(JSON.stringify(result));
}
else {
ctx.status = 404;
ctx.body = 'No comments found';
}

}
else {
ctx.status = 400;
ctx.body = 'Not valid ID of article';
}
}

async function addComment(ctx, next) {
let uId = ctx.request.query
let newComment = ctx.request.body;
let articleId = ctx.params.id;
let userId = uId.userId // will get based on session, now specified by query
try {
let obj = await service.addComment(newComment, articleId, userId);
ctx.status = 201;
ctx.body = JSON.parse(JSON.stringify(obj[0]));
}
catch(e) {
ctx.status = 400;
ctx.body = 'You submitted wrong values or you missing some, please check and try again';
}
}

async function updateComment(ctx, next) {
let uId = ctx.request.query;
let commentId = ctx.params.id;
let updatedComment = ctx.request.body;
let userId = uId.userId // will get based on session, now specified by query
if (commentId > 0) {
try {
var check = await service.checkCommentOwner(commentId,userId);
console.log(check[0])
if (typeof check[0] !== "undefined") {
let obj = await service.updateComment(commentId, userId, updatedComment);
ctx.status = 201;
ctx.body = JSON.parse(JSON.stringify(obj[0]));
}
else {
ctx.status = 404;
ctx.body = 'You cannot edit comment as you are not the owner or comment no longer exists';
}
}
catch(error) {
ctx.status = 400;
ctx.body = 'You submitted wrong values or you missing some, please check and try again';
}

}
else {
ctx.status = 400;
ctx.body = 'Not valid id of comment';
}
}

async function deleteComment(ctx, next) {
let uId = ctx.request.query;
let commentId = ctx.params.id;
let userId = uId.userId // will get based on session, now specified by query
if ((commentId > 0) && (commentId != NaN)) {
let check = await service.checkCommentOwner(commentId,userId);
if (typeof check[0] !== "undefined") {
await service.deleteComment(commentId,userId);
ctx.body = 'Comment was deleted';
ctx.status = 201;
}
else {
ctx.status = 401;
ctx.body = 'You are not the owner of the comment';
}
}
else {
ctx.status = 400;
ctx.body = 'ID needs to be bigger than 0'
}
}
//Exports all to be used in router lib
module.exports = router;

0 comments on commit 7f5eb9e

Please sign in to comment.