All files / src/server body-parser.ts

100% Statements 14/14
100% Branches 0/0
100% Functions 7/7
100% Lines 14/14

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                9x       9x   9x       9x 9x   9x 9x     9x 9x 9x   9x     9x         9x           19x  
import HTTP from 'http';
 
import JsonObject from 'http/type/json-object';
 
abstract class BodyParser {
	private request: HTTP.IncomingMessage;
 
	public constructor(request: HTTP.IncomingMessage) {
		this.request = request;
	}
 
	public async parse(): Promise<JsonObject> {
		const buffer = await this.readBuffer();
 
		return this.transformBuffer(buffer);
	}
 
	private readBuffer(): Promise<Buffer> {
		const request = this.getRequest();
		const chunks: Buffer[] = [];
 
		request.on('data', (data) => {
			chunks.push(data);
		});
 
		return new Promise((resolve, reject) => {
			request.on('end', () => {
				const body = Buffer.concat(chunks);
 
				resolve(body);
			});
 
			request.on('error', reject);
		});
	}
 
	private getRequest(): HTTP.IncomingMessage {
		return this.request;
	}
 
	protected abstract transformBuffer(buffer: Buffer): JsonObject;
}
 
export default BodyParser;