All files / src Handler.ts

100% Statements 66/66
100% Branches 8/8
100% Functions 26/26
100% Lines 65/65

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176                              1x   1x         1x   1x     1x                           82x 82x       78x       1x 1x 1x       1x       48x         48x 48x 8x 8x 8x       5x 5x 5x 1x     4x   5x 5x     43x 1x           43x 1x     43x 1x     43x       8x       31x 31x 29x 29x   2x 2x           5x 5x 4x 4x   1x 1x           7x 7x 6x 6x   1x 1x           5x 5x 4x 4x   1x 1x           3x 3x       1x 1x       1x 1x       1x 1x      
// Copyright (C) 2017  Norman Breau
 
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
 
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
 
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
import {StatusCode} from './StatusCode';
import {Application} from './Application';
import {getInstance} from './instance';
import {Request} from './Request';
import {Response} from './Response';
import {Database} from './Database';
import {Middleware} from './Middleware';
import {StormError} from './StormError';
import {IConfig} from './IConfig';
import { InternalError } from './InternalError';
import { IRequestResponse } from './IRequestResponse';
 
export class Handler<
        TGetRequest     = any,
        TGetResponse    = any,
        TPostRequest    = any,
        TPostResponse   = any,
        TPutRequest     = any,
        TPutResponse    = any,
        TDeleteRequest  = any,
        TDeleteResponse = any
    >  {
    private _app: Application;
    private _middlewares: Array<Middleware>;
 
    constructor(app: Application) {
        this._app = app;
        this._middlewares = this._initMiddlewares();
    }
 
    protected _initMiddlewares(): Array<Middleware> {
        return [];
    }
 
    public getAccessToken(request: Request): string {
        let config: IConfig = getInstance().getConfig();
        let authHeader: string = config.authentication_header;
        return request.getHeader(authHeader);
    }
 
    public getDB(): Database {
        return this._app.getDB();
    }
 
    private async _executeMiddlewares(request: Request, response: Response): Promise<IRequestResponse> {
        let result: IRequestResponse = {
            request,
            response
        };
 
        try {
            for (let i: number = 0; i < this._middlewares.length; i++) {
                let middleware: Middleware = this._middlewares[i];
                console.log(`executing middleware ${i}`);
                result = await middleware.execute(result.request, result.response);
            }
        }
        catch (ex) {
            getInstance().getLogger().error(ex);
            let error: StormError = null;
            if (!(ex instanceof StormError)) {
                error = new InternalError(ex);
            }
            else {
                error = ex;
            }
            this._onMiddlewareReject(request, response, error);
            return Promise.reject(error);
        }
 
        if (!result) {
            result = {
                request: null,
                response: null
            };
        }
 
        if (!result.request) {
            result.request = request;
        }
 
        if (!result.response) {
            result.response = response;
        }
 
        return Promise.resolve(result);
    }
 
    protected _onMiddlewareReject(request: Request, response: Response, error: StormError) {
        response.error(error);
    }
 
    public get(request: Request<TGetRequest>, response: Response<TGetResponse>): Promise<void> {
        return new Promise((resolve, reject) => {
            this._executeMiddlewares(request, response).then((result: IRequestResponse<TGetRequest, TGetResponse>) => {
                this._get(result.request, result.response);
                resolve();
            }).catch((error: StormError) => {
                this._onMiddlewareReject(request, response, error);
                reject(error);
            });
        });
    }
 
    public put(request: Request<TPutRequest>, response: Response<TPutResponse>): Promise<void> {
        return new Promise((resolve, reject) => {
            this._executeMiddlewares(request, response).then((result: IRequestResponse<TPutRequest, TPutResponse>) => {
                this._put(result.request, result.response);
                resolve();
            }).catch((error: StormError) => {
                this._onMiddlewareReject(request, response, error);
                reject(error);
            });
        });
    }
 
    public post(request: Request<TPostRequest>, response: Response<TPostResponse>): Promise<void> {
        return new Promise((resolve, reject) => {
            this._executeMiddlewares(request, response).then((result: IRequestResponse<TPostRequest, TPostResponse>) => {
                this._post(result.request, result.response);
                resolve();
            }).catch((error: StormError) => {
                this._onMiddlewareReject(request, response, error);
                reject(error);
            });
        });
    }
 
    public delete(request: Request<TDeleteRequest>, response: Response<TDeleteResponse>): Promise<void> {
        return new Promise((resolve, reject) => {
            this._executeMiddlewares(request, response).then((result: IRequestResponse<TDeleteRequest, TDeleteResponse>) => {
                this._delete(result.request, result.response);
                resolve();
            }).catch((error: StormError) => {
                this._onMiddlewareReject(request, response, error);
                reject(error);
            });
        });
    }
 
    protected _get(request: Request<TGetRequest>, response: Response<TGetResponse>): Promise<void> {
        response.setStatus(StatusCode.INTERNAL_NOT_IMPLEMENTED).send();
        return Promise.resolve();
    }
 
    protected _post(request: Request<TPostRequest>, response: Response<TPostResponse>): Promise<void> {
        response.setStatus(StatusCode.INTERNAL_NOT_IMPLEMENTED).send();
        return Promise.resolve();
    }
 
    protected _put(request: Request<TPutRequest>, response: Response<TPutResponse>): Promise<void> {
        response.setStatus(StatusCode.INTERNAL_NOT_IMPLEMENTED).send();
        return Promise.resolve();
    }
 
    protected _delete(request: Request<TDeleteRequest>, response: Response<TDeleteResponse>): Promise<void> {
        response.setStatus(StatusCode.INTERNAL_NOT_IMPLEMENTED).send();
        return Promise.resolve();
    }
}