Skip to content

Commit

Permalink
Merge pull request #10 from TuhinBar/dev
Browse files Browse the repository at this point in the history
production v1.0
  • Loading branch information
tuhinexe authored Apr 7, 2023
2 parents 0af5fe0 + 6cda5d6 commit 02f6a0a
Show file tree
Hide file tree
Showing 119 changed files with 12,296 additions and 0 deletions.
96 changes: 96 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
# Logs
logs
.log
npm-debug.log
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
.pnpm-debug.log*

# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9].[0-9].[0-9].[0-9].json

# Runtime data
pids
*.pid
*.seed
*.pid.lock

# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov

# Coverage directory used by tools like istanbul
coverage
*.lcov

# nyc test coverage
.nyc_output

# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt

# Bower dependency directory (https://bower.io/)
bower_components

# node-waf configuration
.lock-wscript

# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release

# Dependency directories
node_modules/
jspm_packages/

# Snowpack dependency directory (https://snowpack.dev/)
web_modules/

# TypeScript cache
*.tsbuildinfo

# Optional npm cache directory
.npm

# Optional eslint cache
.eslintcache

# Optional stylelint cache
.stylelintcache

# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/

# Optional REPL history
.node_repl_history

# Output of 'npm pack'
*.tgz

# Yarn Integrity file
.yarn-integrity

# dotenv environment variable files
.env
.env.development.local
.env.test.local
.env.production.local
.env.local

# parcel-bundler cache (https://parceljs.org/)
.cache
.parcel-cache

# Next.js build output
.next
out

# Nuxt.js build / generate output
.nuxt
dist

# Gatsby files
.cache/
# Comment in t
81 changes: 81 additions & 0 deletions backend/api/ChallengesAPI.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
const Challenges = require("../models/Challenges");
const User = require("../models/Users");

const fetchChallenges = async () => {
const challenges = await Challenges.find({})
.sort({ timestamp: -1 })
.populate("creatorId")
.exec();
return challenges;
};

const createChallenges = async (challengeData, userId) => {
try {
const challenge = new Challenges(challengeData);
await Promise.all([await challenge.save(), User.updateOne(
{ _id: userId },
{
$push: { participatedChallenges: challenge._id },
$addToSet: { challenges: challenge._id },
$inc: { points: 5 }
}
)])
return challenge;
} catch (err) {
console.log(err);
throw new Error(err);
}
};

const fetchOneChallenge = async (challengeId) => {
try {
const challenge = await Challenges.findOne({ _id: challengeId })
.populate("creatorId")
.populate("participators")
.exec();
return challenge;
} catch (err) {
throw new Error(err);
}
};

const participateInChallenge = async(challengeId, userId)=>{
try {
const challenge = await Challenges.findOne({ _id: challengeId });
if (challenge.participators.includes(userId)) {
throw new Error(`You have already participated`);
}
const participatePromise = Challenges.updateOne(
{ _id: challengeId },
{ $addToSet: { participators: userId } }
);
const challengeCreator = await User.findById(challenge.creatorId);
challengeCreator.points += 2;
const foundUserPromise = User.updateOne({ _id: userId }, { $addToSet: { participatedChallenges: challengeId } });
const [user, resultOfParticipation] = await Promise.all([foundUserPromise, participatePromise, challengeCreator.save()]);
return resultOfParticipation;
} catch (error) {
throw new Error(error.message);
}
}

const deleteChallenge = async (challengeId, user) => {
try {
await Challenges.findByIdAndDelete(challengeId);
user.challenges.pull(challengeId)
user.points -= 5;
await user.save();
}catch{
console.log(err);
}
}


module.exports = { fetchChallenges, createChallenges, fetchOneChallenge, participateInChallenge, deleteChallenge };


// const userPromise = User.findById(userId);
// const challengesPromise = Challenge.find({ participants: userId }).sort({
// createdAt: -1
// });
// const [user, challenges] = await Promise.all([userPromise, challengesPromise]);
45 changes: 45 additions & 0 deletions backend/api/commentAPI.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
const Comment = require("../models/Comments");
const Posts = require("../models/Posts");
const User = require("../models/Users");

const addComment = async (commentDetails, postId) => {
try {
const newComment = new Comment(commentDetails);
await newComment.save();

const post = await Posts.findById(postId);
const postCreator = await User.findById(post.creator);
postCreator.points += 2;
await post.stats.comments.push(newComment._id);
Promise.all([postCreator.save(), post.save()])
.then(() => {
return;
})
.catch((error) => {
throw new Error(error);
});
} catch (err) {
throw new Error(err);
}
};

