@@ -68,54 +68,33 @@ export class SSEServerTransport implements Transport {
68
68
async handlePostMessage (
69
69
req : IncomingMessage ,
70
70
res : ServerResponse ,
71
- rawBody ?: string | Buffer ,
72
- bodyEncoding ?: BufferEncoding
71
+ rawOrParsedBody ?: string | unknown ,
73
72
) : Promise < void > {
74
73
if ( ! this . _sseResponse ) {
75
74
const message = "SSE connection not established" ;
76
75
res . writeHead ( 500 ) . end ( message ) ;
77
76
throw new Error ( message ) ;
78
77
}
79
78
80
- let body : string ;
79
+ let body : string | unknown ;
81
80
try {
82
81
const ct = contentType . parse ( req . headers [ "content-type" ] ?? "" ) ;
83
82
if ( ct . type !== "application/json" ) {
84
83
throw new Error ( `Unsupported content-type: ${ ct } ` ) ;
85
84
}
86
85
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
+ } ) ;
111
90
} catch ( error ) {
112
91
res . writeHead ( 400 ) . end ( String ( error ) ) ;
113
92
this . onerror ?.( error as Error ) ;
114
93
return ;
115
94
}
116
95
117
96
try {
118
- await this . handleMessage ( JSON . parse ( body ) ) ;
97
+ await this . handleMessage ( typeof body === 'string' ? JSON . parse ( body ) : body ) ;
119
98
} catch {
120
99
res . writeHead ( 400 ) . end ( `Invalid message: ${ body } ` ) ;
121
100
return ;
0 commit comments