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

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

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 :

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

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 :

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

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 的最简单方法:

async findAll(modelName: 'user' | 'post') {
  switch (modelName) {
    case 'user':
      return this.prisma.user.findMany();
    case 'post':
      return this.prisma.post.findMany();
  }
}
英文:

the easiest way use switch

async findAll(modelName: 'user' | 'post') {
  switch (modelName) {
    case 'user':
      return this.prisma.user.findMany();
    case 'post':
      return this.prisma.post.findMany();
  }
}

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:

确定