Commit 2f7d48e6 authored by rlacko's avatar rlacko 💬
Browse files

Merge branch 'Feature/KSZKEP-15-api-benji' into 'dev'

API Endpoints - benji

See merge request !4
parents c90a503d fcd3766a
Pipeline #4672 passed with stages
in 1 minute and 32 seconds
const { crudControllers } = require('../../utils/crud')
const { Activity } = require('./activityModel')
const { User } = require('../user/userModel')
const { Attendance } = require('../attendance/attendanceModel')
const { Comment } = require('../comment/commentModel')
const { omit, pick } = require('lodash')
exports.default = crudControllers(Activity, [
const pickedKeys = [
'_id',
'title',
'description',
'date',
'type',
])
'createdAt',
'attendance',
'comment',
]
exports.default = crudControllers(Activity, pickedKeys)
exports.default.createOne = async (req, res) => {
try {
// Invalid Date provided
if (!req.body.date || Date.parse(req.body.date) < new Date().getTime())
return res.status(403).json({ messages: ['Invalid date'] })
let activity = await Activity.create({ ...req.body })
// Create Initial participants
if (
!(
req.body.initialParticipants != null &&
req.body.initialParticipants == false
)
) {
let acceptedUsers = await User.find({ role: 'accepted' }).lean().exec()
acceptedUsers = acceptedUsers.map(function getUserSchaccs(user) {
return { schacc: user.schacc }
})
let attendances = activity.attendance
for await (let user of acceptedUsers) {
const newAttendance = await Attendance.create({
activity: activity._id,
user: user.schacc,
})
attendances.push(newAttendance._id)
}
await Activity.findOneAndUpdate(
{ _id: activity._id },
{ attendance: attendances },
{ new: true }
)
.lean()
.exec()
}
await activity
.populate({
path: 'comment',
select: '_id creator text createdAt',
})
.populate({
path: 'attendance',
select: '_id user state',
})
.execPopulate()
// conver to JS Object to overwrite .creator
let objActivity = activity.toObject()
objActivity.creator = objActivity._creator
res
.status(200)
.json({
data: pick(objActivity, pickedKeys),
})
.end()
} catch (err) {
if (err.name == 'ValidationError') {
// Throwed by Mongoose
let messages = []
for (field in err.errors) {
messages.push(err.errors[field].message)
}
return res.status(422).json({ messages })
}
console.error(err)
return res.status(500).json({ message: err.message })
}
}
exports.default.getOne = async (req, res) => {
try {
const activity = await Activity.findOne({ _id: req.params.id })
.populate({
path: 'comment',
select: '_id creator text createdAt',
})
.populate({
path: 'attendance',
select: '_id user state',
})
.select('-__v')
.lean()
.exec()
if (!activity)
return res.status(404).json({ messages: ['No such activity.'] })
return res.status(200).json({ data: pick(activity, pickedKeys) })
} catch (err) {
console.error(err)
return res.status(500).json({ message: err.message })
}
}
exports.default.getMany = async (req, res) => {
try {
const activity = await Activity.find()
.populate({
path: 'comment',
select: '_id creator text createdAt',
})
.populate({
path: 'attendance',
select: '_id user state',
})
.select('-__v')
.lean()
.exec()
if (!activity)
return res.status(404).json({ message: 'Activity not found!' })
res.status(200).json({
data: activity.map(function pickKeys(doc) {
return pick(doc, pickedKeys)
}),
})
} catch (err) {
console.error(err)
res.status(500).json({ message: err.message })
}
}
exports.default.removeOne = async (req, res) => {
try {
const activity = await Activity.findByIdAndDelete({
_id: req.params.id,
})
.populate({
path: 'comment',
select: '_id creator text createdAt',
})
.select('-__v')
.lean()
.exec()
if (!activity) {
return res.status(404).json({ message: 'Activity not found!' })
}
await Attendance.deleteMany({
_id: activity.attendance.map(function getAttendanceIds(element) {
return element._id
}),
})
await Comment.deleteMany({
_id: activity.comment.map(function getCommentIds(element) {
return element._id
}),
})
return res.status(200).json({ data: pick(activity, pickedKeys) })
} catch (err) {
console.error(err)
return res.status(500).json({ message: err.message })
}
}
exports.default.updateOne = async (req, res) => {
try {
const activity = await Activity.findOneAndUpdate(
{ _id: req.params.id },
omit(req.body, ['attendance', 'comment']),
{ new: true }
)
.populate({
path: 'comment',
select: '_id creator text createdAt',
})
.select('-__v')
.lean()
.exec()
if (!activity)
return res.status(404).json({ message: 'Activity not found!' })
res.status(200).json({ data: pick(activity, pickedKeys) })
} catch (err) {
console.error(err)
res.status(500).json({ message: err.message })
}
}
......@@ -36,9 +36,6 @@ const ActivitySchema = new mongoose.Schema(
{ timestamps: true }
)
// Careful with the docs, there are some deprecated ones
// https://mongoosejs.com/docs/guide.html
const Activity = mongoose.model('activity', ActivitySchema)
exports.Activity = Activity
const { Router } = require('express')
const controllers = require('./activityControllers')
const { isLoggedIn, isMentor } = require('../../middlewares/auth')
const router = Router()
// /api/item
router
.route('/')
.get(controllers.default.getMany)
.post(controllers.default.createOne)
.get(isLoggedIn, controllers.default.getMany)
.post(isLoggedIn, isMentor, controllers.default.createOne)
// /api/item/:id
router
.route('/:id')
.get(controllers.default.getOne)
.put(controllers.default.updateOne)
.delete(controllers.default.removeOne)
.get(isLoggedIn, controllers.default.getOne)
.put(isLoggedIn, isMentor, controllers.default.updateOne)
.delete(isLoggedIn, isMentor, controllers.default.removeOne)
exports.default = router
......@@ -6,6 +6,8 @@ const pickedKeys = ['_id', 'activity', 'user', 'state', 'comment']
exports.default = crudControllers(Attendance, pickedKeys)
// On create update activity
exports.default.getOne = async (req, res) => {
try {
const attendance = await Attendance.findOne({ _id: req.params.id })
......
const { crudControllers } = require('../../utils/crud')
const { Comment } = require('./commentModel')
const { omit, pick } = require('lodash')
exports.default = crudControllers(Comment)
exports.default = crudControllers(Comment, ['creator', 'text', 'date'])
function invalidIdResponse(res) {
return res
.status(403)
.json({ messages: ['You cannot modify other users comment.'] })
.end()
}
exports.default.getOne = async (req, res) => {
try {
const comment = await Comment.findOne({
_id: req.params.id,
})
.populate('creator', ['fullName', 'nickName'])
.lean()
.exec()
if (comment.creator._id !== req.user._id && req.user.role !== 'mentor') {
return invalidIdResponse(res)
}
return res
.status(200)
.json({ data: omit(comment, ['_id', '__v', 'creator._id']) })
.end()
} catch (err) {
res.json(err)
}
}
exports.default.getMany = async (req, res) => {
try {
const comments = await Comment.find()
.populate('_creator', '-_id fullName nickName')
.select(['-__v'])
.lean()
.exec()
return res.status(200).json({ data: comments }).end()
} catch (err) {
console.log(err)
res.json(err)
}
}
exports.default.createOne = async (req, res) => {
try {
var comment = await Comment.create({
creator: req.user.schacc,
text: req.body.text,
}).catch((err) => console.log(err))
const retComment = await Comment.findById(comment._id)
.populate('_creator', '-_id fullName nickName schacc')
.lean()
.exec()
retComment.creator = retComment._creator
return res
.status(200)
.json({
data: pick(retComment, ['_id', 'creator', 'text', 'createdAt']),
})
.end()
} catch (err) {
console.log(err)
}
}
exports.default.updateOne = async (req, res) => {
try {
var comment = await Comment.findById(req.params.id).populate('creator')
if (comment.creator._id !== req.user._id) {
return invalidIdResponse(res)
}
var updatedComment = await Comment.findOneAndUpdate(
{ _id: req.params.id },
{ text: req.body.text },
{ new: true }
)
.lean()
.exec()
return res.status(200).json({ data: updatedComment }).end()
} catch (err) {
console.log(err)
}
}
// TODO on delete remove from other models
exports.default.removeOne = async (req, res) => {
try {
const comment = await Comment.findById({ _id: req.params.id })
.populate('creator')
.lean()
.exec()
if (comment.creator._id !== req.user._id) {
return invalidIdResponse(res)
}
const removed = await Comment.findByIdAndRemove({ _id: req.params.id })
if (!removed) {
return res.status(404).end()
}
return res.status(200).json({ data: comment }).end()
} catch (err) {
console.log(err)
}
}
......@@ -9,9 +9,10 @@ const CommentSchema = new mongoose.Schema(
type: String,
required: true,
},
date: {
type: Date,
isAnonim: {
type: Boolean,
required: true,
default: false,
},
},
{ timestamps: true }
......
const { Router } = require('express')
const controllers = require('./commentControllers')
const { isLoggedIn, isMentor } = require('../../middlewares/auth')
const router = Router()
// /api/item
router
.route('/')
.get(controllers.default.getMany)
.post(controllers.default.createOne)
.get(isLoggedIn, isMentor, controllers.default.getMany)
.post(isLoggedIn, controllers.default.createOne)
// /api/item/:id
router
.route('/:id')
.get(controllers.default.getOne)
.put(controllers.default.updateOne)
.delete(controllers.default.removeOne)
.get(isLoggedIn, controllers.default.getOne)
.put(isLoggedIn, controllers.default.updateOne)
.delete(isLoggedIn, controllers.default.removeOne)
exports.default = router
const { crudControllers } = require('../../utils/crud')
const { Solution } = require('./solutionModel')
const { Task } = require('../task/taskModel')
const { pick } = require('lodash')
exports.default = crudControllers(Solution)
exports.default.createOne = async (req, res) => {
try {
const task = await Task.findById(req.body.task)
let solution
if (req.user.role === 'mentor' && req.body.creator) {
// Mentor Creates/Updates a Solution to someone
solution = await Solution.findOneAndUpdate(
{ creator: req.body.creator, task: req.body.task },
{ ...req.body },
{
upsert: true, // Create new One if there is no match
returnOriginal: false,
setDefaultsOnInsert: true,
runValidators: true,
}
)
.lean()
.exec()
} else {
// Someone creates a solution
if (req.user.role != 'mentor') {
delete req.body.isAccepted
delete req.body.comment
}
if (task.deadline < new Date())
return res.status(400).json({
message: `Can't create new Solution! End date was ${task.deadline.toDateString()}`,
})
solution = await Solution.findOneAndUpdate(
{ creator: req.user.schacc, task: req.body.task },
{ ...req.body },
{
upsert: true, // Create new One if there is no match
returnOriginal: false,
setDefaultsOnInsert: true,
runValidators: true,
}
)
.lean()
.exec()
}
if (task.solutions.indexOf(solution._id) == -1) {
task.solutions.push(solution._id)
task.save()
}
let retSolution = await Solution.findById({ _id: solution._id })
.populate('_creator', '-_id fullName nickName schacc')
.populate('comment', 'text creator createdAt')
.lean()
.exec()
retSolution.creator = retSolution._creator
return res.status(200).json({
data: pick(retSolution, [
'_id',
'creator',
'title',
'description',
'file',
'task',
'comment',
'createdAt',
'updatedAt',
'isAccepted',
]),
})
} catch (err) {
if (err.name == 'ValidationError') {
// Throwed by Mongoose
let messages = []
for (field in err.errors) {
messages.push(err.errors[field].message)
}
return res.status(422).json({ messages })
}
console.error(err)
return res.status(500).json({ message: err.message })
}
}
exports.default.getMany = async (req, res) => {
try {
let solutions = undefined
if (req.user.role === 'mentor')
solutions = await Solution.find()
.populate('_creator', '-_id fullName nickName schacc')
.populate('comment', 'text creator createdAt')
.select('-__v')
.lean()
.exec()
else
solutions = await Solution.find({ user: req.user._id })
.populate('_creator', '-_id fullName nickName')
.populate('comment', '-_id text creator createdAt')
.select('-__v')
.lean()
.exec()
return res.status(200).json({
data: solutions.map((e) => {
e.creator = e._creator
return pick(e, [
'_id',
'creator',
'title',
'description',
'file',
'task',
'comment',
'createdAt',
'updatedAt',
'isAccepted',
])
}),
})
} catch (err) {
if (err.name == 'ValidationError') {
// Throwed by Mongoose
let messages = []
for (field in err.errors) {
messages.push(err.errors[field].message)
}
return res.status(422).json({ messages })
}
console.error(err)
return res.status(500).json({ message: err.message })
}
}
exports.default.getOne = async (req, res) => {
try {
let solution = await Solution.findById({ _id: req.params.id })
.populate('_creator', '-_id fullName nickName')
.populate('comment', 'text creator createdAt')
.select('-__v')
.lean()
.exec()
if (!solution)
return res.status(404).json({ messages: ['No such solution.'] })
if (req.user.schacc !== solution.creator && req.user.role !== 'mentor') {
return res
.status(403)
.json({ message: `You don't have permission for this solution.` })
}
return res.status(200).json({
data: pick(solution, [
'_id',
'creator',
'title',
'description',
'file',