Skip to content

Does N+1 problem even exist in our blog-app with Prisma? #5

@hazartilirot

Description

@hazartilirot

Well, I spent a couple of hours digging into subject. Dunno, I've watched some Prisma videos, then I read their docs, then I implemented a couple examples on my own. What are conclusions of mine? Well,

05:51 in the timeline when Laith demonstrates us console.log("called") in a Post resolvers chains. What really happens from what I get is that the console.log just does its job. He hit the line for each post since we want its owner. It's the right place to be. At the same time we don't know what happens behind the scene meaning how Prisma client processes our data.

However if we open our index.ts file and set logging on the Prisma Client
const prisma = new PrismaClient({ log: ['query'] });

we would be able to see that the Prisma sends two queries:

[0] prisma:query SELECT "public"."Post"."id", "public"."Post"."title", "public"."Post"."content", "public"."Post"."published", "public"."Post"."createdAt", "public"."Post"."updatedAt", "public"."Post"."authorId" FROM "public"."Post" WHERE 1=1 OFFSET $1
[0] prisma:query SELECT "public"."User"."id", "public"."User"."email", "public"."User"."name", "public"."User"."password", "public"."User"."createdAt", "public"."User", "updatedAt" FROM "public"."User" WHERE "public"."User"."id" IN ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17,$18,$19,$20,$21,$22,$23,$24,$25,$26,$27,$28,$29
,$30,$31,$32,$33,$34,$35,$36,$37,$38,$39,$40,$41,$42,$43,$44,$45,$46,$47) OFFSET $48

As you may notice the actual query has been optimized. I went a bit further and implemented a basic hash table in vain.

import { Context } from './types'
import { User } from '.prisma/client'

export default {
  user: async (
    parent: { authorId: string},
    args: any,
    { prisma }: Context
  ) => {
    const hash: { [index: string]: User | null } = {};
    if (!hash[parent.authorId]) 
      hash[parent.authorId] = await prisma.user.findUnique({ where: { id: +parent.authorId } })
    
    return hash[parent.authorId]
  }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions