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

PrivateEvents #36

Open
wants to merge 7 commits into
base: dev-v2
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 5 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
Binary file modified .env.secret
Binary file not shown.
16,458 changes: 16,415 additions & 43 deletions package-lock.json

Large diffs are not rendered by default.

2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@
"lusca": "^1.6.1",
"mongoose": "^5.7.5",
"mongoose-unique-validator": "^2.0.3",
"node-cron": "^3.0.0",
"nodemailer": "^6.2.1",
"request": "^2.88.0",
"request-promise": "^4.2.4",
Expand All @@ -65,6 +66,7 @@
"@types/mongoose": "^5.5.6",
"@types/mongoose-unique-validator": "^1.0.1",
"@types/node": "^13.11.1",
"@types/node-cron": "^2.0.4",
"@types/nodemailer": "^6.2.0",
"@types/request-promise": "^4.1.44",
"@types/slug": "^0.9.1",
Expand Down
5 changes: 4 additions & 1 deletion src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@ import * as compression from 'compression';
import * as admin from 'firebase-admin';
import * as fs from 'fs';
import {MONGODB_URI} from './utils/secrets';

import * as cron from 'node-cron';
import {trendUpdate} from './cronJobs/trendUpdate';
import routes from './routes';

let serviceAccount;
Expand Down Expand Up @@ -91,4 +92,6 @@ app.use(
}
);

