UNPKG

@darlean/webservice

Version:

Webservice library for Darlean

85 lines (84 loc) 2.6 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Response = exports.Request = void 0; class Request { constructor(request) { this.request = request; } getHeader(header) { return this.request.headers?.[header.toLowerCase()]; } getRawBody() { return this.request.body; } getTextBody() { return this.request.body?.toString('utf-8'); } response() { return new Response(this.request); } } exports.Request = Request; class Response { constructor(request) { this.headersSent = false; this.request = request; this.response = { statusCode: 200, statusMessage: 'OK', headers: {} }; this.bodyParts = []; } async endWithStatusCode(statusCode, statusMessage) { if (this.headersSent) { throw new Error('Headers are already sent'); } this.response.statusCode = statusCode; this.response.statusMessage = statusMessage; return await this.end(); } setStatusCode(statusCode, statusMessage) { if (this.headersSent) { throw new Error('Headers are already sent'); } this.response.statusCode = statusCode; this.response.statusMessage = statusMessage; } setHeader(header, value) { if (this.headersSent) { throw new Error('Headers are already sent'); } if (this.response.headers) { this.response.headers[header] = value; } } setCookie(value) { if (this.headersSent) { throw new Error('Headers are already sent'); } if (!this.response.cookies) { this.response.cookies = []; } if (this.response.cookies) { this.response.cookies.push(value); } } async push(buffer) { this.headersSent = true; // A future implementation may start pushing body parts directly to the // webserver when the body size is larger than a certain threshold this.bodyParts.push(buffer); } async pushText(contentType, value) { if (this.response.headers?.['content-type'] !== value) { this.setHeader('content-type', contentType); } await this.push(Buffer.from(value, 'utf-8')); } async end() { this.response.body = Buffer.concat(this.bodyParts); return this.response; } } exports.Response = Response;