Skip to content
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

Complete interview homework #352

Open
wants to merge 11 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
5 changes: 5 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# Node modules
node_modules/

# Environment variables
*.env
42 changes: 42 additions & 0 deletions backend/app/app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
// Import required modules and initialize the app.
import express from 'express';
import bodyParser from 'body-parser';
import cors from 'cors';
import { config } from 'dotenv';
config();
import postRoutes from './routes/postRoute.js';
import commentRoutes from './routes/commentRoute.js';
import userRoutes from './routes/userRoute.js';
import { createBlogTable, readJSONFiles, insertData } from './config/db.js';

// Initialize the Express application instance.
const app = express();
const PORT = process.env.APP_PORT;
const DB_PORT = process.env.POSTGRE_PORT;

// Middleware to parse JSON request bodies.
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

// Define API routes with base path '/'.
app.use('/', postRoutes);
app.use('/', commentRoutes);
app.use('/', userRoutes);

// Create blog table before starting server
// Start server on port 3000 and log message on successful start-up.
await createBlogTable();
const jsonData = await readJSONFiles();
if (jsonData) {
await insertData(jsonData);
}
// (async () => {
// const jsonData = await readJSONFiles();
// if (jsonData) {
// await insertData(jsonData);
// }
// })();
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}, database running on port ${DB_PORT}`);
});
112 changes: 112 additions & 0 deletions backend/app/config/db.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
import pkg from 'pg';
const { Pool } = pkg;
import { config } from 'dotenv';
config();
import fs from 'node:fs'

const pool = new Pool({
user: process.env.POSTGRE_USER,
host: process.env.POSTGRE_HOST,
database: process.env.POSTGRE_DATABASE,
password: process.env.POSTGRE_PASSWORD,
port: process.env.POSTGRE_PORT,
});

async function createBlogTable() {
try {
await pool.query(
"\
CREATE TABLE IF NOT EXISTS users ( \
id SERIAL PRIMARY KEY, \
username VARCHAR(50) NOT NULL, \
password VARCHAR(255) NOT NULL, \
name VARCHAR(100), \
dob DATE, \
created_at TIMESTAMP \
); \
CREATE TABLE IF NOT EXISTS posts ( \
id SERIAL PRIMARY KEY, \
owner INT REFERENCES users(id), \
title VARCHAR(100) NOT NULL, \
content TEXT NOT NULL, \
created_at TIMESTAMP, \
tags TEXT[] \
); \
CREATE TABLE IF NOT EXISTS comments ( \
id SERIAL PRIMARY KEY, \
owner INT REFERENCES users(id), \
post INT REFERENCES posts(id), \
content TEXT NOT NULL, \
created_at TIMESTAMP \
);",
(error) => {
if (error) {
throw error;
}
}
);
} catch (error) {
console.log(error.message);
}
}

async function readJSONFiles() {
try {
// Helper function to read a JSON file using streams
const readJSONFile = async (filePath) => {
const readStream = fs.createReadStream(filePath, { encoding: 'utf8' });
let chunkStream = '';
for await (const chunk of readStream) {
chunkStream += chunk;
}
return JSON.parse(chunkStream);
};

// Read all the JSON files asynchronously
const [commentsData, postsData, usersData] = await Promise.all([
readJSONFile('../data/comments.json'),
readJSONFile('../data/posts.json'),
readJSONFile('../data/users.json')
]);

return {
comments: commentsData,
posts: postsData,
users: usersData
};
} catch (error) {
console.error("Error reading files:", error);
}
}

async function insertData(data) {
const { comments, posts, users } = data;
try {
// Insert Users
for (let user of users) {
await pool.query(
'INSERT INTO users (id, username, password, name, dob, created_at) VALUES ($1, $2, $3, $4, $5, to_timestamp($6 / 1000))',
[user.id, user.username, user.password, user.name, user.dob.split('/').reverse().join('-'), user.created_at]
);
}
// Insert Posts
for (let post of posts) {
await pool.query(
'INSERT INTO posts (id, owner, title, content, created_at, tags) VALUES ($1, $2, $3, $4, to_timestamp($5 / 1000), $6)',
[post.id, post.owner, post.title.replace(/"/g, '""'), post.content.replace(/"/g, '""'), post.created_at, post.tags]
);
}
// Insert Comments
for (let comment of comments) {
await pool.query(
'INSERT INTO comments (id, owner, post_id , content , created_at) VALUES ($1,$2,$3,$4,to_timestamp($5 / 1000))',
[comment.id, comment.owner, comment.post, comment.content.replace(/"/g, '""'), comment.created_at]
);
}
} catch (error) {
console.error("Error inserting data:", error);
}
}

export default pool;
export { createBlogTable, readJSONFiles, insertData };
72 changes: 72 additions & 0 deletions backend/app/controllers/commentController.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import Comment from '../models/commentModel.js';

class CommentController {
// Get all comments
static async getComments(req, res) {
try {
const comments = await Comment.getAllComments();
if (!comments.length) {
return res.status(404).json({ message: 'No comments found' });
}
return res.json(comments);
} catch (err) {
console.error(err);
return res.status(500).json({ message: 'Server error' });
}
}

// Get comments by post ID
static async getCommentsByPostId(req, res) {
try {
const comments = await Comment.getCommentsByPostId(req.params.postId);
if (!comments.length) {
return res.status(404).json({ message: 'No comments found for this post' });
}
return res.json(comments);
} catch (err) {
console.error(err);
return res.status(500).json({ message: 'Server error' });
}
}

// Create a new comment
static async createComment(req, res) {
try {
const newComment = await Comment.createComment(req.body);
return res.status(201).json(newComment);
} catch (err) {
console.error(err);
return res.status(500).json({ message: 'Server error' });
}
}

// Update an existing comment
static async updateComment(req, res) {
try {
const updatedComment = await Comment.updateComment(req.params.id, req.body);
if (!updatedComment) {
return res.status(404).json({ message: 'Comment not found' });
}
return res.json(updatedComment);
} catch (err) {
console.error(err);
return res.status(500).json({ message: 'Server error' });
}
}

// Delete a comment
static async deleteComment(req, res) {
try {
const deletedComment = await Comment.deleteComment(req.params.id);
if (!deletedComment) {
return res.status(404).json({ message: 'Comment not found' });
}
return res.json(deletedComment);
} catch (err) {
console.error(err);
return res.status(500).json({ message: 'Server error' });
}
}
}

export default CommentController;
76 changes: 76 additions & 0 deletions backend/app/controllers/postController.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
import Post from '../models/postModel.js';

class PostController {
// Get all posts
static async getPosts(req, res) {
try {
const posts = await Post.getAllPosts();
if (!posts.length) {
return res.status(404).json({ message: 'No posts found' });
}

return res.json(posts);
} catch (err) {
console.error(err);
return res.status(500).json({ message: 'Server error' });
}
}

// Get post by ID
static async getPost(req, res) {
try {
const post = await Post.getPostById(req.params.id);
if (!post) {
return res.status(404).json({ message: 'Post not found' });
}

return res.json(post);
} catch (err) {
console.error(err);
return res.status(500).json({ message: 'Server error' });
}
}

// Create a new post
static async createPost(req, res) {
try {
const newPost = await Post.createPost(req.body);
return res.status(201).json(newPost);
} catch (err) {
console.error(err);
return res.status(500).json({ message: 'Server error' });
}
}

// Update an existing post
static async updatePost(req, res) {
try {
const updatedPost = await Post.updatePost(req.params.id, req.body);
if (!updatedPost) {
return res.status(404).json({ message: 'Post not found' });
}

return res.json(updatedPost);
} catch (err) {
console.error(err);
return res.status(500).json({ message: 'Server error' });
}
}

// Delete a post
static async deletePost(req, res) {
try {
const deletedPost = await Post.deletePost(req.params.id);
if (!deletedPost) {
return res.status(404).json({ message: 'Post not found' });
}

return res.json(deletedPost);
} catch (err) {
console.error(err);
return res.status(500).json({ message: 'Server error' });
}
}
}

export default PostController;
72 changes: 72 additions & 0 deletions backend/app/controllers/userController.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import User from '../models/userModel.js';

class UserController {
// Get all users
static async getUsers(req, res) {
try {
const users = await User.getAllUsers();
if (!users.length) {
return res.status(404).json({ message: "No users found" });
}
return res.json(users);
} catch (error) {
console.error(error);
return res.status(500).json({ message: "Server error" });
}
}

// Get user by ID
static async getUser(req, res) {
try {
const user = await User.getUserById(req.params.id);
if (!user) {
return res.status(404).json({ message: "User not found" });
}
return res.json(user);
} catch (error) {
console.error(error);
return res.status(500).json({ message: "Server error" });
}
}

// Create a new user
static async createUser(req, res) {
try {
const newUser = await User.createUser(req.body);
return res.status(201).json(newUser);
} catch (error) {
console.error(error);
return res.status(500).json({ message: "Server error" });
}
}

// Update an existing user
static async updateUser(req, res) {
try {
const updatedUser = await User.updateUser(req.params.id, req.body);
if (!updatedUser) {
return res.status(404).json({ message: "User not found" });
}
return res.json(updatedUser);
} catch (error) {
console.error(error);
return res.status(500).json({ message: "Server error" });
}
}

// Delete a user
static async deleteUser(req, res) {
try {
const deletedUser = await User.deleteUser(req.params.id);
if (!deletedUser) {
return res.status(404).json({ message: "User not found" });
}
return res.json(deletedUser);
} catch (error) {
console.error(error);
return res.status(500).json({ message: "Server error" });
}
}
}

export default UserController;
Loading