Skip to content

Made Changes in the project #6

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 10 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 2 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand All @@ -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",
Expand Down
18 changes: 18 additions & 0 deletions src/controllers/comments.js
Original file line number Diff line number Diff line change
@@ -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
};
48 changes: 7 additions & 41 deletions src/controllers/posts.js
Original file line number Diff line number Diff line change
@@ -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()
*/
}
4 changes: 2 additions & 2 deletions src/controllers/users.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down
14 changes: 6 additions & 8 deletions src/db/models.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {
Expand Down
Binary file added src/db/socialmedia.db
Binary file not shown.
Binary file added src/db/test.db
Binary file not shown.
39 changes: 29 additions & 10 deletions src/public/app/all-posts.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
function loadPosts() {
$.get('/api/posts', (posts) => {
$.get("/api/posts", (posts) => {
for (let p of posts) {
$('#posts-container').append(
$(`
let item = $(`
<div class="col-4">
<div class="card m-2">
<div class="card-body">
Expand All @@ -12,14 +11,34 @@ function loadPosts() {
${p.body.substr(0, 200)}
<a href="#">...read more</a>
</p>
<a href="#" class="card-link">Comment</a>
<a href="#" class="card-link">Like</a>
<input type = "text" placeholder="Write your comment" class="newComment">
<button class= "card-link btnComment">Comment</button>
<ul class="comment></ul>
</div>
</div>
</div>

`)
)
</div>
`);

let commentBox= item.find(".comment")
for(let comment of p.comment) {
commentBox.append(
${"<li></li>"}.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);
}
})
});
}
33 changes: 26 additions & 7 deletions src/public/app/my-posts.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,7 @@ function loadMyPosts() {

$.get(`/api/posts?userId=${userId}`, (posts) => {
for (let p of posts) {
$('#posts-container').append(
$(`
let item = $(`
<div class="col-4">
<div class="card m-2">
<div class="card-body">
Expand All @@ -14,14 +13,34 @@ function loadMyPosts() {
${p.body.substr(0, 200)}
<a href="#">...read more</a>
</p>
<a href="#" class="card-link">Comment</a>
<a href="#" class="card-link">Like</a>
<input type= "text" placeholder= "add suggestions" class= "newComments">
<button class="card-link btnComment">Comment</button>
<ul class="comment"></ul>
</div>
</div>
</div>

`)
)
`);
let commentBox = item.find(".comment");
for (let comment of p.comments) {
commentBox.append(
$("<li></li>").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);
}
})
}
2 changes: 1 addition & 1 deletion src/public/components/all-posts.html
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ <h1 class="h1 text-center">Recent Posts</h1>
</div>
</div>

<script src="/app/my-posts.js"></script>
<script src="/app/all-posts.js"></script>
<script>
loadPosts()
</script>
2 changes: 1 addition & 1 deletion src/public/components/my-posts.html
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ <h1 class="h1 text-center">Recent Posts</h1>
</div>
</div>

<script src="/app/all-posts.js"></script>
<script src="/app/my-posts.js"></script>
<script>
loadMyPosts()
</script>
45 changes: 42 additions & 3 deletions src/routes/posts/comments.js
Original file line number Diff line number Diff line change
@@ -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
}
2 changes: 2 additions & 0 deletions src/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,15 @@ 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())
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()
Expand Down
11 changes: 11 additions & 0 deletions test/controllers/comments.test.js
Original file line number Diff line number Diff line change
@@ -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"
);
});
});
18 changes: 18 additions & 0 deletions test/controllers/posts.test.js
Original file line number Diff line number Diff line change
@@ -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");
});
});