Topics Fastify & Databases Prisma ORM Integration
intermediate 15 min read

Prisma ORM Integration

Use Prisma ORM with Fastify for type-safe database operations.

Prisma Plugin for Fastify

const Fastify = require('fastify');\nconst fp = require('fastify-plugin');\nconst { PrismaClient } = require('@prisma/client');\n\n// Prisma plugin\nasync function prismaPlugin(fastify, opts) {\n  const prisma = new PrismaClient({\n    log: opts.logging ? ['query', 'info', 'warn', 'error'] : [],\n  });\n\n  await prisma.$connect();\n\n  fastify.decorate('prisma', prisma);\n\n  fastify.addHook('onClose', async (instance) => {\n    await instance.prisma.$disconnect();\n  });\n}\n\napp.register(fp(prismaPlugin, { name: 'prisma', logging: true }));\n\n// Usage\napp.get('/posts', async (request) => {\n  const { page = 1, limit = 10, published } = request.query;\n\n  const where = {};\n  if (published !== undefined) {\n    where.published = published === 'true';\n  }\n\n  const [posts, total] = await Promise.all([\n    app.prisma.post.findMany({\n      where,\n      skip: (page - 1) * limit,\n      take: limit,\n      include: { author: { select: { name: true } } },\n      orderBy: { createdAt: 'desc' },\n    }),\n    app.prisma.post.count({ where }),\n  ]);\n\n  return { data: posts, total, page, totalPages: Math.ceil(total / limit) };\n});

Examples

const Fastify = require('fastify');
const fp = require('fastify-plugin');
const { PrismaClient } = require('@prisma/client');

const app = Fastify({ logger: true });

const prismaPlugin = fp(async (fastify) => {
  const prisma = new PrismaClient();
  await prisma.\$connect();
  fastify.decorate('prisma', prisma);
  fastify.addHook('onClose', () => prisma.\$disconnect());
});

app.register(prismaPlugin);

app.get('/users/:id', {
  schema: {
    params: {
      type: 'object',
      required: ['id'],
      properties: { id: { type: 'integer' } },
    },
  },
}, async (request, reply) => {
  const user = await app.prisma.user.findUnique({
    where: { id: request.params.id },
    include: {
      posts: {
        take: 5,
        orderBy: { createdAt: 'desc' },
      },
    },
  });

  if (!user) {
    reply.code(404);
    return { error: 'User not found' };
  }

  return user;
});

app.listen({ port: 3000 });

Your Notes

Sign in to take notes for this lesson.

Discussion

Sign in to join the discussion.

Flashcards

Sign in to create flashcards.