Middleware

Hook Middleware

Hook Middleware is a powerful middleware that allows you to hook into the URPC lifecycle and execute custom logic before and after CRUD operations. This enables you to implement cross-cutting concerns like validation, logging, caching, notifications, and more.

Installation

npm install @unilab/urpc-core

Basic Usage

import { URPC } from '@unilab/urpc-hono';
import { createHookMiddleware } from '@unilab/urpc-core/middleware';

// Creating Hook Middleware
const hook = createHookMiddleware((hookManager) => {
  hookManager
    .beforeCreate(async (context) => {
      console.log('Before creating:', context);
      // Validation, data transformation, etc.
    })
    .afterCreate(async (context) => {
      console.log('After creating:', context);
      // Notifications, logging, etc.
    });
});

const app = URPC.init({
  plugins: [MyPlugin],
  middlewares: [hook],
});

Audit Logging

const AuditHooks = createHookMiddleware((hookManager) => {
  hookManager
    .afterCreate(async (context) => {
      console.log(`AUDIT: Created ${context.operation} with ID: ${context.result?.id}`);
    })
    .afterUpdate(async (context) => {
      console.log(`AUDIT: Updated ${context.operation} with ID: ${context.result?.id}`);
    })
    .afterDelete(async (context) => {
      console.log(`AUDIT: Deleted ${context.operation}`);
    });
});

Notifications

const NotificationHooks = createHookMiddleware((hookManager) => {
  hookManager
    .afterCreate(async (context) => {
      if (context?.adapter.constructor.name === 'UserAdapter') {
        await sendWelcomeEmail(context.result?.email);
      }
    })
    .afterUpdate(async (context) => {
      await sendUpdateNotification(context.result?.id, context.args.data);
    });
});