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

Backend of main feautre #709

Open
wants to merge 4 commits into
base: main
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
2 changes: 2 additions & 0 deletions backend/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
.env
/node_modules
14 changes: 14 additions & 0 deletions backend/config/db.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import mongoose from 'mongoose';
import { MONGODB_URI } from '../config/server-config.js';

export const connectDB = async () => {
try {
await mongoose.connect(MONGODB_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
console.log('DB connected successfully');
} catch (error) {
console.log('Something went wrong in connecting to DB', error);
}
};
6 changes: 6 additions & 0 deletions backend/config/server-config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import dotenv from 'dotenv';
dotenv.config();

export const PORT = process.env.PORT;
export const MONGODB_URI = process.env.MONGODB_URI;
export const JWT_SECRET = process.env.JWT_SECRET;
191 changes: 191 additions & 0 deletions backend/controller/idea-controller.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,191 @@
import IdeaService from '../service/idea-service.js';
import { uploadImageToCloudinary } from '../utils/cloudinary.js';

const ideaService = new IdeaService();

const createIdea = async (req, res) => {
try {
const { title, description, tags } = req.body;
const userId = req.body.userId;
const imageFile = req.file;
console.log(imageFile);

const now = new Date();

// Find the user's most recent idea submission
const existingIdea = await ideaService.find({ userId });

if (existingIdea) {
// Check if the submission date is within the current month
const lastSubmissionDate = new Date(existingIdea.submissionDate);

// If the last submission is in the current month, restrict the user from submitting
if (lastSubmissionDate.getMonth() === now.getMonth() && lastSubmissionDate.getFullYear() === now.getFullYear()) {
return res.status(400).json({
message: 'You can only submit one idea per month. Please wait until the 1st of next month.',
});
}
}

let imageUrl = null;
if (imageFile) {
imageUrl = await uploadImageToCloudinary(imageFile.buffer); // Upload directly using the buffer
}
console.log(imageUrl);

const idea = await ideaService.createIdea({
title,
description,
tags,
userId,
submissionDate: now,
media: imageUrl,
});

await idea.save();

res.status(200).json({
success: true,
message: 'Idea created successfully',
data: idea,
err: {},
});
} catch (error) {
console.log(error);
res.status(500).json({
message: 'Internal Server error. Something went wrong in idea-controller',
success: false,
err: error.message,
data: {},
});
}
};
const deleteIdea = async (req, res) => {
try {
const ideaId = req.params.id;
const response = await ideaService.deleteIdea(ideaId);
res.status(200).json({
success: true,
message: 'Idea deleted successfully',
data: response,
err: {},
});
} catch (error) {
console.log(error);
res.status(500).json({
message: 'Internal Server error. Something went wrong in idea-controller',
success: false,
err: error.message,
data: {},
});
}
};
const updateIdea = async (req, res) => {
try {
const ideaId = req.params.id;
const data = req.body;
const response = await ideaService.updateIdea(ideaId, data);
res.status(200).json({
success: true,
message: 'Idea updated successfully',
data: response,
err: {},
});
} catch (error) {
console.log(error);
res.status(500).json({
message: 'Internal Server error. Something went wrong in idea-controller',
success: false,
err: error.message,
data: {},
});
}
};
const getIdea = async (req, res) => {
try {
const ideaId = req.params.id;
const response = await ideaService.getIdea(ideaId);
res.status(200).json({
success: true,
message: 'Idea fetched successfully',
data: response,
err: {},
});
} catch (error) {
console.log(error);
res.status(500).json({
message: 'Internal Server error. Something went wrong in idea-controller',
success: false,
err: error.message,
data: {},
});
}
};

const voteIdeas = async (req, res) => {
try {
const ideaId = req.params.id;
const userId = req.body.userId;

const response = await ideaService.voteOnIdea(ideaId, userId);

res.status(200).json({
success: true,
message: 'Voted successfully',
data: response,
err: {},
});
} catch (error) {
console.log(error);
res.status(500).json({
message: 'Internal Server error. Something went wrong in idea-controller',
success: false,
err: error.message,
data: {},
});
}
};

const getTopTrendingIdeas = async (req, res) => {
try {
const trendingIdeas = await ideaService.getTopTrendingIdeas();

res.status(200).json({
success: true,
message: 'Top 5 trending ideas fetched successfully',
data: trendingIdeas,
err: {},
});
} catch (error) {
console.error('Error in getTopTrendingIdeas Controller:', error);
res.status(500).json({
message: 'Internal Server error. Something went wrong while fetching top trending ideas',
success: false,
err: error.message,
data: {},
});
}
};

const getAllIdeas = async (req, res) => {
try {
const ideas = await ideaService.getAllIdeas();

res.status(200).json({
success: true,
message: 'All ideas fetched successfully',
data: ideas,
err: {},
});
} catch (error) {
console.error('Error in getAllIdeas Controller:', error);
res.status(500).json({
message: 'Internal Server error. Something went wrong while fetching all ideas',
success: false,
err: error.message,
data: {},
});
}
};

export { createIdea, deleteIdea, updateIdea, getIdea, voteIdeas, getTopTrendingIdeas, getAllIdeas };
161 changes: 161 additions & 0 deletions backend/controller/user-controller.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,161 @@
import userModel from '../model/user-model.js';
import { JWT_SECRET } from '../config/server-config.js';
import bcrypt from 'bcryptjs';
import jwt from 'jsonwebtoken';
import validator from 'validator';
import UserService from '../service/user-service.js';

const loginUser = async (req, res) => {
const { email, password } = req.body;
try {
const user = await userModel.findOne({ email });
if (!user) {
return res.status(404).json({
message: 'User not found',
success: false,
});
}

const isMatch = await bcrypt.compare(password, user.password);

if (!isMatch) {
return res.status(401).json({
message: 'Invalid user or password',
success: false,
});
}

const token = createToken(user._id);
res.json({
success: true,
token: token,
data: user,
userId: user._id,
});
} catch (error) {
console.log(error);
res.status(500).json({
success: false,
message: 'Internal Server Error',
});
}
};

const createToken = (id) => {
return jwt.sign({ id }, JWT_SECRET, { expiresIn: '15d' });
};

const registerUser = async (req, res) => {
const { name, email, password } = req.body;
try {
const exists = await userModel.findOne({ email });

if (exists) {
return res.status(200).json({
message: 'User already exists',
data: exists,
success: true,
});
}

if (!validator.isEmail(email)) {
return res.status(402).json({
message: 'Write a valid email',
success: false,
});
}

//hashing
const SALT = await bcrypt.genSalt(10);
const hashedPassword = await bcrypt.hash(password, SALT);

const newUser = new userModel({
name: name,
email: email,
password: hashedPassword,
});
console.log(newUser);

const user = await newUser.save();

const token = createToken(user._id);
res.status(202).json({
message: 'Verified token',
success: true,
token: token,
userId: user._id,
data: user,
});
} catch (error) {
console.log(error);
res.status(500).json({
success: false,
message: 'Internal Server Error',
});
}
};

const userService = new UserService();

const updateUser = async (req, res) => {
try {
const user = await userService.updateUser(req.params.id, req.body);
return res.status(200).json({
data: user,
success: true,
err: {},
message: 'Successfully updated the user info',
});
} catch (error) {
console.log(error);
res.status(500).json({
message: 'Internal Server error',
success: false,
err: error.message,
data: {},
});
}
};

const deleteUser = async (req, res) => {
try {
const user = await userService.deleteUser(req.params.id);
return res.status(200).json({
data: user,
success: true,
err: {},
message: 'Successfully deleted the account',
});
} catch (error) {
console.log(error);
res.status(500).json({
message: 'Internal Server error',
success: false,
err: error.message,
data: {},
});
}
};

const getUser = async (req, res) => {
try {
const { id } = req.params;
const user = await userService.getUser(id);
return res.status(200).json({
data: user,
success: true,
err: {},
message: 'Successfully fetched the user info',
});
} catch (error) {
console.log(error);
res.status(500).json({
message: 'Internal Server error',
success: false,
err: error.message,
data: {},
});
}
};

export { loginUser, registerUser, updateUser, deleteUser, getUser };
Loading
Loading