All files / src endpoint.ts

81.98% Statements 91/111
74.19% Branches 23/31
82.76% Functions 24/29
81.98% Lines 91/111

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 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291      18x     18x 18x   18x 18x 18x   18x 18x 18x 18x 18x 18x                                           37x 37x 37x 37x 37x   37x           28x           106x       27x                   27x       18x 18x   18x 1x     17x                   10x       37x       9x 2x     7x       7x       8x       8x                     28x 28x   28x       28x 21x     7x 7x   7x       28x 28x 28x   28x           28x 28x   28x       37x 37x   37x       52x       28x 2x     26x 2x     24x 12x     12x   12x       24x   24x       26x 26x 26x   26x   26x 26x           9x 6x   3x     9x   9x   9x       26x 26x   26x       26x   26x       7x 7x 7x   7x       18x                                                   7x 7x   7x         7x                 18x  
import HTTP from 'http';
 
import Node from 'type/node';
import HttpError from 'http/error';
import HeaderMap from 'http/type/header-map';
import Repository from 'repository';
import HttpHeader from 'http/enum/header';
import HttpMethod from 'http/enum/method';
import BodyParser from 'server/body-parser';
import StatusCode from 'http/enum/status-code';
import ContentType from 'http/enum/content-type';
import ServerError from 'http/error/server-error';
import UrlParameters from 'http/type/url-parameters';
import JsonBodyParser from 'server/body-parser/json';
import BadRequestError from 'http/error/bad-request';
import parseQuerystring from 'http/utility/parse-querystring';
import UrlEncodedBodyParser from 'server/body-parser/url-encoded';
import getSuccessfulStatusCode from 'http/utility/get-successful-status-code';
import LoadAccountForRequestOperation from 'operation/load-account-for-request';
 
// eslint-disable-next-line @typescript-eslint/ban-types
type AllowedOutputs = string | Buffer | object;
 
abstract class Endpoint<Input, Output extends AllowedOutputs> {
	private request: HTTP.IncomingMessage;
	private response: HTTP.ServerResponse;
	private url_parameters: UrlParameters;
	private query_parameters: Record<string, unknown> | undefined;
	private repository: Repository;
	private status_code: StatusCode;
	private response_headers: HeaderMap;
	private request_body: Input | undefined;
	private account: Node | undefined;
 
	public constructor(
		request: HTTP.IncomingMessage,
		response: HTTP.ServerResponse,
		url_parameters: UrlParameters,
		repository: Repository
	) {
		this.request = request;
		this.response = response;
		this.url_parameters = url_parameters;
		this.repository = repository;
		this.status_code = getSuccessfulStatusCode(request);
 
		this.response_headers = {
			[HttpHeader.CONTENT_TYPE]: this.getResponseContentType()
		};
	}
 
	public serve(): void {
		this.serveInternal()
			.then(this.handleResult.bind(this))
			.catch(this.handleError.bind(this));
	}
 
	protected getRequest(): HTTP.IncomingMessage {
		return this.request;
	}
 
	protected getResponse(): HTTP.ServerResponse {
		return this.response;
	}
 
	protected setHeaderValue(header: HttpHeader, value: string): void {
		const headers = this.getResponseHeaders();
 
		headers[header] = value;
	}
 
	protected getResponseHeaders(): HeaderMap {
		return this.response_headers;
	}
 
	protected getUrlParameter(parameter: string): string {
		const parameters = this.getUrlParameters();
		const value = parameters[parameter];
 
		if (value === undefined) {
			throw new BadRequestError();
		}
 
		return value;
	}
 
	protected getQueryParameter(parameter: string): any {
		const query_parameters = this.getQueryParameters();
 
		return query_parameters[parameter];
	}
 
	protected setStatusCode(status_code: StatusCode): void {
		this.status_code = status_code;
	}
 
	protected getRepository(): Repository {
		return this.repository;
	}
 
	protected getRequestBody(): Input {
		if (this.hasUnparsableMethod()) {
			return {} as Input;
		}
 
		Iif (this.request_body === undefined) {
			throw new Error('Tried to read request body, but it was not set');
		}
 
		return this.request_body;
	}
 
