All files ServiceProvider.ts

94.44% Statements 51/54
91.67% Branches 11/12
90% Functions 18/20
94.44% Lines 51/54

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      1x 1x 1x   1x   1x       1x                     1x       5x       4x       5x       1x       5x       4x   4x 1x 2x 1x     1x         4x       4x 4x               4x 4x   4x 4x     4x 4x 4x 4x 4x 4x   4x   4x 4x 4x   4x 2x 2x           4x 4x 4x     4x           4x 3x 3x     4x         4x       1x       1x       1x       1x      
 
import {Application} from './Application';
import {IServiceHeaders} from './IServiceHeaders';
import {HTTPMethod} from './HTTPMethod';
import {ServiceResponse} from './ServiceResponse';
import * as http from 'http';
 
const NO_DATA: string = `|${0x0}|`;
 
export abstract class ServiceProvider {
    private _app: Application;
 
    public constructor(app: Application) {
        this._app = app;
    }
 
    protected abstract _getBase(): string;
    protected abstract _getPort(): number;
 
    protected _getApp(): Application {
        return this._app;
    }
 
    public getApp(): Application {
        return this._app;
    }
 
    protected _getDomain(): string {
        return '127.0.0.1';
    }
 
    private _getSecret(): string {
        return this._app.getConfig().backend_authentication_secret;
    }
 
    public urlSuffix(): string {
        return '/';
    }
 
    protected _getProtocol(): string {
        return 'http';
    }
 
    public getVersion(): string {
        return 'v1';
    }
 
    protected _createURL(url: string, queryParams?: any): string {
        let queryString: string = '';
 
        if (queryParams) {
            for (let i in queryParams) {
                if (queryString === '') {
                    queryString = '?' + i + '=' + queryParams[i];
                }
                else {
                    queryString += '&' + i + '=' + queryParams[i];
                }
            }
        }
 
        return `/api/${this._getBase()}/${this.getVersion()}/${url}${this.urlSuffix()}${queryString}`;
    }
 
    public request(method: HTTPMethod, url: string, accessToken: string, data: any, headers?: IServiceHeaders, additionalOptions?: any): Promise<ServiceResponse> {
        return new Promise<ServiceResponse>((resolve, reject) => {
            let httpOpts: http.RequestOptions = {
                port: this._getPort(),
                hostname: `${this._getDomain()}`,
                method: method,
                path: url,
                headers: headers || {}
            };
 
            httpOpts.headers[this._app.getConfig().authentication_header] = accessToken;
            httpOpts.headers[this._app.getConfig().backend_authentication_header] = this._getSecret();
            
            Eif (!httpOpts.headers['Content-Type']) {
                httpOpts.headers['Content-Type'] = 'application/json';
            }
 
            this._app.getLogger().trace(`ServiceProvider Request`);
            this._app.getLogger().trace(`METHOD: ${httpOpts.method}`);
            this._app.getLogger().trace(`HOSTNAME: ${httpOpts.hostname}`);
            this._app.getLogger().trace(`PORT: ${httpOpts.port}`);
            this._app.getLogger().trace(`PATH: ${httpOpts.path}`);
            this._app.getLogger().trace(`HEADERS: ${JSON.stringify(httpOpts.headers)}`);
            
            let responseData: Buffer = Buffer.from('');
 
            let request: http.ClientRequest = http.request(httpOpts, (response: http.IncomingMessage) => {
                this._app.getLogger().trace(`ServiceProvider Response Status: ${response.statusCode}`);
                this._app.getLogger().trace(`ServiceProvider Response Headers: ${JSON.stringify(response.headers)}`);
 
                response.on('data', (chunk: Buffer) => {
                    this._app.getLogger().trace(`ServiceProvider Received Chunk: ${chunk}`);
                    responseData = Buffer.concat([
                        responseData,
                        chunk
                    ]);
                });
 
                response.on('end', () => {
                    this._app.getLogger().trace(`ServiceProvider request has completed.`);
                    resolve(new ServiceResponse(responseData, response));
                });
 
                response.on('error', (e: Error) => {
                    this._app.getLogger().error(e.message);
                    reject(e);
                });
            });
 
            if (data && data !== NO_DATA) {
                data = JSON.stringify(data);
                request.write(data);
            }
 
            this._sendRequest(request);
        });
    }
 
    private _sendRequest(request: http.ClientRequest): void {
        request.end();
    }
 
    public get(url: string, accessToken: string, data?: any, headers?: IServiceHeaders, additionalOptions?: any): Promise<ServiceResponse> {
        return this.request(HTTPMethod.GET, this._createURL(url, data), accessToken, NO_DATA, headers, additionalOptions);
    }
 
    public post(url: string, accessToken: string, data?: any, headers?: IServiceHeaders, additionalOptions?: any): Promise<ServiceResponse> {
        return this.request(HTTPMethod.POST, this._createURL(url), accessToken, data, headers, additionalOptions);
    }
 
    public put(url: string, accessToken: string, data?: any, headers?: IServiceHeaders, additionalOptions?: any): Promise<ServiceResponse> {
        return this.request(HTTPMethod.PUT, this._createURL(url), accessToken, data, headers, additionalOptions);
    }
 
    public delete(url: string, accessToken: string, data?: any, headers?: IServiceHeaders, additionalOptions?: any): Promise<ServiceResponse> {
        return this.request(HTTPMethod.DELETE, this._createURL(url), accessToken, data, headers, additionalOptions);
    }
}