const deleteComment = async (commentId, postId) => {
const post = await Posts.findById(postId);
post.stats.comments.pull(commentId);
const postCreator = await User.findById(post.creator);
postCreator.points -= 2;
Promise.all([
postCreator.save(),
post.save(),
Comment.findByIdAndDelete(commentId),
])
.then(() => {
return;
})
.catch((error) => {
throw new Error(error);
});
};


module.exports = {addComment, deleteComment};
17 changes: 17 additions & 0 deletions backend/api/deleteImage.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
const cloudinary = require('cloudinary').v2;

// Configuration
cloudinary.config({
cloud_name: process.env.CLOUD_NAME,
api_key: process.env.API_KEY,
api_secret: process.env.API_SECRET
});


// Delete image from cloudinary
const deleteImage = async (imageId) => {
await cloudinary.uploader.destroy(imageId);
return true;
}

module.exports = deleteImage;
55 changes: 55 additions & 0 deletions backend/api/devAPI.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
const userModel = require("../models/Users");
const postModel = require("../models/Posts");

async function increaseLike(postId, currentLike, currentDisLike, userId) {
const postFound = await postModel.findById(postId).then((post)=>{
if(post){
let indexInDownvotes = post.stats.downvoted_by.indexOf(userId);
if(indexInDownvotes > -1){
post.stats.downvoted_by.splice(indexInDownvotes, 1);
}
post.stats.upvoted_by.push(userId);
post.stats.upvotes = currentLike + 1;
post.stats.downvotes = currentDisLike;
post.save();
userModel.findById(post.creator).then((user)=>{
user.points += 1;
user.save();
})
return post;
}

});
if (postFound) {
return postFound.posts;
} else {
console.log("posts not found");
}
}
async function decreaseLike(postId, currentLike, currentDisLike, userId) {
const postFound = await postModel.findById(postId).then((post)=>{
if(post){
let indexInUpvotes = post.stats.upvoted_by.indexOf(userId);
if(indexInUpvotes > -1){
post.stats.upvoted_by.splice(indexInUpvotes, 1);
}
post.stats.downvoted_by.push(userId);
post.stats.upvotes = currentLike;
post.stats.downvotes = currentDisLike + 1;
post.save();
userModel.findById(post.creator).then((user)=>{
user.points -= 1;
user.save();
})
return post;
}

});
if (postFound) {
return postFound.posts;
} else {
console.log("posts not found");
}
}

module.exports = { increaseLike, decreaseLike };
16 changes: 16 additions & 0 deletions backend/api/getSignature.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
const cloudinary = require('cloudinary').v2;

// Configuration
cloudinary.config({
cloud_name: process.env.CLOUD_NAME,
api_key: process.env.API_KEY,
api_secret: process.env.API_SECRET
});

const getSignature = async (req, res) => {
const timestamp = Math.round(new Date().getTime() / 1000);
const signature = cloudinary.utils.api_sign_request( { timestamp: timestamp }, process.env.API_SECRET);
res.json({signature: signature, timestamp: timestamp});
}

module.exports = getSignature;
52 changes: 52 additions & 0 deletions backend/api/pollsApi.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
const Polls = require("../models/Polls");
const User = require("../models/Users");

const voteCount = async (pollId, optionId, userId) => {
try {
const poll = await Polls.findById(pollId);
let option = poll.options.find((option) => option._id == optionId);
for (optionCheck of poll.options) {
if (optionCheck.voted_by.includes(userId)) {
return;
}
}
const pollCreator = await User.findById(poll.creatorId);
pollCreator.points += 1;
option.voted_by.push(userId);
await Promise.all([pollCreator.save(), poll.save()]);
} catch (err) {
console.log(err);
}
};

const deletePoll = async (pollId, user) => {
try {
user.polls.pull(pollId);
user.points -= 5;
await Promise.all([user.save(), Polls.findByIdAndDelete(pollId)]);
} catch {
console.log(err);
}
};

const fetchPolls = async () => {
const polls = await Polls.find({}).sort({timestamp: -1}).populate("creatorId").exec();
const totalVotes = polls.map(poll => {
return poll.options.reduce((acc, option) => {
return acc + option.voted_by.length;
}, 0);
});
return [polls, totalVotes];
}


async function getPolls(user) {
const userFound = await User.findById(user._id).populate("polls").exec();
if (userFound) {
return userFound.polls;
} else {
console.log("poll not found");
}
}

module.exports = { voteCount, deletePoll, fetchPolls, getPolls };
Loading

0 comments on commit 02f6a0a

Please sign in to comment.