UNPKG

@tsed/platform-koa

Version:
92 lines (91 loc) 2.03 kB
import { PlatformResponse } from "@tsed/platform-http"; /** * @platform * @koa */ export class PlatformKoaResponse extends PlatformResponse { get ctx() { return this.raw.ctx; } get statusCode() { return this.raw.status; } get locals() { return this.ctx.state; } /** * Return the Node.js response object */ getRes() { return this.raw.res; } hasStatus() { // KOA set 404 by default return this.statusCode !== 404; } /** * Sets the HTTP status for the response. * * @param status */ status(status) { this.raw.status = status; return this; } /** * Set `Content-Type` response header with `type` through `mime.lookup()` * when it does not contain "/", or set the Content-Type to `type` otherwise. * * Examples: * * res.type('.html'); * res.type('html'); * res.type('json'); * res.type('application/json'); * res.type('png'); */ contentType(contentType) { this.raw.type = contentType; return this; } getHeaders() { return this.raw.headers; } stream(data) { this.raw.body = data; return this; } getBody() { return this.raw.body; } cookie(name, value, opts) { if (value === null) { this.ctx.cookies.set(name); } else { this.ctx.cookies.set(name, value, opts); } return this; } json(data) { this.end(data); return this; } buffer(data) { this.end(data); return this; } end(data) { if ([301, 302, 303, 307, 308].includes(this.statusCode)) { if (this.request.method === "HEAD") { this.getRes().end(); } else { this.getRes().end(data); } } else { this.raw.body = data; } } }