谢谢任何帮助。
我在前端使用 apollo-client 和后端graphql-nexus、prisma2 和 graphql-yoga 服务器。
我想用@paljs/plugins 解决n + 1 问题。
在前端,我有一个查询帖子,例如:
query posts{
posts {
id
favoritedBy(where: { id: { equals: $currentUserId } }) {
id
}
author {
id
avatar {
id
}
}
link {
id
}
games {
id
}
tags {
id
}
likes(where: { user: { id: { equals: $currentUserId } } }) {
id
}
}
}
帖子解析器:
import { PrismaSelect } from '@paljs/plugins'
export const posts = queryField('posts', {
type: 'Post',
list: true,
args: {
...
},
resolve: async (_parent, args, { prisma, request }, info) => {
const select = new PrismaSelect(info).value
let opArgs: FindManyPostArgs = {
take: 10,
orderBy: {
[args.orderBy]: 'desc',
},
...select
}
const post = await prisma.post.findMany(opArgs)
//The result I want to return with the "sub-models" like likes, author tags...
console.log(JSON.stringify(post, undefined, 2))
return post
},
})
我记录查询
const prisma = new PrismaClient({
log: ['query'],
})
我的问题:使用 PrismaSelect,我有 5 个查询,如果我在前端检查请求时间,我需要 PrismaSelect 多 300-400 毫秒。那么我做错了什么?我在@paljs/plugins文档中看到了上下文中的选择。也许那是我的错误。如何在上下文中使用选择?
这是我的上下文:
import { PrismaClient, PrismaClientOptions } from '@prisma/client'
import { PubSub } from 'graphql-yoga'
import { PrismaDelete, onDeleteArgs } from '@paljs/plugins'
class Prisma extends PrismaClient {
constructor(options?: PrismaClientOptions) {
super(options)
}
async onDelete(args: onDeleteArgs) {
const prismaDelete = new PrismaDelete(this)
await prismaDelete.onDelete(args)
}
}
export const prisma = new PrismaClient({
log: ['query'],
})
export const pubsub = new PubSub()
export interface Context {
prisma: PrismaClient
request: any
pubsub: PubSub
}
export function createContext(request: any): Context {
return { prisma, request, pubsub }
}