UNPKG

@canlooks/ajax

Version:

A modular request management tool

85 lines (84 loc) 3.16 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Service = void 0; exports.Config = Config; exports.RequestInterceptor = RequestInterceptor; exports.ResponseInterceptor = ResponseInterceptor; const ajaxInstance_1 = require("./ajaxInstance"); const utility_1 = require("./utility"); class Service { static config = {}; static ajax = ajaxInstance_1.ajax.create(this.config); static get resolvedConfig() { return this.ajax.config; } /** * ------------------------------------------------------------------ * alias without body */ static get(url, config = {}) { return this.ajax((0, utility_1.mergeConfig)(config, { url, method: 'GET' })); } static delete(url, config = {}) { return this.ajax((0, utility_1.mergeConfig)(config, { url, method: 'DELETE' })); } static head(url, config = {}) { return this.ajax((0, utility_1.mergeConfig)(config, { url, method: 'HEAD' })); } static options(url, config = {}) { return this.ajax((0, utility_1.mergeConfig)(config, { url, method: 'OPTIONS' })); } /** * ------------------------------------------------------------------ * alias with body */ static post(url, body, config = {}) { return this.ajax((0, utility_1.mergeConfig)(config, { url, body, method: 'POST' })); } static put(url, body, config = {}) { return this.ajax((0, utility_1.mergeConfig)(config, { url, body, method: 'PUT' })); } static patch(url, body, config = {}) { return this.ajax((0, utility_1.mergeConfig)(config, { url, body, method: 'PATCH' })); } } exports.Service = Service; function Config(config) { return (target) => { target.config = config; target.ajax = target.ajax.create(config); const requestInterceptors = target_requestInterceptors.get(target); if (requestInterceptors) { for (const interceptor of requestInterceptors) { target.ajax.requestInterceptor.add(interceptor.bind(target)); } } const responseInterceptors = target_responseInterceptors.get(target); if (responseInterceptors) { for (const interceptor of responseInterceptors) { target.ajax.responseInterceptor.add(interceptor.bind(target)); } } }; } const target_requestInterceptors = new WeakMap(); function RequestInterceptor(a, b, c) { const fn = () => (target, propertyKey, descriptor) => { setInternalMap(target_requestInterceptors, target, descriptor.value); }; return c ? fn()(a, b, c) : fn(); } const target_responseInterceptors = new WeakMap(); function ResponseInterceptor(a, b, c) { const fn = () => (target, propertyKey, descriptor) => { setInternalMap(target_responseInterceptors, target, descriptor.value); }; return c ? fn()(a, b, c) : fn(); } function setInternalMap(map, target, value) { if (typeof value === 'function') { const interceptors = map.get(target) || new Set(); interceptors.add(value); map.set(target, interceptors); } }