skip to Main Content

I’m trying to fetch data from database and this is my prisma model:

  model instant_reports {
  id         BigInt    @id @default(autoincrement()) @db.UnsignedBigInt
  created_at DateTime?
  updated_at DateTime?
  deleted_at DateTime?
  timestamp  BigInt?
  client_id  BigInt?
  uniq_users BigInt?
}

So when i fetch data like this

  prismaService.instant_reports.findMany({
      skip: 0,
      take: 30,
    });

It throws error

TypeError: Do not know how to serialize a BigInt at JSON.stringify(<anonymous>)

And i don’t even know how to deal with it, is there way to change data handler in findMany method?

If there is no rows in instant_reports so it gives me empty array without error, so the problem is in data with BigInt type

2

Answers


  1. Chosen as BEST ANSWER

    The error is because JavaScript's JSON.stringify doesn't know how to handle BigInt types. So I should have to create a custom serialiser for BigInt fields before sending them as a response to the client. Like this:

    function bigIntToString(value) {
      const MAX_SAFE_INTEGER = 2 ** 53 - 1;
      return value <= MAX_SAFE_INTEGER ? Number(value) : value.toString();
    }
    
    function serializeInstantReports(instantReports) {
      return instantReports.map(report => {
        const newReport = { ...report };
        if (typeof report.id === 'bigint') newReport.id = bigIntToString(report.id);
        // ...
        // such convirtions for other BigInt fields
        // ...
        return newReport;
      });
    }
    

    And then return from a fetch function result of this serializeInstantReports


  2. It worked for me. Add this code to the beginning of yours.

    BigInt.prototype.toJSON = function () {
      const int = Number.parseInt(this.toString());
      return int ?? this.toString();
    };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search