UNPKG

abi.js

Version:

[![typescript-icon]][typescript-link] [![license-icon]][license-link] [![status-icon]][status-link] [![ci-icon]][ci-link] [![twitter-icon]][twitter-link]

67 lines (66 loc) 1.83 kB
export class Context { constructor(request, logger = console) { Object.defineProperty(this, "request", { enumerable: true, configurable: true, writable: true, value: request }); Object.defineProperty(this, "logger", { enumerable: true, configurable: true, writable: true, value: logger }); } get url() { return new URL(this.request.url); } get method() { return this.request.method; } get pathname() { return decodeURIComponent(this.url.pathname); } respond(body, headers, status, statusText) { return new Response(body, { status, statusText, headers }); } redirect(location, status) { return Response.redirect(location, status); } json(arg1, arg2) { if (arg1 === undefined && arg2 === undefined) { return this.request.json(); } return new Response(JSON.stringify(arg1), arg2); } text(body, init) { return new Response(body, init); } render(result) { if (result instanceof Response) { return result; } if (typeof result === 'string') { return this.text(result); } if (typeof result === 'number') { return this.respond(null, {}, result); } return this.json(result); } abort(code = 500, message, headers) { const err = `Error ${code}${message ? `: ${message}` : ''}`; this.logger.error(err); return this.respond(err, headers, code); } log(...args) { this.logger.log(...args); } warn(...args) { this.logger.warn(...args); } error(...args) { this.logger.error(...args); } }