import { BadRequestError , Body , CurrentUser , Get , JsonController , Param , Put , UseBefore , ForbiddenError } from 'routing-controllers' ; import * as moment from 'moment' ; import passportJwtMiddleware from '../security/passportJwtMiddleware' ; import { errorCodes } from '../config/errorCodes' ; import { Progress } from '../models/progress/Progress' ; import { Course } from '../models/Course' ; import { Unit , IUnitModel } from '../models/units/Unit' ; import { IUser } from '../../../shared/models/IUser' ; @ JsonController ( '/progress' ) @ UseBefore ( passportJwtMiddleware ) export class ProgressController { private static checkDeadline ( unit ) { if ( unit . deadline && moment ( unit . deadline ) . isBefore ( ) ) { throw new BadRequestError ( errorCodes . progress . pastDeadline . text ) ; } } api apiName apiGroup apiParam apiSuccess apiSuccessExample apiError @ Get ( '/units/:id' ) async getUnitProgress ( @ Param ( 'id' ) id , @ CurrentUser ( ) currentUser ) { const unit = await Unit . findById ( id ) ; const course = await Course . findById ( unit . _course ) ; if ( ! course . checkPrivileges ( currentUser ) . userCanViewCourse ) { throw new ForbiddenError ( ) ; } const progress = await Progress . findOne ( { user : currentUser , unit : id } ) ; return progress ? progress . toObject ( { virtuals : true } ) : { } ; } api apiName apiGroup apiParam apiParam apiSuccess apiSuccessExample apiError @ Put ( '/' ) async updateProgress ( @ Body ( ) data , @ CurrentUser ( ) currentUser ) { const unit = await Unit . findById ( data . unit ) ; const course = await Course . findById ( unit . _course ) ; if ( ! course . checkPrivileges ( currentUser ) . userCanViewCourse ) { throw new ForbiddenError ( ) ; } ProgressController . checkDeadline ( unit ) ; data . user = currentUser . _id ; data . course = course . _id ; let progress = await Progress . findOne ( { user : currentUser , unit } ) ; if ( ! progress ) { progress = await Progress . create ( data ) ; } else { progress . set ( data ) ; await progress . save ( ) ; } return progress . toObject ( ) ; } }