UNPKG

stackpress

Version:

Incept is a content management framework.

90 lines (89 loc) 2.35 kB
import Status from '@stackpress/lib/Status'; import Exception from '@stackpress/lib/Exception'; import { nest, isObject } from '@stackpress/lib/Nest'; export default class Response { errors; _code = 0; _error; _results; _stack; _status = ''; _total = 0; get code() { return this._code; } get error() { return this._error; } get results() { if (isObject(this._results)) { return Object.freeze(this._results); } else if (Array.isArray(this._results)) { return Array.from(this._results); } return this._results; } get stack() { return this._stack; } get status() { return this._status; } get total() { return this._total; } constructor(response) { const { code, status, error, errors, stack, results, total } = response; if (code) { this._code = code; } if (status) { this._status = status; } else if (this._code) { this._status = Status.get(this._code)?.status || 'Unknown Status'; } if (error) { this._error = error; } this.errors = nest(); if (errors) { this.errors.set(errors); } if (stack) { this._stack = stack; } if (results) { this._results = results; } if (total) { this._total = total; } } toException(message) { const error = message || this._error || 'Unknown Error'; const exception = Exception.for(error) .withCode(this._code) .withErrors(this.errors()); if (this._stack) { let stack = `Response: ${error}\n`; stack += this._stack.map(trace => ` at ${trace.method} (` + `${trace.file}:${trace.line}:${trace.char}` + `)`).join('\n'); exception.stack = stack; } return exception; } toStatusResponse() { return { code: this._code, status: this._status, error: this._error, errors: this.errors(), stack: this._stack, results: this.results, total: this._total }; } }