UNPKG

@zerooneit/expressive-tea

Version:
71 lines (70 loc) 3.28 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ProxyProperty = exports.ProxyOption = exports.ProxyContainer = void 0; const MetaData_1 = require("../classes/MetaData"); const httpProxy = require("express-http-proxy"); const object_helper_1 = require("../helpers/object-helper"); const lodash_1 = require("lodash"); const RequestExceptions_1 = require("../exceptions/RequestExceptions"); const constants_1 = require("../libs/constants"); const NON_ASYNC_METHODS = ['host']; function ProxyContainer(source, targetUrl) { return (ProxyContainerClass) => { class ExpressiveTeaProxy extends ProxyContainerClass { constructor(...args) { super(...args); this.source = source; this.target = targetUrl; const options = {}; const host = MetaData_1.default.get(constants_1.PROXY_SETTING_KEY, this, constants_1.PROXY_METHODS.HOST); for (const value of Object.values(constants_1.PROXY_METHODS)) { if (value !== constants_1.PROXY_METHODS.HOST) { options[value] = MetaData_1.default.get(constants_1.PROXY_SETTING_KEY, this, value); } } for (const value of Object.values(constants_1.PROXY_PROPERTIES)) { const key = MetaData_1.default.get(constants_1.PROXY_SETTING_KEY, this, value); if (!(0, lodash_1.isUndefined)(key)) { // @ts-ignore:next-line options[value] = this[key]; } } this.proxyHandler = httpProxy(host ? host.value.bind(this) : this.target); } __register(server) { const proxyMetadata = MetaData_1.default.get(constants_1.PROXY_SETTING_KEY, (0, object_helper_1.getClass)(this)); console.info(`[PROXY - ${proxyMetadata.name}] ${this.source} -> ${this.target}`); server.use(this.source, this.proxyHandler); } } ; const settings = { source, targetUrl, name: ProxyContainerClass.name }; MetaData_1.default.set(constants_1.PROXY_SETTING_KEY, settings, ProxyContainerClass); return ExpressiveTeaProxy; }; } exports.ProxyContainer = ProxyContainer; function ProxyOption(option) { return (target, propertyKey, descriptor) => { if (NON_ASYNC_METHODS.includes(option) && (0, object_helper_1.isAsyncFunction)(descriptor.value)) { throw new RequestExceptions_1.GenericRequestException(`${String(propertyKey)} must not be declared as Async Function.`); } MetaData_1.default.set(constants_1.PROXY_SETTING_KEY, descriptor, target, option); }; } exports.ProxyOption = ProxyOption; function ProxyProperty(option, value) { return (target, propertyKey) => { MetaData_1.default.set(constants_1.PROXY_SETTING_KEY, propertyKey, target, option); let currentValue = target[propertyKey]; Object.defineProperty(target, propertyKey, { get: () => value, set: () => { currentValue = value; } }); }; } exports.ProxyProperty = ProxyProperty;