UNPKG

@canlooks/ajax

Version:
96 lines (95 loc) 3.34 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Service = void 0; exports.Module = Module; exports.BeforeRequest = BeforeRequest; exports.BeforeResponse = BeforeResponse; const ajaxInstance_1 = require("./ajaxInstance"); const util_1 = require("./util"); class Service { config; ajax; constructor(config) { this.config = config; this.ajax = ajaxInstance_1.ajax.extend(config); } /** * ------------------------------------------------------------------ * alias without body */ get(url, config = {}) { return this.ajax((0, util_1.mergeConfig)(config, { url, method: 'GET' })); } delete(url, config = {}) { return this.ajax((0, util_1.mergeConfig)(config, { url, method: 'DELETE' })); } head(url, config = {}) { return this.ajax((0, util_1.mergeConfig)(config, { url, method: 'HEAD' })); } options(url, config = {}) { return this.ajax((0, util_1.mergeConfig)(config, { url, method: 'OPTIONS' })); } /** * ------------------------------------------------------------------ * alias with body */ post(url, body, config = {}) { return this.ajax((0, util_1.mergeConfig)(config, { url, body, method: 'POST' })); } put(url, body, config = {}) { return this.ajax((0, util_1.mergeConfig)(config, { url, body, method: 'PUT' })); } patch(url, body, config = {}) { return this.ajax((0, util_1.mergeConfig)(config, { url, body, method: 'PATCH' })); } } exports.Service = Service; function Module(a) { const fn = (config = {}) => (target) => { return { [target.name]: class extends target { constructor(config1 = {}) { super((0, util_1.mergeConfig)(config, config1)); setInterceptors(target.prototype, this); } } }[target.name]; }; return typeof a === 'function' ? fn()(a) : fn(a); } /** * ------------------------------------------------------------------ * 方法修饰器 */ const prototype_beforeRequestPropertySet = new WeakMap(); const prototype_beforeResponsePropertySet = new WeakMap(); function BeforeRequest(a, b, c) { const fn = (prototype, propertyKey, descriptor) => { defineMethodDecorator(prototype, propertyKey, prototype_beforeRequestPropertySet); }; return c ? fn(a, b, c) : fn; } function BeforeResponse(a, b, c) { const fn = (prototype, propertyKey, descriptor) => { defineMethodDecorator(prototype, propertyKey, prototype_beforeResponsePropertySet); }; return c ? fn(a, b, c) : fn; } function defineMethodDecorator(prototype, propertyKey, map) { const propertySet = map.get(prototype) || new Set(); propertySet.add(propertyKey); map.set(prototype, propertySet); } function setInterceptors(prototype, context) { const fn = (type) => { const map = type === 'beforeRequest' ? prototype_beforeRequestPropertySet : prototype_beforeResponsePropertySet; const propertySet = map.get(prototype); if (propertySet) { for (const property of propertySet) { context.ajax[type].add(context[property].bind(context)); } } }; fn('beforeRequest'); fn('beforeResponse'); }