@@ -68,54 +68,33 @@ export class SSEServerTransport implements Transport {
6868 async handlePostMessage (
6969 req : IncomingMessage ,
7070 res : ServerResponse ,
71- rawBody ?: string | Buffer ,
72- bodyEncoding ?: BufferEncoding
71+ rawOrParsedBody ?: string | unknown ,
7372 ) : Promise < void > {
7473 if ( ! this . _sseResponse ) {
7574 const message = "SSE connection not established" ;
7675 res . writeHead ( 500 ) . end ( message ) ;
7776 throw new Error ( message ) ;
7877 }
7978
80- let body : string ;
79+ let body : string | unknown ;
8180 try {
8281 const ct = contentType . parse ( req . headers [ "content-type" ] ?? "" ) ;
8382 if ( ct . type !== "application/json" ) {
8483 throw new Error ( `Unsupported content-type: ${ ct } ` ) ;
8584 }
8685
87- if ( rawBody ) {
88- if ( typeof rawBody === 'string' ) {
89- body = rawBody ;
90- } else if ( Buffer . isBuffer ( rawBody ) ) {
91- if ( bodyEncoding ) {
92- body = rawBody . toString ( bodyEncoding ) ;
93- } else if ( ct . parameters . charset ) {
94- if ( Buffer . isEncoding ( ct . parameters . charset ) ) {
95- body = rawBody . toString ( ct . parameters . charset as BufferEncoding ) ;
96- } else {
97- throw new Error ( 'Unsupported buffer encoding: ${ct.parameters.charset}' )
98- }
99- } else {
100- body = rawBody . toString ( 'utf8' ) ;
101- }
102- } else {
103- throw new Error ( "Unsupported rawBody type. rawBody must be one of 'Buffer' or 'string'" ) ;
104- }
105- } else {
106- body = await getRawBody ( req , {
107- limit : MAXIMUM_MESSAGE_SIZE ,
108- encoding : ct . parameters . charset ?? "utf-8" ,
109- } ) ;
110- }
86+ body = rawOrParsedBody ?? await getRawBody ( req , {
87+ limit : MAXIMUM_MESSAGE_SIZE ,
88+ encoding : ct . parameters . charset ?? "utf-8" ,
89+ } ) ;
11190 } catch ( error ) {
11291 res . writeHead ( 400 ) . end ( String ( error ) ) ;
11392 this . onerror ?.( error as Error ) ;
11493 return ;
11594 }
11695
11796 try {
118- await this . handleMessage ( JSON . parse ( body ) ) ;
97+ await this . handleMessage ( typeof body === 'string' ? JSON . parse ( body ) : body ) ;
11998 } catch {
12099 res . writeHead ( 400 ) . end ( `Invalid message: ${ body } ` ) ;
121100 return ;
0 commit comments