如何将 Prisma 模型作为通用基础存储库(baseRepository)的创建工作?

huangapple go评论100阅读模式
英文:

How to make prisma model work as generic for creating baseRepository?

问题

以下是翻译好的部分:

"The idea is I pass the model name to use crud operation for all tables :

  1. class BaseRepository{
  2. db = prisma
  3. async findAll(modelName: "user" | "post"){
  4. return await this.prisma[modelName].findMany()
  5. }
  6. }

The findMany doesn't work and returns typescript error and also when I tried to use findUnique or any other function they don't work also.. how I can make them work?"

英文:

The idea is I pass the model name to use crud operation for all tables :

  1. class BaseRepository{
  2. db = prisma
  3. async findAll(modelName: "user" | "post"){
  4. return await this.prisma[modelName].findMany()
  5. }
  6. }

The findMany doesn't work and returns typescript error and also when I tried to use findUnique or any other function they don't work also.. how I can make them work?

答案1

得分: 1

使用 switch 的最简单方法:

  1. async findAll(modelName: 'user' | 'post') {
  2. switch (modelName) {
  3. case 'user':
  4. return this.prisma.user.findMany();
  5. case 'post':
  6. return this.prisma.post.findMany();
  7. }
  8. }
英文:

the easiest way use switch

  1. async findAll(modelName: 'user' | 'post') {
  2. switch (modelName) {
  3. case 'user':
  4. return this.prisma.user.findMany();
  5. case 'post':
  6. return this.prisma.post.findMany();
  7. }
  8. }

huangapple
  • 本文由 发表于 2023年7月7日 07:39:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/76633115.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定