UNPKG

@canlooks/ajax

Version:
89 lines (88 loc) 3.02 kB
import { ajax } from './ajaxInstance'; import { mergeConfig } from './util'; export class Service { config; ajax; constructor(config) { this.config = config; this.ajax = ajax.extend(config); } /** * ------------------------------------------------------------------ * alias without body */ get(url, config = {}) { return this.ajax(mergeConfig(config, { url, method: 'GET' })); } delete(url, config = {}) { return this.ajax(mergeConfig(config, { url, method: 'DELETE' })); } head(url, config = {}) { return this.ajax(mergeConfig(config, { url, method: 'HEAD' })); } options(url, config = {}) { return this.ajax(mergeConfig(config, { url, method: 'OPTIONS' })); } /** * ------------------------------------------------------------------ * alias with body */ post(url, body, config = {}) { return this.ajax(mergeConfig(config, { url, body, method: 'POST' })); } put(url, body, config = {}) { return this.ajax(mergeConfig(config, { url, body, method: 'PUT' })); } patch(url, body, config = {}) { return this.ajax(mergeConfig(config, { url, body, method: 'PATCH' })); } } export function Module(a) { const fn = (config = {}) => (target) => { return { [target.name]: class extends target { constructor(config1 = {}) { super(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(); export function BeforeRequest(a, b, c) { const fn = (prototype, propertyKey, descriptor) => { defineMethodDecorator(prototype, propertyKey, prototype_beforeRequestPropertySet); }; return c ? fn(a, b, c) : fn; } export 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'); }