33import { ConfigService } from '@hashgraph/json-rpc-config-service/dist/services' ;
44import { ParameterizedContext } from 'koa' ;
55
6+ interface IResponseContext {
7+ body : {
8+ jsonrpc : unknown ;
9+ id : unknown ;
10+ result ?: unknown ;
11+ error ?: { code : unknown ; message : unknown } ;
12+ } ;
13+ status : number | undefined ;
14+ }
15+
616const VALID_JSON_RPC_HTTP_REQUESTS_STATUS_CODE = ConfigService . get ( 'VALID_JSON_RPC_HTTP_REQUESTS_STATUS_CODE' ) ;
717
818const FALLBACK_RESPONSE_BODY = {
@@ -16,41 +26,36 @@ export const INVALID_METHOD_RESPONSE_BODY = {
1626 error : { code : - 32600 , message : 'Invalid HTTP method: only POST is allowed' } ,
1727} ;
1828
19- /**
20- * Ensures a JSON-RPC response uses a valid JSON-RPC 2.0 structure.
21- * Normalizes missing or invalid fields for both single and batch responses.
22- * May update HTTP status depending on VALID_JSON_RPC_HTTP_REQUESTS_STATUS_CODE.
23- *
24- * @param {ParameterizedContext } ctx - Koa context containing status and body.
25- */
26- export const jsonRpcComplianceLayer = async (
27- ctx : {
28- body : {
29- jsonrpc : unknown ;
30- id : unknown ;
31- result ?: unknown ;
32- error ?: { code : unknown ; message : unknown } ;
33- } ;
34- status : number | undefined ;
35- } & ParameterizedContext ,
36- ) => {
29+ const makeSureBodyExistsAndCanBeChecked = ( ctx : IResponseContext ) => {
3730 if ( ! ctx . body ) {
3831 ctx . status = 400 ;
3932 ctx . body = FALLBACK_RESPONSE_BODY ;
40- return ;
33+ return false ;
4134 }
4235
4336 if ( Array . isArray ( ctx . body ) ) {
4437 ctx . status = 200 ;
45- return ;
38+ return false ;
4639 }
4740
4841 if ( typeof ctx . body !== 'object' ) {
4942 ctx . status = 400 ;
5043 ctx . body = FALLBACK_RESPONSE_BODY ;
51- return ;
44+ return false ;
5245 }
5346
47+ return true ;
48+ } ;
49+
50+ /**
51+ * Ensures a JSON-RPC response uses a valid JSON-RPC 2.0 structure.
52+ * Normalizes missing or invalid fields for both single and batch responses.
53+ * May update HTTP status depending on VALID_JSON_RPC_HTTP_REQUESTS_STATUS_CODE.
54+ *
55+ * @param {IResponseContext & ParameterizedContext } ctx - Koa context containing status and body.
56+ */
57+ export const jsonRpcComplianceLayer = async ( ctx : IResponseContext & ParameterizedContext ) => {
58+ if ( ! makeSureBodyExistsAndCanBeChecked ( ctx ) ) return ;
5459 ctx . body . jsonrpc ||= FALLBACK_RESPONSE_BODY . jsonrpc ;
5560 ctx . body . id ||= FALLBACK_RESPONSE_BODY . id ;
5661
0 commit comments