import { Request , Response } from 'express' ; import { RestResponse } from './rest-response' ; import { Validatable , Validator , ValidatorError } from '../validation' ; import { BusinessViolationError , MethodNotAllowedError , ResourceNotFoundError , ValidationFailureError , ValidationFailureFactory } from './errors' ; export class RestController { constructor ( ) { } respond ( res , item , statusCode = 200 ) { const response = new RestResponse ( item ) ; return res . status ( statusCode ) . json ( response ) ; } respondNoContent ( res , statusCode = 204 ) { return res . status ( statusCode ) . json ( ) ; } validateModel ( model ) { const validatorErrors = model . validate ( ) ; this . throwValidatorErrors ( validatorErrors ) ; } validateData ( data , constraints ) { const validatorErrors = Validator . validate ( data , constraints ) ; this . throwValidatorErrors ( validatorErrors ) ; } validateResourceFound ( item ) { if ( item == null ) { throw new ResourceNotFoundError ( ) ; } } throwMethodNotAllowedError ( req , res , next ) { throw new MethodNotAllowedError ( ) ; } throwBusinessViolation ( businessViolationCode , message ? ) { throw new BusinessViolationError ( businessViolationCode , message ) ; } private throwValidatorErrors ( validatorErrors ) { if ( validatorErrors == null ) { return ; } const failures = validatorErrors . map ( ( error ) => { return ValidationFailureFactory . fromValidatorError ( error ) ; } ) ; throw new ValidationFailureError ( failures ) ; } }