import { Authorized , Body , BodyParam , CurrentUser , Delete , ForbiddenError , Get , JsonController , NotFoundError , Param , Post , Put , UseBefore } from 'routing-controllers' ; import passportJwtMiddleware from '../security/passportJwtMiddleware' ; import { Lecture } from '../models/Lecture' ; import { ILecture } from '../../../shared/models/ILecture' ; import { Course } from '../models/Course' ; import { IUser } from '../../../shared/models/IUser' ; @ JsonController ( '/lecture' ) @ UseBefore ( passportJwtMiddleware ) export class LectureController { api apiName apiGroup apiParam apiSuccess apiSuccessExample apiError apiError @ Get ( '/:id' ) async getLecture ( @ Param ( 'id' ) id , @ CurrentUser ( ) currentUser ) { const lecture = await Lecture . findById ( id ) . orFail ( new NotFoundError ( ) ) ; const course = await Course . findOne ( { lectures : id } ) ; if ( ! course . checkPrivileges ( currentUser ) . userCanViewCourse ) { throw new ForbiddenError ( ) ; } return lecture . toObject ( ) ; } api apiName apiGroup apiPermission apiPermission apiParam apiSuccess apiSuccessExample apiError apiError @ Authorized ( [ 'teacher' , 'admin' ] ) @ Post ( '/' ) async addLecture ( @ BodyParam ( 'name' , { required : true } ) name , @ BodyParam ( 'description' , { required : true } ) description , @ BodyParam ( 'courseId' , { required : true } ) courseId , @ CurrentUser ( ) currentUser ) { const course = await Course . findById ( courseId ) . orFail ( new NotFoundError ( ) ) ; if ( ! course . checkPrivileges ( currentUser ) . userCanEditCourse ) { throw new ForbiddenError ( ) ; } const lecture = await new Lecture ( { name , description } ) . save ( ) ; course . lectures . push ( lecture ) ; await course . save ( ) ; return lecture . toObject ( ) ; } api apiName apiGroup apiPermission apiPermission apiParam apiParam apiSuccess apiSuccessExample apiError apiError @ Authorized ( [ 'teacher' , 'admin' ] ) @ Put ( '/:id' ) async updateLecture ( @ Param ( 'id' ) id , @ Body ( ) lectureUpdate , @ CurrentUser ( ) currentUser ) { const course = await Course . findOne ( { lectures : id } ) . orFail ( new NotFoundError ( ) ) ; if ( ! course . checkPrivileges ( currentUser ) . userCanEditCourse ) { throw new ForbiddenError ( ) ; } const lecture = await Lecture . findByIdAndUpdate ( id , lectureUpdate , { 'new' : true } ) ; return lecture . toObject ( ) ; } api apiName apiGroup apiPermission apiPermission apiParam apiSuccess apiSuccessExample apiError apiError @ Authorized ( [ 'teacher' , 'admin' ] ) @ Delete ( '/:id' ) async deleteLecture ( @ Param ( 'id' ) id , @ CurrentUser ( ) currentUser ) { const course = await Course . findOne ( { lectures : id } ) . orFail ( new NotFoundError ( ) ) ; if ( ! course . checkPrivileges ( currentUser ) . userCanEditCourse ) { throw new ForbiddenError ( ) ; } await Course . updateMany ( { } , { $pull : { lectures : id } } ) ; await Lecture . findByIdAndRemove ( id ) ; return { } ; } }