Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feature: useSSE() basic implement #60

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions src/functions/sendRequest.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { filterItem, map, objectKeys } from '@/helper';
import { undefinedValue } from '@/helper/variables';
import { Arg } from 'alova';

/**
* 构建完整的url
* @param base baseURL
* @param url 路径
* @param params url参数
* @returns 完整的url
*/
export const buildCompletedURL = (baseURL: string, url: string, params: Arg) => {
// baseURL如果以/结尾,则去掉/
baseURL = baseURL.endsWith('/') ? baseURL.slice(0, -1) : baseURL;
// 如果不是/或http协议开头的,则需要添加/
url = url.match(/^(\/|https?:\/\/)/) ? url : `/${url}`;

const completeURL = baseURL + url;

// 将params对象转换为get字符串
// 过滤掉值为undefined的
const paramsStr = map(
filterItem(objectKeys(params), key => params[key] !== undefinedValue),
key => `${key}=${params[key]}`
).join('&');
// 将get参数拼接到url后面,注意url可能已存在参数
return paramsStr
? +completeURL.includes('?')
? `${completeURL}&${paramsStr}`
: `${completeURL}?${paramsStr}`
: completeURL;
};
48 changes: 47 additions & 1 deletion src/helper/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { CacheExpire, LocalCacheConfig, Method } from 'alova';
import { AlovaMethodHandler, CacheExpire, LocalCacheConfig, Method } from 'alova';
import { BackoffPolicy } from '~/typings/general';
import { ObjectCls, PromiseCls, StringCls, falseValue, nullValue, trueValue, undefinedValue } from './variables';

Expand Down Expand Up @@ -320,3 +320,49 @@ export const delayWithBackoff = (backoff: BackoffPolicy, retryTimes: number) =>
}
return retryDelayFinally;
};
/**
* 获取请求方法对象
* @param methodHandler 请求方法句柄
* @param args 方法调用参数
* @returns 请求方法对象
*/
export const getHandlerMethod = <S, E, R, T, RC, RE, RH>(
methodHandler: Method<S, E, R, T, RC, RE, RH> | AlovaMethodHandler<S, E, R, T, RC, RE, RH>,
args: any[] = []
) => {
const methodInstance = isFn(methodHandler) ? methodHandler(...args) : methodHandler;
createAssert('scene')(
instanceOf(methodInstance, Method),
'hook handler must be a method instance or a function that returns method instance'
);
return methodInstance;
};

