* Helper function to decompress data received over the network. * It returns the parsed JSON object, if valid, or undefined.
(
receivedData: Uint8Array | string
)
| 174 | * It returns the parsed JSON object, if valid, or undefined. |
| 175 | */ |
| 176 | async function decompressData( |
| 177 | receivedData: Uint8Array | string |
| 178 | ): Promise<object | undefined> { |
| 179 | if (compressionMethod === 'none') { |
| 180 | // If no compression is used, we just parse the data. |
| 181 | if (typeof receivedData !== 'string') { |
| 182 | logger.error( |
| 183 | `Error while parsing message using compressionMethod ${compressionMethod}: received data is not a string.` |
| 184 | ); |
| 185 | return; |
| 186 | } |
| 187 | |
| 188 | try { |
| 189 | const parsedData = JSON.parse(receivedData); |
| 190 | return parsedData; |
| 191 | } catch (e) { |
| 192 | logger.error( |
| 193 | `Error while parsing message: ${(e as Error).toString()}` |
| 194 | ); |
| 195 | return; |
| 196 | } |
| 197 | } |
| 198 | const compressionStreamFormat = |
| 199 | compressionMethod === 'cs:gzip' ? 'gzip' : 'deflate'; |
| 200 | |
| 201 | // @ts-ignore - We checked that DecompressionStream is available in the browser. |
| 202 | const ds = new DecompressionStream(compressionStreamFormat); |
| 203 | const writer = ds.writable.getWriter(); |
| 204 | writer.write(receivedData); |
| 205 | writer.close(); |
| 206 | |
| 207 | const decompressedStream = ds.readable; |
| 208 | const reader = decompressedStream.getReader(); |
| 209 | const chunks: any[] = []; |
| 210 | |
| 211 | while (true) { |
| 212 | const { done, value } = await reader.read(); |
| 213 | if (done) break; |
| 214 | chunks.push(value); |
| 215 | } |
| 216 | |
| 217 | const decompressedData = new Uint8Array( |
| 218 | chunks.reduce((acc, chunk) => acc.concat(Array.from(chunk)), []) |
| 219 | ); |
| 220 | const decoder = new TextDecoder(); |
| 221 | const jsonStringData = decoder.decode(decompressedData); // Convert Uint8Array back to string |
| 222 | try { |
| 223 | const parsedData = JSON.parse(jsonStringData); |
| 224 | return parsedData; |
| 225 | } catch (e) { |
| 226 | logger.error(`Error while parsing message: ${(e as Error).toString()}`); |
| 227 | return; |
| 228 | } |
| 229 | } |
| 230 | |
| 231 | /** |
| 232 | * Helper function to get the messages list for a given message name. |