fodma1
fodma1

Reputation: 3535

Prisma js return join fields

I'm trying to implement batching and caching with the Facebook DataLoader. Let's say I have the following schema (taken from here):

type Post {
  id: ID! @id
  title: String!
  published: Boolean! @default(value: false)
  author: User
  comments: [Comment!]!
}

type User {
  id: ID! @id
  name: String
  posts: [Post!]!
  comments: [Comment!]!
}

type Comment {
  id: ID! @id
  text: String!
  post: Post!
  writtenBy: User!
}

I am working on a tricky resolver which lists all comments created by the same user under the same post for a given comment. To retrieve a single entry I would go like:

const fetchCommentsByUserForSamePost = async (commentId: string, userId: string): Promise<Comment[]> => {
  const comments = await this.prisma.comment.findOne({ where: { id: commentId } })
    .post()
    .comments({
      where: {
        writtenBy: { id: userId }
      }
    })
  return comments;
}

This works well for a single query, but I would like to batch the queries. In raw SQL I'd return commentId and userId in every row, such that I can group the results by these fields. But I can't find a way to return the original commentId with Prisma to generalize the query to work with a list of commentId - userId pairs.

Is there a way to accomplish this with Prisma, or I am missing something? I am aware that making two requests could solve this, but that would result in an involved logic, plus I'd rather avoid making two DB roundtrips.

Upvotes: 0

Views: 3071

Answers (1)

mavilein
mavilein

Reputation: 11668

Prisma 2.0 already has a Dataloader built in exactly for this purpose. This means your resolvers might do multiple calls to findOne but those will be batched into one big SQL query under the hood. So there should be no need for you to implement this optimization on your own.

Upvotes: 1

Related Questions