Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
IMiddlewareError, Err, Next, Request, Response,
OverrideMiddleware, GlobalErrorHandlerMiddleware
} from 'ts-express-decorators';
import { ValidatorError } from 'typescript-param-validator';
import { API_ERRORS } from '../types/app.errors';
import { ApiError } from '../utils/error';
export interface IApiErrorResponse {
code: number;
status: number;
message: string;
stack?: string;
reasons?: string[];
}
@OverrideMiddleware(GlobalErrorHandlerMiddleware)
export class ServerErrorMiddleware implements IMiddlewareError {
constructor() {}
public use(
@Err() error: ApiError | ValidatorError,
@Request() request: ExpressRequest,
@Response() res: ExpressResponse,
@Next() next: ExpressNext
) {
// tslint:disable-next-line
let { status, code, message } = error as ApiError;
const response: IApiErrorResponse = {
message: message || 'Error occurred',
code: code,
status
import { Request } from 'express';
import { IMiddleware, OverrideMiddleware, AuthenticatedMiddleware,
EndpointInfo, EndpointMetadata, Req
} from 'ts-express-decorators';
import { AuthService } from '../services/auth/auth.service';
import { API_ERRORS } from '../types/app.errors';
import { ApiError } from '../utils/error';
@OverrideMiddleware(AuthenticatedMiddleware)
export class AuthMiddleware implements IMiddleware {
constructor(
private authService: AuthService
) {
}
async use(@EndpointInfo() endpoint: EndpointMetadata, @Req() request: Request) {
const token = this.extractHeaderFromRequest(request);
if (!token) throw new ApiError(API_ERRORS.UNAUTHORIZED);
request.user = await this.authService.validateToken(token);
}
private extractHeaderFromRequest(req: Request): string {
const authHeader = req.headers.authorization;
import { Response as ExpressResponse } from 'express';
import {
SendResponseMiddleware, IMiddlewareError, OverrideMiddleware, ResponseData, Response
} from 'ts-express-decorators';
@OverrideMiddleware(SendResponseMiddleware)
export class ServerResponseMiddleware implements IMiddlewareError {
public use(
@ResponseData() data: any,
@Response() res: ExpressResponse
) {
/**
* We want to wrap all of our api responses inside a data object
* This will help when the API will need to response
*/
res.json({
data
});
}
}