Skip to content

Commit

Permalink
Merge pull request #13378 from CodyTseng/optimize-ws-adapter-handler-…
Browse files Browse the repository at this point in the history
…find

perf(ws): optimize message handler lookup
  • Loading branch information
kamilmysliwiec authored Aug 12, 2024
2 parents ccfa23e + 8c7718e commit e5c439d
Showing 1 changed file with 6 additions and 5 deletions.
11 changes: 6 additions & 5 deletions packages/platform-ws/adapters/ws-adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,10 +111,13 @@ export class WsAdapter extends AbstractWsAdapter {
handlers: MessageMappingProperties[],
transform: (data: any) => Observable<any>,
) {
const handlersMap = new Map<string, MessageMappingProperties>();
handlers.forEach(handler => handlersMap.set(handler.message, handler));

const close$ = fromEvent(client, CLOSE_EVENT).pipe(share(), first());
const source$ = fromEvent(client, 'message').pipe(
mergeMap(data =>
this.bindMessageHandler(data, handlers, transform).pipe(
this.bindMessageHandler(data, handlersMap, transform).pipe(
filter(result => !isNil(result)),
),
),
Expand All @@ -131,14 +134,12 @@ export class WsAdapter extends AbstractWsAdapter {

public bindMessageHandler(
buffer: any,
handlers: MessageMappingProperties[],
handlersMap: Map<string, MessageMappingProperties>,
transform: (data: any) => Observable<any>,
): Observable<any> {
try {
const message = JSON.parse(buffer.data);
const messageHandler = handlers.find(
handler => handler.message === message.event,
);
const messageHandler = handlersMap.get(message.event);
const { callback } = messageHandler;
return transform(callback(message.data, message.event));
} catch {
Expand Down

0 comments on commit e5c439d

Please sign in to comment.