Skip to content

Commit

Permalink
* core: support for setting global beforeSend callbacks to ajax.
Browse files Browse the repository at this point in the history
  • Loading branch information
catouse committed Sep 12, 2024
1 parent 6aa43a7 commit 088ca31
Showing 1 changed file with 19 additions and 5 deletions.
24 changes: 19 additions & 5 deletions lib/core/src/ajax/ajax.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import {$} from '@zui/core';

import type {AjaxCallbackMap, AjaxCompleteCallback, AjaxErrorCallback, AjaxFormItemValue, AjaxSetting, AjaxSuccessCallback} from './types';
import type {AjaxBeforeSendCallback, AjaxCallbackMap, AjaxCompleteCallback, AjaxErrorCallback, AjaxFormItemValue, AjaxOptionsModifier, AjaxSetting, AjaxSuccessCallback} from './types';

Check warning on line 3 in lib/core/src/ajax/ajax.ts

View workflow job for this annotation

GitHub Actions / deploy

'AjaxOptionsModifier' is defined but never used

function setHeader(headers: HeadersInit, name: string, value: string) {
if (headers instanceof Headers) {
Expand Down Expand Up @@ -72,7 +72,9 @@ export function createFormData(data: string | FormData | URLSearchParams | Recor
return formData;
}

export class Ajax<T> {
export class Ajax<T = unknown> {
static globalBeforeSends: AjaxBeforeSendCallback[] = [];

private declare _timeoutID: number;

private _controller: AbortController;
Expand Down Expand Up @@ -199,9 +201,6 @@ export class Ajax<T> {
...initOptions
} = this.setting;

if (beforeSend?.(initOptions) === false) {
return;
}
if (type) {
initOptions.method = type;
}
Expand All @@ -227,6 +226,21 @@ export class Ajax<T> {
this.abort();
});
}

const beforeSends = [...(this.constructor as typeof Ajax).globalBeforeSends, beforeSend];
for (const callback of beforeSends) {
if (!callback) {
continue;
}
const result = callback.call(this, initOptions);
if (result === false) {
return;
}
if (result) {
Object.assign(initOptions, result);
}
}

if (success) {
this.success(success);
}
Expand Down

0 comments on commit 088ca31

Please sign in to comment.