import passportJwtMiddleware from '../security/passportJwtMiddleware' ; import { BadRequestError , Get , JsonController , QueryParam , UseBefore , CurrentUser , NotFoundError , ForbiddenError } from 'routing-controllers' ; import { errorCodes } from '../config/errorCodes' ; import { IMessageModel , Message } from '../models/Message' ; import { IUser } from '../../../shared/models/IUser' ; import { ChatRoom } from '../models/ChatRoom' ; @ JsonController ( '/message' ) @ UseBefore ( passportJwtMiddleware ) export default class MessageController { private async assertUserViewAuthForRoomId ( currentUser , roomId ) { if ( ! roomId ) { throw new BadRequestError ( ) ; } const room = await ChatRoom . findById ( roomId ) ; if ( ! room ) { throw new NotFoundError ( errorCodes . chat . roomNotFound . text ) ; } if ( ! ( await room . checkPrivileges ( currentUser ) ) . userCanViewMessages ) { throw new ForbiddenError ( ) ; } } api apiName apiGroup apiParam apiParam apiParam apiParam apiSuccess apiSuccessExample apiError apiError apiError @ Get ( '/' ) async getMessages ( @ QueryParam ( 'room' ) roomId , @ QueryParam ( 'skip' ) skip = 0 , @ QueryParam ( 'limit' ) limit , @ QueryParam ( 'order' ) order = - 1 , @ CurrentUser ( ) currentUser ) { await this . assertUserViewAuthForRoomId ( currentUser , roomId ) ; const messages = await Message . find ( { room : roomId } ) . sort ( { createdAt : order } ) . skip ( skip ) . limit ( limit ) ; return messages . map ( ( message ) => message . forDisplay ( ) ) ; } api apiName apiGroup apiParam apiSuccessExample apiError apiError apiError @ Get ( '/count' ) async getMessageCount ( @ QueryParam ( 'room' ) roomId , @ CurrentUser ( ) currentUser ) { await this . assertUserViewAuthForRoomId ( currentUser , roomId ) ; const count = await Message . countDocuments ( { room : roomId } ) ; return { count } ; } }