Skip to content

Commit

Permalink
Reverse the order of WebSocket events (#5148)
Browse files Browse the repository at this point in the history
* Reverse the event log order in the view and subscribe to messages after the latest
  • Loading branch information
gatzjames authored Sep 8, 2022
1 parent a91b988 commit a8b1a42
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 3 deletions.
8 changes: 6 additions & 2 deletions packages/insomnia/src/main/network/websocket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,8 @@ const dispatchWebSocketEvent = (target: Electron.WebContents, eventChannel: stri
// Otherwise, append to send queue for this event channel.
const sendQueue = sendQueueMap.get(eventChannel);
if (sendQueue) {
sendQueue.push(wsEvent);
// Add the event to the top of queue so that the latest message is first.
sendQueue.unshift(wsEvent);
} else {
sendQueueMap.set(eventChannel, [wsEvent]);
}
Expand Down Expand Up @@ -433,7 +434,10 @@ const findMany = async (
}
const body = await fs.promises.readFile(response.bodyPath);
return body.toString().split('\n').filter(e => e?.trim())
.map(e => JSON.parse(e)) || [];
// Parse the message
.map(e => JSON.parse(e))
// Reverse the list of messages so that we get the latest message first
.reverse() || [];
};

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,21 @@ export function useWebSocketConnectionEvents({ responseId }: { responseId: strin
if (isMounted) {
setEvents(allEvents);
}

const afterLatestEvent = (event: WebSocketEvent, prevEvents: WebSocketEvent[]) => {
if (prevEvents.length === 0) {
return true;
}

return event.timestamp > prevEvents[0]?.timestamp;
};

// Subscribe to new events and update the state.
unsubscribe = window.main.on(`webSocket.${responseId}.event`,
(_, events: WebSocketEvent[]) => {
console.log('received events', events);
if (isMounted) {
setEvents(allEvents => allEvents.concat(events));
setEvents(prevEvents => events.filter(event => afterLatestEvent(event, prevEvents)).concat(prevEvents));
}

// Wait to give the CTS signal until we've rendered a frame.
Expand Down

0 comments on commit a8b1a42

Please sign in to comment.