-
Notifications
You must be signed in to change notification settings - Fork 5
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
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
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; | ||
}; |
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'; | ||
|
||
|
@@ -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); | ||
} | ||
// 返回取消注册函数 | ||
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
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 这个判断好像无效,因为按你写的callbacks至少都会是一个空数组 |
||
|
||
const removeAllCallback = () => { | ||
callbacks = []; | ||
}; | ||
|
||
return [setCallback, triggerCallback as Fn, removeAllCallback] as const; | ||
} |
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); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 这里为什么要通过useRequest来创建data,是不是直接 |
||
const readyState = $<SSEHookReadyState>(SSEHookReadyState.CONNECTING); | ||
|
||
// type: eventname & useCallback() | ||
const eventMap: Map<string, ReturnType<typeof useCallback>> = new Map(); | ||
const [onOpen, triggerOnOpen, offOpen] = useCallback<SSEOnOpenTrigger>(); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 可能你没注意到 |
||
|
||
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)!; | ||
|
||
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, | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 这个最好也可以_exp$一下,在react中可直接用 |
||
eventSource, | ||
onMessage, | ||
onError, | ||
onOpen, | ||
on | ||
}; | ||
}; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
我提下我的见解,如果我的话,我会把
onCallbackChange
接收处默认为noop
,这样就不需要多个地方判断onCallbackChange
是否有值,当然你这样写也没啥问题。