type AnyFn = (...args: any[]) => any;
export function useCallback<Fn extends AnyFn = AnyFn>(onCallbackChange?: (callbacks: Fn[]) => void) {
let callbacks: Fn[] = [];

const setCallback = (fn: Fn) => {
if (!callbacks.includes(fn)) {
callbacks.push(fn);
onCallbackChange && onCallbackChange(callbacks);
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

我提下我的见解,如果我的话,我会把onCallbackChange接收处默认为noop,这样就不需要多个地方判断onCallbackChange是否有值,当然你这样写也没啥问题。

// 返回取消注册函数
return () => {
callbacks = filterItem(callbacks, e => e !== fn);
onCallbackChange && onCallbackChange(callbacks);
};
};

const triggerCallback = (...args: any[]) => {
if (callbacks) {
return forEach(callbacks, fn => fn(args));
}
};
Comment on lines +358 to +360
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

这个判断好像无效,因为按你写的callbacks至少都会是一个空数组


const removeAllCallback = () => {
callbacks = [];
};

return [setCallback, triggerCallback as Fn, removeAllCallback] as const;
}
128 changes: 128 additions & 0 deletions src/hooks/useSSE.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
import { T$, T$$, TonMounted$, Tupd$, Twatch$, T_$, T_exp$, TonUnmounted$ } from '@/framework/type';
import { AlovaMethodHandler, Method, useRequest } from 'alova';
import { getConfig, getHandlerMethod, useCallback } from '@/helper';
import { buildCompletedURL } from '@/functions/sendRequest';
import {
AlovaSSEErrorEvent,
AlovaSSEEvent,
AlovaSSEMessageEvent,
SSEHookConfig,
SSEHookReadyState,
SSEOn,
SSEOnErrorTrigger,
SSEOnMessageTrigger,
SSEOnOpenTrigger
} from '~/typings/general';

// !! interceptByGlobalResponded 参数 尚未实现

export default <S, E, R, T, RC, RE, RH>(
handler: Method<S, E, R, T, RC, RE, RH> | AlovaMethodHandler<S, E, R, T, RC, RE, RH>,
config: SSEHookConfig = {},
$: T$,
$$: T$$,
_$: T_$,
_exp$: T_exp$,
upd$: Tupd$,
watch$: Twatch$,
onMounted$: TonMounted$,
onUnmounted$: TonUnmounted$
// useFlag$: TuseFlag$,
// useMemorizedCallback$: TuseMemorizedCallback$
) => {
// SSE 不需要传参(吧?)
const methodInstance = getHandlerMethod(handler);
const { baseURL, url } = methodInstance;
const { params, transformData, headers } = getConfig(methodInstance);

const fullURL = buildCompletedURL(baseURL, url, params);
const eventSource = new EventSource(fullURL, { withCredentials: config.withCredentials });

const { data, update } = useRequest(handler, config);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

这里为什么要通过useRequest来创建data,是不是直接$(config.initialData)就可以了

const readyState = $<SSEHookReadyState>(SSEHookReadyState.CONNECTING);

// type: eventname & useCallback()
const eventMap: Map<string, ReturnType<typeof useCallback>> = new Map();
const [onOpen, triggerOnOpen, offOpen] = useCallback<SSEOnOpenTrigger>();
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

我觉得这个useCallback非常棒

const [onMessage, triggerOnMessage, offMessage] = useCallback<SSEOnMessageTrigger<any>>();
const [onError, triggerOnError, offError] = useCallback<SSEOnErrorTrigger>();

const dataHandler = (data: any) => {
const transformedData = transformData ? transformData(data, (headers || {}) as RH) : data;
update({ data: transformedData });
return data;
};

// 将 SourceEvent 产生的事件变为 AlovaSSEHook 的事件
const createSSEEvent = (eventName: string, event: MessageEvent<any> | Event) => {
if (eventName === 'open') {
return {
method: methodInstance,
eventSource
} as AlovaSSEEvent;
}
if (eventName === 'error') {
return {
method: methodInstance,
eventSource,
error: new Error('sse error')
} as AlovaSSEErrorEvent;
}

// 其余名称的事件都是(类)message 的事件,data 交给 dataHandler 处理
return {
method: methodInstance,
eventSource,
data: dataHandler((event as MessageEvent).data)
} as AlovaSSEMessageEvent<any>;
};
Comment on lines +57 to +78
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

可能你没注意到createHookEvent这个文件,应该是可以使用这个函数,然后调整下对SSE的事件对象的支持能用上。


const on: SSEOn = (eventName, handler) => {
if (!eventMap.has(eventName)) {
const useCallbackObject = useCallback<(event: AlovaSSEEvent) => void>(callbacks => {
if (callbacks.length === 0) {
eventSource.removeEventListener(eventName, useCallbackObject[1] as any);
eventMap.delete(eventName);
}
});

const trigger = useCallbackObject[1];
eventMap.set(eventName, useCallbackObject);
eventSource.addEventListener(eventName, event => {
trigger(createSSEEvent(eventName, event));
});
}

const [onEvent] = eventMap.get(eventName)!;

Check warning on line 96 in src/hooks/useSSE.ts

View workflow job for this annotation

GitHub Actions / quality

Forbidden non-null assertion

return onEvent(handler);
};

eventSource.addEventListener('open', event => {
upd$(readyState, SSEHookReadyState.OPEN);
triggerOnOpen(createSSEEvent('open', event));
});
eventSource.addEventListener('error', event => {
upd$(readyState, SSEHookReadyState.CLOSED);
triggerOnError(createSSEEvent('error', event) as AlovaSSEErrorEvent);
});
eventSource.addEventListener('message', event => {
triggerOnMessage(createSSEEvent('message', event) as AlovaSSEMessageEvent<any>);
});

onUnmounted$(() => {
offOpen();
offMessage();
offError();
});

return {
readyState: _exp$(readyState),
data,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

这个最好也可以_exp$一下,在react中可直接用

eventSource,
onMessage,
onError,
onOpen,
on
};
};
5 changes: 5 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
import useCaptcha_unified from '@/hooks/useCaptcha';
import useForm_unified from '@/hooks/useForm';
import useRetriableRequest_unified from '@/hooks/useRetriableRequest';
import useSSE_unified from '@/hooks/useSSE';
import { actionDelegationMiddleware as actionDelegationMiddleware_unified } from '@/middlewares/actionDelegation';

export const usePagination = (handler, config = {}) =>
Expand Down Expand Up @@ -93,3 +94,7 @@
trueValue
);
});

// 导出useSSE
export const useSSE = (handler, config = {}) =>
useSSE_unified(handler, config, $, $$, _$, _exp$, upd$, watch$, onMounted$, useFlag$, useMemorizedCallback$);

Check failure on line 100 in src/index.js

View workflow job for this annotation

GitHub Actions / quality

Insert `⏎`
47 changes: 47 additions & 0 deletions typings/general.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -836,5 +836,52 @@ type AutoRequestHookConfig<S, E, R, T, RC, RE, RH> = {
*/
throttle?: number;
} & RequestHookConfig<S, E, R, T, RC, RE, RH>;

/**
* SSERequest配置
*/
type SSEHookConfig = {
/** 会传给new EventSource */
withCredentials?: boolean;

/** 是否经过alova实例的responded拦截,默认为true */
interceptByGlobalResponded?: boolean;

/** 初始数据 */
initialData?: any;
};

type SSEReturnType<S> = {
readyState: ExportedType<boolean, S>;
data: R;
eventSource: EventSource;

onOpen(callback: (event: AlovaSSEEvent) => void): void;
onMessage<T>(callback: (event: AlovaSSEMessageEvent<T>) => void): void;
onError(callback: (event: AlovaSSEErrorEvent) => void): void;
on(eventName: 'open' | 'message' | 'error', handler: (event: AlovaSSEEvent) => void): () => void;
};

const enum SSEHookReadyState {
CONNECTING = 0,
OPEN = 1,
CLOSED = 2
}

interface AlovaSSEEvent {
method: Method; // alova的method实例
eventSource: EventSource; // eventSource实例
}
interface AlovaSSEErrorEvent extends AlovaSSEEvent {
error: Error; // 错误对象
}
interface AlovaSSEMessageEvent<T> extends AlovaSSEEvent {
data: T; // 每次响应的,经过拦截器转换后的数据
}
type SSEOnOpenTrigger = (event: AlovaSSEEvent) => void;
type SSEOnMessageTrigger<T> = (event: AlovaSSEMessageEvent<T>) => void;
type SSEOnErrorTrigger = (event: AlovaSSEErrorEvent) => void;
type SSEOn = (eventName: 'open' | 'message' | 'error', handler: (event: AlovaSSEEvent) => void) => () => void;

type NotifyHandler = () => void;
type UnbindHandler = () => void;
Loading