@httpc/kit
Version:
httpc toolbox for building function-based API with minimal code and end-to-end type safety
72 lines (71 loc) • 2.34 kB
JavaScript
import { cleanUndefined } from "../utils";
import { ServiceErrorPresets, ServiceError } from "./error";
export const ServiceErrorPreset = new 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");
export function BaseService(presets) {
return !presets
? _BaseService
: class extends _BaseService {
constructor() {
//@ts-expect-error
super(...arguments);
//@ts-ignore
this.__errorPresets = presets || ServiceErrorPreset;
}
};
}
export class _BaseService {
constructor(logger, ...args) {
this.logger = logger;
this.__errorPresets = 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,
...cleanUndefined({
message,
data,
})
};
this.logger.error("%s: %s", info.errorCode, info.message, info.data);
throw new ServiceError(info);
}
}