diff --git a/package.json b/package.json index 9ad48f4..3e5c5a0 100644 --- a/package.json +++ b/package.json @@ -2,7 +2,7 @@ "name": "social-media-project", "version": "1.0.0", "description": "", - "main": "index.js", + "main": "server.js", "scripts": { "start": "node src/server.js", "test": "mocha test/setup.js test/**/*.test.js", @@ -14,9 +14,7 @@ "express": "^4.17.1", "mysql2": "^2.1.0", "sequelize": "^5.21.7", - "sqlite3": "^4.2.0" - }, - "devDependencies": { + "sqlite3": "^4.2.0", "chai": "^4.2.0", "chai-as-promised": "^7.1.1", "mocha": "^7.2.0", diff --git a/src/controllers/comments.js b/src/controllers/comments.js index e69de29..e5af768 100644 --- a/src/controllers/comments.js +++ b/src/controllers/comments.js @@ -0,0 +1,18 @@ +const { Posts, Users, Comments } = require("../db/models"); + +async function createComment(user_id, post_id, comment_body) { + let user = await Users.findOne({ + where: { + id: user_id, + }, + }); + return await Comments.create({ + body: comment_body, + title: user.username, + userId: user_id, + postId: post_id, + }); + } +module.exports = { + createComment +}; \ No newline at end of file diff --git a/src/controllers/posts.js b/src/controllers/posts.js index 8b87710..7027bf2 100644 --- a/src/controllers/posts.js +++ b/src/controllers/posts.js @@ -1,58 +1,24 @@ -const { Posts, Users } = require('../db/models') +const { Posts, Users, Comments} = require('../db/models') async function createNewPost(userId, title, body) { - const post = await Posts.create({ + return await Posts.create({ title, body, userId, - }) - - return post + }); } -/** - * showAllPosts({username: ''}) - * showAllPosts({title: ''}) - */ async function findAllPosts(query) { let where = {} if (query.userId) { where.userId = query.userId } - const posts = await Posts.findAll({ - include: [ Users ], + return await Posts.findAll({ + include: [ Users, Comments ], where - }) - - return posts + }); } module.exports = { createNewPost, findAllPosts -} - -/* Test Code */ -/* -async function task() { - // console.log( - // await createNewPost( - // 1, - // 'This is a sample post', - // 'Body of the post goes here' - // ) - // ), - // console.log( - // await createNewPost( - // 2, - // 'Another sample post', - // 'Some body example here as well' - // ) - // ) - const posts = await showAllPosts() - for (let p of posts) { - console.log(`${p.title}\nauthor: ${p.user.username}\n${p.body}\n==========\n`) - } -} - -task() -*/ \ No newline at end of file +} \ No newline at end of file diff --git a/src/controllers/users.js b/src/controllers/users.js index 1b52937..3b433df 100644 --- a/src/controllers/users.js +++ b/src/controllers/users.js @@ -2,9 +2,9 @@ const { Users } = require('../db/models') const { genRandomUsername } = require('../utils/username') async function createAnonUser() { - const user = await Users.create({ + return await Users.create({ username: genRandomUsername(), - }) + }); return user } diff --git a/src/db/models.js b/src/db/models.js index dd5870c..8f03321 100644 --- a/src/db/models.js +++ b/src/db/models.js @@ -3,16 +3,14 @@ const Sequelize = require('sequelize') let db if (process.env.NODE_ENV == 'testing') { db = new Sequelize({ - dialect: 'sqlite', - storage: ':memory:', - }) + dialect: "sqlite", + storage: __dirname + "/test.db", + }); } else { db = new Sequelize({ - dialect: 'mysql', - database: 'cbsocialmediadb', - username: 'cbsocialuser', - password: 'cbsocialpass', - }) + dialect: "sqlite", + storage: __dirname + "/socialmedia.db", + }); } const COL_ID_DEF = { diff --git a/src/db/socialmedia.db b/src/db/socialmedia.db new file mode 100644 index 0000000..f16b041 Binary files /dev/null and b/src/db/socialmedia.db differ diff --git a/src/db/test.db b/src/db/test.db new file mode 100644 index 0000000..8043289 Binary files /dev/null and b/src/db/test.db differ diff --git a/src/public/app/all-posts.js b/src/public/app/all-posts.js index 04aa02d..6ee04da 100644 --- a/src/public/app/all-posts.js +++ b/src/public/app/all-posts.js @@ -1,8 +1,7 @@ function loadPosts() { - $.get('/api/posts', (posts) => { + $.get("/api/posts", (posts) => { for (let p of posts) { - $('#posts-container').append( - $(` + let item = $(`
@@ -12,14 +11,34 @@ function loadPosts() { ${p.body.substr(0, 200)} ...read more

- Comment - Like + + +
    "}.text(`[${comment.title}]:${comment.body}`) + ); + } + + item.find(".btnComment").on("click",()=>{ + $.post( + "/api/commments", + { + post_id:p.id, + comment_body: item.find(".newComment").val(), + }, + (comment)=>{ + $("#content").load('/components/all-posts.html'); + } + ); + }); + $("#posts-container").append(item); } - }) + }); } diff --git a/src/public/app/my-posts.js b/src/public/app/my-posts.js index 9708598..ee5832f 100644 --- a/src/public/app/my-posts.js +++ b/src/public/app/my-posts.js @@ -3,8 +3,7 @@ function loadMyPosts() { $.get(`/api/posts?userId=${userId}`, (posts) => { for (let p of posts) { - $('#posts-container').append( - $(` + let item = $(`
    @@ -14,14 +13,34 @@ function loadMyPosts() { ${p.body.substr(0, 200)} ...read more

    - Comment - Like + + +
      - - `) - ) + `); + let commentBox = item.find(".comment"); + for (let comment of p.comments) { + commentBox.append( + $("
    • ").text(`[${comment.title}] : ${comment.body}`) + ); + } + + item.find(".btnComment").on("click", () => { + $.post( + "/api/comments", + { + post_id: p.id, + comment_body: item.find(".newComment").val(), + user_id: JSON.parse(window.localStorage.user).id, + }, + (comment) => { + $("#content").load(`/components/my-posts.html`); + } + ); + }); + $("#posts-container").append(item); } }) } diff --git a/src/public/components/all-posts.html b/src/public/components/all-posts.html index 242a75f..0d9209d 100644 --- a/src/public/components/all-posts.html +++ b/src/public/components/all-posts.html @@ -5,7 +5,7 @@

      Recent Posts

    - + \ No newline at end of file diff --git a/src/public/components/my-posts.html b/src/public/components/my-posts.html index 127bc0b..5657e12 100644 --- a/src/public/components/my-posts.html +++ b/src/public/components/my-posts.html @@ -5,7 +5,7 @@

    Recent Posts

    - + \ No newline at end of file diff --git a/src/routes/posts/comments.js b/src/routes/posts/comments.js index 632f4c2..4dee6d1 100644 --- a/src/routes/posts/comments.js +++ b/src/routes/posts/comments.js @@ -1,7 +1,46 @@ -const { Router } = require('express') +const route = require('express').Router() +const {createComment} = require("../../controllers/comments"); -const commentsRoute = Router() +//create comments +route.post("/", async (req, res) => { + try { + let { user_id, post_id, comment_body } = req.body; + if (!user_id || !post_id || !comment_body) { + res.status(403).send("Bad Request"); + } else { + console.log("============================================="); + console.log("going to create comment"); + console.log(user_id, post_id, comment_body); + console.log("============================================="); + + let comment = await createComment(user_id, post_id, comment_body); + + if (comment) { + res.status(201).send(comment); + } else { + res.status(501).send("not created Please try again"); + } + } + } catch (e) { + res.status(501).send(e); + } +}); + +// get all comments of a post id +route.get("/:post_id", async (req, res) => { + try { + let allComments = await Comments.findAll({ + where: { + postId: req.params.post_id, + }, + }); + res.status(200).send(allComments); + } catch (e) { + console.log(e); + res.status(404).send("Not Found"); + } +}); module.exports = { - commentsRoute + commentsRoute: route } \ No newline at end of file diff --git a/src/server.js b/src/server.js index 5d06647..2927f46 100644 --- a/src/server.js +++ b/src/server.js @@ -3,6 +3,7 @@ const express = require('express') const { db } = require('./db/models') const { usersRoute } = require('./routes/users') const { postsRoute } = require('./routes/posts') +const { commentsRoute } = require('./routes/posts/comments') const app = express() app.use(express.json()) @@ -10,6 +11,7 @@ app.use(express.urlencoded({extended: true})) app.use('/api/users', usersRoute) app.use('/api/posts', postsRoute) +app.use('/api/comments', commentsRoute) app.use('/', express.static(__dirname + '/public')) db.sync() diff --git a/test/controllers/comments.test.js b/test/controllers/comments.test.js new file mode 100644 index 0000000..4547a99 --- /dev/null +++ b/test/controllers/comments.test.js @@ -0,0 +1,11 @@ + +const { expect } = require("chai"); +const { createComment } = require("../../src/controllers/comments"); + +describe("/controllers/comments", () => { + it("should create comment on a post by user", async () => { + await expect(createComment(1, 12, "good comment")).to.be.rejectedWith( + "SQLITE_CONSTRAINT: FOREIGN KEY constraint failed" + ); + }); +}); \ No newline at end of file diff --git a/test/controllers/posts.test.js b/test/controllers/posts.test.js new file mode 100644 index 0000000..e4fe787 --- /dev/null +++ b/test/controllers/posts.test.js @@ -0,0 +1,18 @@ +const { expect } = require("chai"); +const { createNewPost, findAllPosts } = require("../../src/controllers/posts"); + +describe("/controllers/posts", () => { + it("should create a new post", async () => { + const post = await createNewPost(1, "title", "body"); + expect(post.userId).to.equal(1); + expect(post.title).to.equal("title"); + expect(post.body).to.equal("body"); + }); + it("should find all the posts ", async () => { + let query = { + userId: 1, + }; + let posts = await findAllPosts(query); + expect(posts).to.be.an("array"); + }); +}); \ No newline at end of file