Chuyển đến nội dung

Bài 30 · Performance and Patterns

Client Extensions

Customize Prisma Client with $extends - add computed result fields, custom model methods, query hooks for soft delete and auditing, and client-level helpers - with a runnable stand-in.

Real applications repeat the same rules everywhere: hide soft-deleted rows, add a fullName field, log slow queries, enforce tenant filters. Copying those rules into every query invites bugs. Client extensions let you attach them to the client once with $extends, and every query benefits. They replace the old $use middleware, which was removed in Prisma 6.

The Prisma code is read-only (it needs the npm package). The TryIts are labelled stand-ins: a tiny $extends clone over an in-memory store so you can see how each hook composes.

The four component types

$extends returns a new client (the original is unchanged) and takes an object with these optional parts:

Component Purpose Example
result add computed fields to query results fullName
model add custom methods to a model user.signUp()
query intercept and modify queries soft delete, auditing
client add methods to the client itself $log()

result: computed fields

TypeScript
const prisma = new PrismaClient({ adapter }).$extends({
  result: {
    user: {
      fullName: {
        needs: { firstName: true, lastName: true },
        compute(user) {
          return `${user.firstName} ${user.lastName}`;
        },
      },
    },
  },
});

const u = await prisma.user.findFirstOrThrow();
console.log(u.fullName);

needs lists the real fields the computed one depends on; Prisma fetches them even if your select leaves them out. Computed fields exist only in memory, are not filterable in where, and are typed for you.

model: custom methods

TypeScript
const prisma = new PrismaClient({ adapter }).$extends({
  model: {
    user: {
      async signUp(email: string) {
        return prisma.user.create({ data: { email } });
      },
    },
  },
});

await prisma.user.signUp('[email protected]');

Use Prisma.getExtensionContext(this) inside a method to refer to the model it was called on, so one method can be added to all models with $allModels.

query: intercepting operations

This is the powerful one. A handler receives { model, operation, args, query }; call query(args) to continue, after changing args or wrapping the result.

TypeScript
const prisma = new PrismaClient({ adapter }).$extends({
  query: {
    post: {
      async findMany({ args, query }) {
        args.where = { ...args.where, deletedAt: null };   // hide soft-deleted rows
        return query(args);
      },
    },
    $allModels: {
      async $allOperations({ model, operation, args, query }) {
        const start = performance.now();
        const result = await query(args);
        console.log(`${model}.${operation} took ${(performance.now() - start).toFixed(1)}ms`);
        return result;
      },
    },
  },
});

$allModels and $allOperations are wildcards. Order matters when you chain several $extends calls: each one wraps the previous.

Node.js Stand-in: a mini $extends with query hooks

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Soft delete, done properly

Soft delete marks rows deleted instead of removing them (deletedAt DateTime?). With a query extension you override delete and deleteMany to update, and findMany, findFirst, findUnique and count to add deletedAt: null. Remember what extensions cannot cover: raw queries, relation loading (include) of soft-deleted children, and unique constraints (a deleted email still blocks a new account with the same email). Decide those rules up front.

Other uses

  • Audit logging: write to an AuditLog table after every create, update and delete.
  • Multi-tenancy: force where: { tenantId } on every query. For hard isolation prefer PostgreSQL row-level security; the extension is a convenience layer, not a security boundary.
  • Validation: parse args.data with a schema library before query(args).
  • Caching: Prisma Accelerate ships as an extension (withAccelerate()), adding cacheStrategy to queries.
  • Client helpers: client: { $healthCheck() { return prisma.$queryRaw...; } }.
Node.js Stand-in: audit every write through one wrapper

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Gotchas

  • $extends returns a new client; keep using the extended one, and export only that from your db module.
  • Query hooks run per operation, including those inside nested writes and transactions started from the extended client.
  • Types flow through, but heavy extensions can slow TypeScript; keep them focused.
  • Extensions add overhead to every query: keep hooks cheap and do not log full results in production.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. What does $extends return?

    Extensions are immutable: you get a new client and must use that one.
  2. 2. Which component adds a fullName field to results?

    result extensions define computed fields with needs and compute.
  3. 3. In a query hook, what does calling query(args) do?

    query continues the operation; change args before calling it, or wrap its result.
  4. 4. Which is a limit of a soft-delete query extension?

    Raw SQL does not go through query hooks, so it must filter deleted rows itself.

Summary

  • $extends adds result, model, query and client behavior and returns a new client.
  • Query hooks implement soft delete, auditing, timing and tenant filters in one place.
  • Computed fields need needs and live only in memory.
  • Raw queries and some relation paths bypass hooks; design around that.
  • This replaces the removed $use middleware.

Next: Connection Pooling and Logging

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.