Skip to content
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
2 changes: 1 addition & 1 deletion apps/api/.env
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
ACCESS_TOKEN_SECRET=[YOUR_ACCESS_TOKEN_SECRET_HERE]
REFRESH_TOKEN_SECRET=[YOUR_REFRESH_TOKEN_SECRET_HERE]
MONGO_URL=[YOUR_MONGO_CONNECTION_STRING_HERE]
MONGO_URL=mongodb+srv://ana:gSW0Y2m7EuyYgaR7@cluster0.xnnqz.mongodb.net/?retryWrites=true&w=majority&appName=Cluster0
147 changes: 147 additions & 0 deletions apps/api/src/controllers/post.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
import Post from "../models/post";
import Comment from "../models/comments";

//Get all posts
const getPosts = async (req, res) => {
try {
const posts = await Post.find().populate('category').populate('comments');

// Return all the posts with a 200 status code
res.status(200).json(posts);
} catch (error) {
const { message } = error;
res.status(500).json({ message });
}
}

//Get post by id
const getPostById = async (req, res) => {
// Retrieve the id from the route params
const { id } = req.params;
try {
const post = await Post.findById(id).populate('category').populate('comments');

if (!post) {
// If we don't find the category return a 404 status code with a message
return res.status(404).json({ message: 'Post not found' });
}

// Return the category with a 200 status code
res.status(200).json(post);
} catch (error) {
const { message } = error;
res.status(500).json({ message });
}
}

//Get post by category
const getPostsByCategory = async (req, res) => {
const category = req.params.category;
try {
const post = await Post.find({ category: category }).populate('category').populate('comments');
if (!post) {
return res.status(404).json({ message: 'Post by category not found' });
}

res.status(200).json(post);
} catch (error) {
const { message } = error;
res.status(500).json({ message });
}

}

//Create post
const createPost = async (req, res) => {
try {
const post = await Post.create(req.body);

// Return the created post with a 201 status code
res.status(200).json(post);
} catch (error) {
const { message } = error;
res.status(500).json({ message });
}
}

//Create post comment
const createPostComment = async (req, res) => {
// Retrieve the id from the route params
const { id } = req.params;
try {
const post = await Post.findById(id);

if (!post) {
// If we don't find the category return a 404 status code with a message
return res.status(404).json({ message: 'Post not found' });
}

const comment = await Comment.create(req.body);
post.comments.push(comment.id);
await post.save();

// Return the created post with a 201 status code
res.status(200).json(comment);
} catch (error) {
const { message } = error;
res.status(500).json({ message });
}
}

//Update post
const updatePost = async (req, res) => {
// Retrieve the id from the route params
const { id } = req.params;
try {
const post = await Post.findByIdAndUpdate(id, req.body, { new: true });

if (!post) {
// If we don't find the category return a 404 status code with a message
return res.status(404).json({ message: 'Post not found' });
}

// Return the category with a 200 status code
res.status(200).json(post);
} catch (error) {
const { message } = error;
res.status(500).json({ message });
}
}

//Delete post
const deletePost = async (req, res) => {
// Retrieve the id from the route params
const { id } = req.params;

try {
// Check and delete if we have a post with that id
const post = await Post.findById(id);

// If we don't find the post return a 404 status code with a message
if (!post) {
return res.status(404).json({ message: 'Post not found' });
}

await Comment.deleteMany({
_id: { $in: post.comments },
});

await post.deleteOne();

// Return a 200 status code
res.status(200).json(post);
} catch (error) {
const { message } = error;
res.status(500).json({ message });
}
};

export default {
getPosts,
getPostById,
getPostsByCategory,
createPost,
createPostComment,
updatePost,
deletePost
};
2 changes: 2 additions & 0 deletions apps/api/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { verifyToken } from './middleware/auth';
import { errorHandler } from './middleware/errorHandler';
import auth from './routes/auth';
import categories from './routes/categories';
import posts from './routes/posts';

const host = process.env.HOST ?? 'localhost';
const port = process.env.PORT ? Number(process.env.PORT) : 3000;
Expand All @@ -22,6 +23,7 @@ app.use('/api/auth', auth);

app.use(verifyToken);
app.use('/api/categories', categories);
app.use('/api/posts', posts);

app.use(errorHandler);

Expand Down
26 changes: 26 additions & 0 deletions apps/api/src/models/comments.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import mongoose, { Document, Schema } from "mongoose";

interface IComment extends Document {
author: string;
content: string;
}

export const commentSchema = new Schema<IComment>(
{
author: {
type: String,
required: [true, 'Property is required']
},
content: {
type: String,
required: [true, 'Property is required']
}
},
{
timestamps: true
}
);

const Comment = mongoose.model<IComment>('Comment', commentSchema);

export default Comment;
43 changes: 43 additions & 0 deletions apps/api/src/models/post.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import mongoose, { Document, Schema, Types } from 'mongoose';

interface IPost extends Document {
title: string;
image: string;
description: string;
category: Types.ObjectId;
comments: Types.ObjectId[];
}

export const postSchema = new Schema<IPost>(
{
title: {
type: String,
required: [true, 'Property is required']
},
image: {
type: String,
required: [true, 'Property is required']
},
description: {
type: String,
required: [true, 'Property is required']
},
category: {
type: Schema.Types.ObjectId,
required: [true, 'Property is required'],
ref: "Category"
},
comments: {
type: [Schema.Types.ObjectId],
required: [true, 'Property is required'],
ref: "Comment"
}
},
{
timestamps: true
}
);

const Post = mongoose.model<IPost>('Post', postSchema);

export default Post;
27 changes: 27 additions & 0 deletions apps/api/src/routes/posts.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import express from 'express';
import postController from '../controllers/post';

const router = express.Router();

// Get all posts
router.get('/', postController.getPosts);

//Get post by id
router.get('/:id', postController.getPostById);

//Get post by category
router.get('/category/:category', postController.getPostsByCategory);

//Create post
router.post('/', postController.createPost);

//Create comment
router.post('/:id/comments', postController.createPostComment);

//Update post
router.patch('/:id', postController.updatePost);

//Delete post
router.delete('/:id', postController.deletePost);

export default router;
Loading