	protected getAccount(): Node {
		Iif (this.account === undefined) {
			throw new Error('Tried to read account, but it was not set');
		}
 
		return this.account;
	}
 
	protected redirectToUrl(url: string): void {
		this.setStatusCode(StatusCode.REDIRECT);
		this.setHeaderValue(HttpHeader.LOCATION, url);
 
		this.sendString('');
	}
 
	private async serveInternal(): Promise<Output | void> {
		await this.parseBody();
		await this.loadAccount();
 
		return this.process();
	}
 
	private async parseBody(): Promise<void> {
		if (this.hasUnparsableMethod()) {
			return Promise.resolve();
		}
 
		const body_parser = this.getBodyParser();
		const body = await body_parser.parse();
 
		this.request_body = body as Input;
	}
 
	private async loadAccount(): Promise<void> {
		const repository = this.getRepository();
		const system_account = await repository.fetchSystemAccount();
		const request = this.getRequest();
 
		const input = {
			request,
			repository,
			account: system_account
		};
 
		const operation = new LoadAccountForRequestOperation(input);
		const account = await operation.perform();
 
		this.account = account;
	}
 
	private hasUnparsableMethod(): boolean {
		const request = this.getRequest();
		const method = request.method;
 
		return method === HttpMethod.GET || method === HttpMethod.OPTIONS;
	}
 
	private getStatusCode(): StatusCode {
		return this.status_code;
	}
 
	private handleResult(result: Output | void): void {
		if (result === undefined) {
			return;
		}
 
		if (result instanceof Buffer) {
			return this.sendData(result);
		}
 
		if (typeof result === 'string') {
			return this.sendString(result);
		}
 
		const serialized_result = JSON.stringify(result);
 
		return this.sendString(serialized_result);
	}
 
	private sendString(result: string): void {
		const buffer = Buffer.from(result);
 
		return this.sendData(buffer);
	}
 
	private sendData(data: Buffer): void {
		const response = this.getResponse();
		const status_code = this.getStatusCode();
		const headers = this.getResponseHeaders();
 
		this.logCompletion();
 
		response.writeHead(status_code, headers);
		response.end(data);
	}
 
	private handleError(error: Error): void {
		let http_error;
 
		if (error instanceof HttpError) {
			http_error = error;
		} else {
			http_error = new ServerError(error.message);
		}
 
		this.setStatusCode(http_error.status_code);
 
		const serialized_error = this.serializeError(http_error);
 
		return this.handleResult(serialized_error);
	}
 
	private logCompletion(): void {
		const url = this.getRequestUrl();
		const status_code = this.getStatusCode();
 
		console.log(`[${status_code}] ${url}`);
	}
 
	private getRequestUrl(): string {
		const request = this.getRequest();
 
		return request.url || '/';
	}
 
	private getRequestContentType(): ContentType {
		const request = this.getRequest();
		const header_value = request.headers[HttpHeader.CONTENT_TYPE];
		const content_type = header_value as ContentType;
 
		return content_type || ContentType.JSON;
	}
 
	private getUrlParameters(): UrlParameters {
		return this.url_parameters;
	}
 
	private getQueryParameters(): Record<string, unknown> {
		if (this.query_parameters === undefined) {
			this.query_parameters = this.parseQueryParameters();
		}
 
		return this.query_parameters;
	}
 
	private parseQueryParameters(): Record<string, unknown> {
		const url = this.getRequestUrl();
		const query_index = url.indexOf('?');
 
		if (query_index === -1) {
			return {};
		}
 
		const suffix = url.slice(query_index + 1);
		const result = parseQuerystring(suffix);
 
		return result as Record<string, unknown>;
	}
 
	private getBodyParser(): BodyParser {
		const request = this.getRequest();
		const content_type = this.getRequestContentType();
 
		switch (content_type) {
			case ContentType.URL_ENCODED:
				return new UrlEncodedBodyParser(request);
			case ContentType.JSON:
			default:
				return new JsonBodyParser(request);
		}
	}
 
	protected abstract process(): Promise<Output | void>;
	protected abstract getResponseContentType(): ContentType;
	protected abstract serializeError(error: HttpError): Output;
}
 
export default Endpoint;