UNPKG

@mojojs/core

Version:

Real-time web framework

94 lines 2.28 kB
import { stringifyCookie } from './cookie.js'; import { Headers } from '../headers.js'; /** * Server response class. */ export class ServerResponse { constructor(sendResponse) { /** * Response headers. */ this.headers = new Headers(); /** * Response has already been sent. */ this.isSent = false; /** * Response status code. */ this.statusCode = 200; /** * Response status message. */ this.statusMessage = null; this._ctx = undefined; this._sendResponse = sendResponse; } /** * Append header value. */ append(name, value) { this.headers.append(name, value); return this; } /** * Bind context to response. */ bindContext(ctx) { this._ctx = new WeakRef(ctx); } /** * Set response content length. */ length(len) { return this.set('Content-Length', len.toString()); } /** * Send response. */ async send(body) { this.isSent = true; const ctxRef = this._ctx; if (ctxRef === undefined) return; const ctx = ctxRef.deref(); if (ctx === undefined) return; const app = ctx.app; const newBody = await app.hooks.runHook('send:before', ctx, body); if (newBody !== undefined) body = newBody; if (ctx.isSessionActive === true) await app.session.store(ctx, await ctx.session()); this._sendResponse(this, body); } /** * Set HTTP header for response. */ set(name, value) { this.headers.set(name, value); return this; } /** * Set cookie value. */ setCookie(name, value, options) { return this.append('Set-Cookie', stringifyCookie(name, value, options)); } /** * Set response status. */ status(code, message) { this.statusCode = code; if (message !== undefined) this.statusMessage = message; return this; } /** * Set response content type. */ type(type) { return this.set('Content-Type', type); } } //# sourceMappingURL=response.js.map