LoginSignup
0
0

More than 1 year has passed since last update.

Nuxt3 + prismaでRailsのActiveRecord MySQLデータベースを読み込んだ時に困ったこと

Posted at

起こった事象

npx prisma db pullでschema.prismaにDB内容を反映した後npx prisma generateでprisma clientにschemaを反映。その後apiを叩いた時に以下のエラーが発生。

[nuxt] [request error] [unhandled] [500] Do not know how to serialize a BigInt

以下のGithub issueでも話題に上がっているように、どうやらBigIntにtoJsonメソッドが生えていないことが原因のようです。

ActiveRecordはid系のカラムをBigIntで生成しますからね。

解決策は

  1. BigIntにtoJsonメソッドを生やす
  2. schemaでid系のカラムをIntとしてmappingする

2の場合だとdb pullした時にIntのカラムがBigIntに書き変わってしまい使い勝手が悪いので1の方法で今回は対処しました。

prismaディレクトリ下でprisma clientをexportしているのでそこでBigIntにtoJsonを生やします。


import { PrismaClient } from '@prisma/client'

declare global {
  interface BigInt {
    toJSON(): string;
  }
}

BigInt.prototype.toJSON = function (): string {
  return this.toString();
};

const prismaClient = new PrismaClient()

export default prismaClient

私の場合はこれで動作しました。参考までに関係ありそうなnpmパッケージのバージョンを以下に記載しておきます。

{
    "@prisma/client": "^4.10.1",
    "nuxt": "^3.2.2",
    "prisma": "^4.10.1",
    "typescript": "^4.9.5"
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0