react-antd-admin-panel
Version:
Modern TypeScript-first React admin panel builder with Ant Design 6
165 lines • 3.92 kB
JavaScript
import axios from 'axios';
/**
* Get Model - Type-safe HTTP GET request builder
* @template T - Response data type
*/
export class Get {
_target;
_params = {};
_headers = {};
_config = {};
_hooks = {};
_abortController;
static _axios = axios.create();
/**
* Set the request target URL
*/
target(url) {
this._target = url;
return this;
}
/**
* Set URL parameters
*/
params(params) {
this._params = { ...this._params, ...params };
return this;
}
/**
* Set a single URL parameter
*/
param(key, value) {
this._params[key] = value;
return this;
}
/**
* Set request headers
*/
headers(headers) {
this._headers = { ...this._headers, ...headers };
return this;
}
/**
* Set a single header
*/
header(key, value) {
this._headers[key] = value;
return this;
}
/**
* Set additional request configuration
*/
config(config) {
this._config = { ...this._config, ...config };
return this;
}
/**
* Hook called before the request is sent
*/
onBefore(callback) {
this._hooks.onBefore = callback;
return this;
}
/**
* Hook called when request succeeds
*/
onThen(callback) {
this._hooks.onThen = callback;
return this;
}
/**
* Hook called when request fails
*/
onCatch(callback) {
this._hooks.onCatch = callback;
return this;
}
/**
* Hook called after request completes (success or failure)
*/
onFinally(callback) {
this._hooks.onFinally = callback;
return this;
}
/**
* Execute the GET request
*/
async execute() {
if (!this._target) {
throw new Error('Target URL is required');
}
this._abortController = new AbortController();
let config = {
method: 'GET',
url: this._target,
params: this._params,
headers: this._headers,
signal: this._abortController.signal,
...this._config,
};
try {
// Apply onBefore hook
if (this._hooks.onBefore) {
config = await this._hooks.onBefore(config);
}
const response = await Get._axios.request(config);
const data = response.data;
// Apply onThen hook
if (this._hooks.onThen) {
await this._hooks.onThen(data);
}
return data;
}
catch (error) {
// Apply onCatch hook
if (this._hooks.onCatch) {
return this._hooks.onCatch(error);
}
throw error;
}
finally {
// Apply onFinally hook
if (this._hooks.onFinally) {
await this._hooks.onFinally();
}
}
}
/**
* Cancel the request
*/
cancel(message) {
if (this._abortController) {
this._abortController.abort(message);
}
}
/**
* Set global axios instance
*/
static setAxios(instance) {
Get._axios = instance;
}
/**
* Get the current axios instance
*/
static getAxios() {
return Get._axios;
}
/**
* Configure global defaults
*/
static configure(config) {
if (config.baseURL) {
Get._axios.defaults.baseURL = config.baseURL;
}
if (config.timeout) {
Get._axios.defaults.timeout = config.timeout;
}
if (config.headers) {
Get._axios.defaults.headers.common = {
...Get._axios.defaults.headers.common,
...config.headers,
};
}
}
}
//# sourceMappingURL=Get.js.map