How to parse the http request using typebox?

367 views Asked by At

I am using the typebox validator

import { Type } from '@sinclair/typebox';
import { Value } from '@sinclair/typebox/value';

const metaReqSchema = Type.Object({
  name: Type.String()
});
const reqSchema = Type.Object({
  // You can also type querystring, headers and response
  params: Type.Object({
    idParam: Type.String()
  }),
  body: metaReqSchema
});
@httpPost('/version/:idParam')
  public async getMeta(request: Request, response: Response, next: NextFunction) {
    try {
      const dataInputValidated = Value.Decode(reqSchema, request);

      console.log('iNPUT vALDIATED', dataInputValidated.body);
      console.log('Param', dataInputValidated.params);

      return response.status(200).json({
        data: 1
      });
    } catch (err) {
      return response.status(500).json({
        data: err
      });
    }
  }

Getting this error : Converting circular structure to JSON\n --> starting at object with constructor 'Socket'\n | property 'parser' -> object with constructor 'HTTPParser'\n --- property 'socket' closes the circle

While validating just request.body or request.parse, it works I need validated input from the request object which maps to the input type.

But decoding gives same object as the request.


try {
      const dataInputValidated = Value.Decode(metaReqSchema, request.body);

      console.log('iNPUT vALDIATED', dataInputValidated);
      console.log('Param', dataInputValidated);

      return response.status(200).json({
        data: dataInputValidated
      });
    } catch (err) {
      return response.status(500).json({
        error: err
      });
    }
    ```


This works but valdiating the reqSchema it throws circular json error
1

There are 1 answers

0
Kamran On

You are trying to store whole response object which is complex data structure and contains circular dependencies as it stated in error message (TypeError: Converting circular structure to JSON)

What you should do is either you map the data you need instead of storing whole circular object.