@canlooks/ajax
Version:
78 lines (77 loc) • 2.81 kB
JavaScript
import { ajax } from './ajaxInstance.js';
import { mergeConfig } from './utility.js';
export class Service {
static config = {};
static ajax = ajax.create(this.config);
static get resolvedConfig() {
return this.ajax.config;
}
/**
* ------------------------------------------------------------------
* alias without body
*/
static get(url, config = {}) {
return this.ajax(mergeConfig(config, { url, method: 'GET' }));
}
static delete(url, config = {}) {
return this.ajax(mergeConfig(config, { url, method: 'DELETE' }));
}
static head(url, config = {}) {
return this.ajax(mergeConfig(config, { url, method: 'HEAD' }));
}
static options(url, config = {}) {
return this.ajax(mergeConfig(config, { url, method: 'OPTIONS' }));
}
/**
* ------------------------------------------------------------------
* alias with body
*/
static post(url, body, config = {}) {
return this.ajax(mergeConfig(config, { url, body, method: 'POST' }));
}
static put(url, body, config = {}) {
return this.ajax(mergeConfig(config, { url, body, method: 'PUT' }));
}
static patch(url, body, config = {}) {
return this.ajax(mergeConfig(config, { url, body, method: 'PATCH' }));
}
}
export 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();
export 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();
export 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);
}
}