To modify the last 20 values in the message to the required persistedSize, you can use a loop to update the corresponding elements in the Values array. Here's the modified implementation:
/**
* Creates a WebSocket route handler that intercepts messages for a specific connector
* and modifies the field_PersistedSize last 20 values in the statistics payload.
*
* @param {string} connectorId - The connector ID to match in the WebSocket messages.
* @param {number} persistedSize - The desired value to set for field_PersistedSize.
* @returns {Function} A route handler function for Playwright's WebSocket route.
*/
const createConnectorPersistedSizeHandler = (connectorId, persistedSize) => (route) => {
const server = route.connectToServer();
server.onMessage((message) => {
const messageObject = JSON.parse(message);
const getStatsMsg = messageObject?.payload?.data?.GetStats;
if (getStatsMsg && messageObject.id === connectorId) {
const valuesLength = getStatsMsg.Values.length;
const startIndex = Math.max(0, valuesLength - 20); // Ensure startIndex is not negative
for (let i = startIndex; i < valuesLength; i++) {
getStatsMsg.Values[i][1] = persistedSize; // Change the field_PersistedSize value
}
message = JSON.stringify(messageObject);
console.log(`Modified message with persistedSize ${persistedSize} for connector ID: ${connectorId}`);
}
console.log(`Unmodified message for connector ID: ${connectorId}`);
return route.send(message); // Send either modified or original message
});
};
Explanation of Changes:
-
Loop to Update Last 20 Values:
- Introduced a
for loop to iterate over the last 20 elements in the Values array.
- Calculated the
startIndex to ensure we don't go out of bounds if the array has fewer than 20 elements.
- Updated the
field_PersistedSize value (at index 1) for each of the last 20 elements.
-
Condition to Match Connector ID:
- Re-added the condition
messageObject.id === connectorId to ensure we only modify messages for the specified connector ID.
-
Logging:
- Updated the logging messages to reflect the modification of the last 20 values.
Example Usage in Playwright:
const { chromium } = require('playwright');
(async () => {
const browser = await chromium.launch();
const page = await browser.newPage();
// Intercept WebSocket connections
await page.route('wss://your-websocket-url', (route) => {
const handler = createConnectorPersistedSizeHandler('9cf5e744-e170-46f8-b380-267e41fa4da4', 100); // Set field_PersistedSize to 100 for last 20 values
handler(route);
});
// Navigate to your page or perform actions that trigger WebSocket communication
await page.goto('https://your-app-url');
// Your test logic here
await browser.close();
})();