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
Creating Hook Middleware
Use the createHookMiddleware
factory function to create a hook middleware:
import { createHookMiddleware } from '@unilab/urpc-core/middleware';
const HookMiddleware = 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.
});
});
Registering with URPC
import { URPC } from '@unilab/urpc-hono';
const app = URPC.init({
plugins: [MyPlugin],
middlewares: [HookMiddleware],
});
Hook Types
Operation-Specific Hooks
Create Hooks
beforeCreate
: Executed before entity creationafterCreate
: Executed after successful entity creation
Update Hooks
beforeUpdate
: Executed before entity updateafterUpdate
: Executed after successful entity update
Delete Hooks
beforeDelete
: Executed before entity deletionafterDelete
: Executed after successful entity deletion
Universal Hooks
beforeAny
: Executed before any operationafterAny
: Executed after any operation
Hook Function Signature
Each hook function receives three parameters:
type HookFunction<T extends Record<string, any>> = (
context: MiddlewareContext<T>
) => Promise<void> | void;
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);
});
});
UniWeb3 Plugin
UniWeb3 is a comprehensive blockchain plugin for URPC that provides unified access to multiple blockchain networks. It includes support for EVM-compatible chains and Solana, allowing you to query blockchain data through a consistent API.
Logging Middleware
Logging Middleware is a powerful middleware that automatically logs all repository operations including execution time, arguments, results, and error information. It provides detailed insights into your application's data access patterns and helps with debugging and monitoring.