// Schedule cron-Jobs
cron.schedule('0 */30 * * * *', trendUpdate);
export default app;
5 changes: 5 additions & 0 deletions src/controllers/body.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,11 @@ export const addBody = async (
next: NextFunction
) => {
try {
const user = await User.findById(req.payload);

if (user === null || user.superSuperAdmin === false) {
throw createError(401, 'Unauthorized', 'Invalid');
}
const newBody = new Body(req.body);
await newBody.save();
res.send(createResponse('Body Created Successfully', newBody));
Expand Down
221 changes: 142 additions & 79 deletions src/controllers/event.ts
Original file line number Diff line number Diff line change
Expand Up @@ -137,19 +137,61 @@ export const deleteEvent = async (
}
};

export const getEvent = async (req: Request, res: Response) => {
const [user, event] = await Promise.all([
User.findById(req.payload),
Event.findById(req.params.id).populate('body').populate('updates').exec(),
]);
if (user === null || event === null) {
return res.status(400).json({message: 'Error'});
export const getStarredEvents = async (
req: Request,
res: Response,
next: NextFunction
) => {
try {
const user = await User.findById(req.payload);

if (user === null) {
throw createError(401, 'Unauthorized', 'Invalid');
}
const starredEvents = user.staredEvents;
res.send(createResponse('Starred Events', starredEvents));
} catch (error) {
next(error);
}
};

export const getEvent = async (
req: Request,
res: Response,
next: NextFunction
) => {
try {
const user = await User.findById(req.payload);
const event = await Event.findById(req.params.id)
.populate('body')
.populate('updates');
if (user === null) {
throw createError(401, 'Unauthorized', 'Invalid');
}
if (event === null) {
throw createError(400, 'Error ', 'Invalid Event');
}
// console.log(event);
const body = await Body.findById(event.body);
if (!body) {
throw createError(400, 'Error ', 'Invalid');
}
const members = body.members;
const valid_member = members.filter(member => {
return member.userId.toString() === user._id.toString();
});
// console.log(valid_member);
if (event.private === false || valid_member.length !== 0) {
const respData = {
event: toEventJSON(event, user),
};
res.send(createResponse('Event Found', respData));
} else {
throw createError(400, 'Error', 'Event is not public');
}
} catch (error) {
next(error);
}
// console.log(event);
const respData = {
event: toEventJSON(event, user),
};
return res.send(respData);
};

export const getEvents = async (
Expand All @@ -159,36 +201,58 @@ export const getEvents = async (
) => {
//!TODO IF WE WANT TO ADD THE OPTION TO FILTER BY CLUB OR YEAR OR ANYTHING
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const query: any = {};
if (typeof req.query.body !== 'undefined') {
query.body = req.query.body;
}
return Promise.all([
Event.find(query)
// .sort({ endDate: "desc" })
.populate('body')
.populate('updates')
.exec(),
User.findById(req.payload),
])
.then(([events, user]) => {
if (user === null) {
throw createError(401, 'Unauthorized', 'Invalid');
}
if (events !== null) {
const respData = {
events: events.map(event => toEventJSON(event, user)),
};
return res.send(createResponse('Events Found', respData));
try {
const user = await User.findById(req.payload);
if (user === null) {
throw createError(401, 'Unauthorized', 'Invalid');
}
let events;
let priv = false;
if (req.query) {
if (req.query.p === '1') {
priv = true;
}
const respData = {
}
events = await Event.find({private: priv})
.populate('body')
.populate('updates');
// events = await Event.find().populate('body').populate('updates');
if (priv) {
//using maps to return an array of promises
const promises = events.map(event => Body.findById(event.body));
const bodies = await Promise.all(promises);
const fevents = events.filter((event, index) => {
const body = bodies[index];
if (!body) {
return false;
}
const members = body.members;
const valid_member = members.filter(member => {
return member.userId.toString() === user._id.toString();
});
if (valid_member.length !== 0) {
return true;
} else {
return false;
}
});
events = fevents;
}

let respData;
if (events !== null) {
respData = {
events: events.map(event => toEventJSON(event, user)),
};
} else {
respData = {
events: [],
};
return res.send(createResponse('Events Found', respData));
})
.catch(e => {
next(e);
});
}
res.send(createResponse('Events Found', respData));
} catch (error) {
next(error);
}
};

export const addUpdate = async (
Expand Down Expand Up @@ -279,49 +343,48 @@ export const removeUpdate = async (
}
};

export const putUpdateEvent = (
export const putUpdateEvent = async (
req: Request,
res: Response,
next: NextFunction
) => {
return Promise.all([
Event.findById(req.params.id),
User.findById(req.payload),
])
.then(([event, user]) => {
if (event === null || user === null) {
throw createError(400, 'Invalid', 'No Such Event Exists');
}
if (req.body.name !== null) {
event.name = req.body.name;
}
if (req.body.about !== null) {
event.about = req.body.about;
}
if (req.body.imageLink !== null) {
event.imageLink = req.body.imageLink;
}
if (req.body.venue !== null) {
event.venue = req.body.venue;
}
if (req.body.startDate !== null) {
event.startDate = req.body.startDate;
}
if (req.body.endDate !== null) {
event.endDate = req.body.endDate;
}
event.save().then(event => {
// const respData = {
// event: toEventJSON(event, user)
// };
// console.log(respData);
const respData = {
id: event._id,
};
return res.send(createResponse('Event Updated Successfully', respData));
});
})
.catch(e => {
next(e);
try {
const [event, user] = await Promise.all([
Event.findById(req.params.id),
User.findById(req.payload),
]);
if (event === null || user === null) {
throw createError(400, 'Invalid', 'No Such Event Exists');
}
if (req.body.name !== null) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fix The update method, the same can be done using a single command.

event.name = req.body.name;
}
if (req.body.about !== null) {
event.about = req.body.about;
}
if (req.body.imageLink !== null) {
event.imageLink = req.body.imageLink;
}
if (req.body.venue !== null) {
event.venue = req.body.venue;
}
if (req.body.startDate !== null) {
event.startDate = req.body.startDate;
}
if (req.body.endDate !== null) {
event.endDate = req.body.endDate;
}
event.save().then(event_1 => {
// const respData = {
// event: toEventJSON(event, user)
// };
// console.log(respData);
const respData = {
id: event_1._id,
};
return res.send(createResponse('Event Updated Successfully', respData));
});
} catch (e) {
next(e);
}
};
3 changes: 2 additions & 1 deletion src/controllers/news.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ export const getNews = async (
title: 1,
sourceName: 1,
createdAt: 1,
trendRate: 1,
},
{
limit: parseInt(req.query.limit),
Expand All @@ -56,7 +57,7 @@ export const newsDetails = async (
throw createError(401, 'Unauthorized', 'Invalid Credentials');
}
const news = await News.findById(req.params.id);
if (!news) {
if (!news || news.visible === false) {
throw createError(
401,
'Doesnot Exists',
Expand Down
1 change: 1 addition & 0 deletions src/controllers/role.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
//Controllers File for Roles
7 changes: 3 additions & 4 deletions src/controllers/user.ts
Original file line number Diff line number Diff line change
Expand Up @@ -349,16 +349,15 @@ export const removeAdmin = async (
// }
// };

export const loggedInUserDetails = (
export const loggedInUserDetails = async (
req: Request,
res: Response,
next: NextFunction
) => {
try {
const user = User.findById(req.payload)
const user = await User.findById(req.payload)
.populate('adminOf')
.populate('superAdminOf')
.exec();
.populate('superAdminOf');

if (user === null) {
throw createError(401, 'Unauthorized', 'No Such User Found');
Expand Down
9 changes: 9 additions & 0 deletions src/cronJobs/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
## Cron-Jobs

---

> This folder contains Jobs that are required to run regularly at specified period of time. This is done using `node-cron` npm package

_**Currently The Jobs are :**_

1. **TrendUpdate** : It updates the trendRate for all the news documents. Runs every 30 minutes
19 changes: 19 additions & 0 deletions src/cronJobs/trendUpdate.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import News from '../models/news';

export const trendUpdate = async () => {
try {
console.log('News TrendUpdate:Start', Date.now());
const news = await News.find({visible: true});
news.forEach(async thisDoc => {
const timeElapsedInHours =
(new Date().getTime() - thisDoc.createdAt.getTime()) / (1000 * 60 * 60);
const trendRate = thisDoc.clicks / timeElapsedInHours;
thisDoc.trendRate = trendRate;

await News.updateOne({_id: thisDoc._id}, {$set: {trendRate: trendRate}});
});
console.log('News TrendUpdate:Stop', Date.now());
} catch (err) {
console.log(err);
}
};
Loading