UNPKG

@httpc/kit

Version:

httpc toolbox for building function-based API with minimal code and end-to-end type safety

77 lines (76 loc) 2.57 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports._BaseService = exports.BaseService = exports.ServiceErrorPreset = void 0; const utils_1 = require("../utils"); const error_1 = require("./error"); exports.ServiceErrorPreset = new error_1.ServiceErrorPresets() .add("invalid_param", { status: 400 }) .add("unauthorized", { status: 401 }) .add("forbidden", { status: 403 }) .add("not_allowed", { status: 422 }) .add("invalid_state") .add("not_found") .add("misconfiguration") .add("not_supported") .add("processing_error"); function BaseService(presets) { return !presets ? _BaseService : class extends _BaseService { constructor() { //@ts-expect-error super(...arguments); //@ts-ignore this.__errorPresets = presets || exports.ServiceErrorPreset; } }; } exports.BaseService = BaseService; class _BaseService { constructor(logger, ...args) { this.logger = logger; this.__errorPresets = exports.ServiceErrorPreset; this.__inTransaction = false; this._setArguments([...arguments]); logger.debug("Created"); } _setArguments(args) { this.__arguments = args.slice(); } inTransaction(data) { if (this.__inTransaction) { return this; } function activate(arg) { return (arg && typeof arg === "object" && typeof arg.inTransaction === "function") ? arg.inTransaction?.(data) || arg : arg; } const ctor = this.constructor; const args = this.__arguments.map(x => Array.isArray(x) ? x.map(activate) : activate(x)); const instance = new ctor(...args); instance.__inTransaction = true; return instance; } _raiseError(error, message, data) { if (typeof message === "object") { data = message; message = undefined; } const preset = this.__errorPresets?.get(error); const info = { status: 500, ...preset, errorCode: error, ...(0, utils_1.cleanUndefined)({ message, data, }) }; this.logger.error("%s: %s", info.errorCode, info.message, info.data); throw new error_1.ServiceError(info); } } exports._BaseService = _BaseService;