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

Minte.upload file #84

Open
wants to merge 6 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
1,163 changes: 1,058 additions & 105 deletions starter-project-backend-g32/package-lock.json

Large diffs are not rendered by default.

4 changes: 3 additions & 1 deletion starter-project-backend-g32/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,16 @@
"author": "",
"license": "ISC",
"dependencies": {
"cloudinary": "^1.30.1",
"@types/bcrypt": "^5.0.0",
"@types/jsonwebtoken": "^8.5.8",
"bcrypt": "^5.0.1",
"dotenv": "^10.0.0",
"express": "^4.17.1",
"jsonwebtoken": "^8.5.1",
"mongodb-memory-server": "^7.6.3",
"mongoose": "^5.13.4"
"mongoose": "^5.13.4",
"multer": "^1.4.5-lts.1"
},
"devDependencies": {
"@types/dotenv": "^8.2.0",
Expand Down
13 changes: 6 additions & 7 deletions starter-project-backend-g32/src/app.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,20 @@
import express, {Application, Request, Response, NextFunction, json} from 'express';
import dotenv from 'dotenv';

dotenv.config();

import articleRoutes from './routes/article'
import userRoutes from './routes/user'
import commentRouter from './routes/comment';
dotenv.config();
import commentRoutes from './routes/comment'
import uploadRoutes from './routes/upload'


dotenv.config();
const app: Application = express();
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use("/" , json({}));

app.use("/api/v1/comment", commentRouter);
app.use('/api/v1/articles', articleRoutes);
app.use('/api/v1/articles', articleRoutes)
app.use('/api/v1/comments', commentRoutes)
app.use('/api/v1/upload', uploadRoutes)
app.use('/api/v1/userProfile', userRoutes);

export default app;
103 changes: 103 additions & 0 deletions starter-project-backend-g32/src/controllers/comment.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
import {Request , Response } from "express";
import Comment from "../models/comment";
import Article from "../models/article";


export const createComment = async (req:Request, res:Response ) => {
const comment = new Comment(req.body);
await comment.save().then(() => {
res.status(201).json({
message: "Comment added successfully",
comment: comment
});
}).catch((error: Error) => {
res.status(400).json({
error: error
});
} );

}

export const getComment = async (req:Request, res:Response ) => {

try{
const article = await Article.findById({ _id: req.params.articleID })
if (article){
await Comment.findById(req.params.commentID).then((comment : typeof Comment) => {
res.status(200).json(comment);
}).catch((error: Error) => {
res.status(404).json({
error: error
});
} );
}else{
res.status(404).json({msg: "article not found"})
}
}catch(err){
res.status(500).json({msg: err})
}

}

export const getComments = async (req:Request, res:Response ) => {
await Comment.find().then((comments: any) => {
res.status(200).json(comments);
}).catch((error: Error) => {
res.status(400).json({
error: error
});
} );
}

export const deleteComment = async (req:Request, res:Response ) => {
try{
const article = await Article.findById({ _id: req.params.articleID })
if (article){
await Comment.findByIdAndRemove(req.params.commentID).then(() => {
res.status(200).json({
message: "Comment deleted successfully"
});
}).catch((error: Error) => {
res.status(404).json({
error: error
});
} );
}else{
res.status(404).json({msg: "article not found"})
}
}catch(err){
res.status(500).json(err)
}

}

export const updateComment = async (req:Request, res:Response ) => {
try{
const article = await Article.findById({ _id: req.params.articleID })
if (article){
if(!req.body.content) {
res.status(400).json({
error: "Content is required"
});
}else{
const {content , createdAt} = req.body;
const updatedComment = {"content" : content , "createdAt": createdAt ? createdAt : new Date()};

await Comment.findByIdAndUpdate(req.params.commentID, updatedComment).then(() => {
res.status(200).json({
message: "Comment updated successfully"
});
}).catch((error: Error) => {
res.status(404).json({
error: error
});
} );
}
}else{
res.status(404).json({msg: "article not found"})
}
}catch(err){
res.status(500).json(err)
}

}
82 changes: 82 additions & 0 deletions starter-project-backend-g32/src/controllers/upload.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
import { Request, Response } from 'express'
import cloudinary from '../utils/cloudinary'
import User from '../models/user.models'
import Article from '../models/article'

export const deleteUserProfile = async (req: Request, res: Response) => {
try {
let user = await User.findById(req.params.id)
const cloudinaryId = user?.profilePic.split(/.jpg|.jpeg|.png/,2)[1]
cloudinaryId && (await cloudinary.uploader.destroy(cloudinaryId))
const data = {
profilePic: "",
}
user = await User.findByIdAndUpdate(req.params.id, data, { new: true })
res.status(200).json(user)
} catch (err) {
res.status(404).json(err)
}
}


export const updateUserProfile = async (req: Request, res: Response) => {
try {
let user = await User.findById(req.params.id)
const cloudinaryId = user?.profilePic.split(/.jpg|.jpeg|.png/,2)[1]
cloudinaryId && (await cloudinary.uploader.destroy(cloudinaryId))
let result = {secure_url:"",public_id:""};
if (req.file) {
result = await cloudinary.uploader.upload(req.file.path)
}else{
return res.status(400).end()
}
const profileData = user?.profilePic || result.secure_url + result.public_id

const data = {
profilePic: profileData
};
user = await User.findByIdAndUpdate(req.params.id, data, { new: true })
res.status(200).json(user)
} catch (err) {
res.status(404).json(err)
}
}

export const deleteArticleMedia = async (req: Request, res: Response) => {
try {
let article = await Article.findById({_id:req.params.id})
const cloudinaryId = article?.media.split(/.jpg|.jpeg|.png/,2)[1]
cloudinaryId && (await cloudinary.uploader.destroy(cloudinaryId))
const data = {
media: '',
}
article = await Article.findByIdAndUpdate(req.params.id, data, { new: true })
res.status(200).json(article)
} catch (err) {
res.status(404).json(err)
}
}


export const updateArticleMedia = async (req: Request, res: Response) => {
try {
let article = await Article.findById(req.params.id)
const cloudinaryId = article?.media.split(/.jpg|.jpeg|.png/,2)[1]
cloudinaryId && (await cloudinary.uploader.destroy(cloudinaryId))
let result = {secure_url:"",public_id:""};
if (req.file) {
result = await cloudinary.uploader.upload(req.file.path);
}else{
return res.status(400).end()
}
const profileData = article?.media || result.secure_url + result.public_id

const data = {
media: profileData,
}
article = await Article.findByIdAndUpdate(req.params.id, data, { new: true })
res.status(200).json(article)
} catch (err) {
res.status(404).json(err)
}
}
1 change: 1 addition & 0 deletions starter-project-backend-g32/src/models/article.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ export interface IArticle extends Document {
}

const articleSchema: Schema<IArticle> = new mongoose.Schema({

author: {
type: String,
required: true
Expand Down
42 changes: 20 additions & 22 deletions starter-project-backend-g32/src/models/comment.ts
Original file line number Diff line number Diff line change
@@ -1,25 +1,23 @@
const mongoose = require('mongoose');

const commentSchema = new mongoose.Schema({
articleId: {
type: mongoose.Schema.Types.ObjectId,
ref:"Article",
required: true
},

content: {
type: String,
required: true
},
},
{
timestamps: {
createdAt: 'created_at',
updatedAt: 'updated_at'
}
}

)

const commentSchema = new mongoose.Schema({
articleId: {
type: mongoose.Schema.Types.ObjectId,
ref: "Article",
required: true,
},
userId: {
type: mongoose.Schema.Types.ObjectId,
ref: "User",
required: true,
},
content: {
type: String,
required: true
},
createdAt: {
type: Date,
default: Date.now
},
})
const Comment = mongoose.model('Comment', commentSchema);
export default Comment;
1 change: 1 addition & 0 deletions starter-project-backend-g32/src/models/user.models.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ const userSchema = new Schema<IUser>({
max: [20, "password can not be more than 20 characters"],
},
profilePic: String,

});


Expand Down
2 changes: 1 addition & 1 deletion starter-project-backend-g32/src/routes/article.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,4 @@ router.route("/:articleID").get(getSpecificArticle).put(updateArticle).delete(de
router.route("/:articleID/rating").post(createRating)
router.route("/:articleID/rating/:ratingId").get(getSpecificRating).put(updateRating)

export default router
export default router
1 change: 0 additions & 1 deletion starter-project-backend-g32/src/routes/comment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ commentRouter.get("/:id",getComment) // get comment by id
commentRouter.get('/:articleid', getCommentsByArticleId) // get comments by article id
commentRouter.post('/' , createComment); // create comment
commentRouter.put('/:id' , updateComment); // update comment
commentRouter.patch('/:id' , patchComment); // patch comment
commentRouter.delete('/:id' , deleteComment); // delete comment

export default commentRouter;
16 changes: 16 additions & 0 deletions starter-project-backend-g32/src/routes/upload.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { Router } from 'express'
import upload from "../utils/multer"

import {
deleteUserProfile,
updateUserProfile,
deleteArticleMedia,
updateArticleMedia
} from '../controllers/upload'

const router = Router()

router.route('/userProfile/:id').put(upload.single('image'),updateUserProfile).delete(deleteUserProfile)
router.route('/articleMedia/:id').put(upload.single('image'),updateArticleMedia).delete(deleteArticleMedia)

export default router
7 changes: 3 additions & 4 deletions starter-project-backend-g32/src/server.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,16 @@
import app from "./app"
import mongoose from 'mongoose';

const PORT = process.env.PORT || 8000
const PORT = process.env.PORT || 3000
const DB_URI = process.env.MONGO_URI || "mongodb://localhost:27017/usersdb";

mongoose.connect(DB_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
useFindAndModify: false,
})

.then(() => {
app.listen(PORT, () => console.log(`Server running... ${PORT}`));
})
.catch((err: any) => console.log('Error occurred while connecting', err));

.catch((err: any) => console.log('Error occurred while connecting', err));
Loading