英文:
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();
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论