Prisma:类型错误:不知道如何序列化 BigInt

blu*_*per 6 mysql node.js nestjs prisma

我正在尝试从数据库中获取数据,这是我的 prisma 模型:

  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?
}
Run Code Online (Sandbox Code Playgroud)

所以当我获取这样的数据时

  prismaService.instant_reports.findMany({
      skip: 0,
      take: 30,
    });
Run Code Online (Sandbox Code Playgroud)

它抛出错误

TypeError:不知道如何在 JSON.stringify(<anonymous>) 处序列化 BigInt

我什至不知道如何处理它,有没有办法改变findMany方法中的数据处理程序?

如果没有行,instant_reports那么它会给我空数组而没有错误,所以问题出在 BigInt 类型的数据中

小智 9

这对我有用。将此代码添加到您的代码的开头。

BigInt.prototype.toJSON = function () {
  const int = Number.parseInt(this.toString());
  return int ?? this.toString();
};
Run Code Online (Sandbox Code Playgroud)


blu*_*per 0

该错误是因为 JavaScript 的 JSON.stringify 不知道如何处理 BigInt 类型。因此,我应该先为 BigInt 字段创建一个自定义序列化程序,然后再将它们作为响应发送给客户端。像这样:

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;
  });
}
Run Code Online (Sandbox Code Playgroud)

然后从获取函数结果返回serializeInstantReports