何时使用
当需要对 NitroStack 工具方法实现请求验证、授权检查、响应映射、日志记录、错误处理或性能追踪时,使用此技能。
1. 守卫(Guard 和 @UseGuards)
守卫基于身份验证、授权或其他条件决定是否应由工具处理程序处理请求。
接口:
import { Guard, ExecutionContext } from '@nitrostack/core';
export interface Guard {
canActivate(context: ExecutionContext): boolean | Promise<boolean>;
}
示例:
import { Guard, ExecutionContext, Injectable } from '@nitrostack/core';
@Injectable()
export class RolesGuard implements Guard {
async canActivate(context: ExecutionContext): Promise<boolean> {
const userRoles = context.clientMetadata?.roles || [];
return userRoles.includes('admin');
}
}
使用 @UseGuards(...) 应用守卫:
import { Tool, UseGuards, z } from '@nitrostack/core';
import { RolesGuard } from './roles.guard.js';
export class AdminTools {
@Tool({
name: 'delete_system_logs',
description: '从服务器删除所有系统日志。',
inputSchema: z.object({}),
})
@UseGuards(RolesGuard)
async deleteLogs() {
return { success: true };
}
}
2. 拦截器(InterceptorInterface 和 @UseInterceptors)
拦截器可以转换/拦截输入参数或工具方法执行后的映射输出。
接口:
import { ExecutionContext } from '@nitrostack/core';
export interface InterceptorInterface {
intercept(context: ExecutionContext, next: () => Promise<unknown>): Promise<unknown>;
}
示例:
import { InterceptorInterface, ExecutionContext, Injectable } from '@nitrostack/core';
@Injectable()
export class TimingInterceptor implements InterceptorInterface {
async intercept(context: ExecutionContext, next: () => Promise<unknown>): Promise<unknown> {
const start = Date.now();
const result = await next();
const duration = Date.now() - start;
context.logger.info(`执行耗时 ${duration}ms`);
return {
...result,
_meta: { durationMs: duration }
};
}
}
3. 异常过滤器(ExceptionFilterInterface 和 @UseFilters)
异常过滤器捕获守卫、拦截器或工具处理程序自身抛出的任何错误,并将其映射为用户友好的 JSON 载荷。
接口:
import { ExecutionContext } from '@nitrostack/core';
export interface ExceptionFilterInterface {
catch(exception: unknown, context: ExecutionContext): unknown | Promise<unknown>;
}
示例:
import { ExceptionFilterInterface, ExecutionContext, Injectable } from '@nitrostack/core';
@Injectable()
export class CustomExceptionFilter implements ExceptionFilterInterface {
catch(exception: unknown, context: ExecutionContext) {
const message = exception instanceof Error ? exception.message : '未知错误';
return {
error: true,
message,
timestamp: new Date().toISOString()
};
}
}
在工具方法上使用 @UseFilters(...) 应用过滤器:
import { Tool, UseFilters, z } from '@nitrostack/core';
import { CustomExceptionFilter } from './custom-exception.filter.js';
export class LoggingTools {
@Tool({
name: 'generate_report',
description: '生成系统使用情况报告。',
inputSchema: z.object({}),
})
@UseFilters(CustomExceptionFilter)
async generateReport() {
throw new Error('报告生成功能尚未实现。');
}
}
4. 中间件(MiddlewareInterface、@Middleware 和 @UseMiddleware)
中间件在请求到达工具处理程序之前执行,并且可以通过调用 next() 来包装处理程序的执行。
接口:
import { ExecutionContext } from '@nitrostack/core';
export interface MiddlewareInterface {
use(context: ExecutionContext, next: () => Promise<unknown>): Promise<unknown>;
}
示例:
import { Middleware, MiddlewareInterface, ExecutionContext } from '@nitrostack/core';
@Middleware()
export class LoggingMiddleware implements MiddlewareInterface {
async use(context: ExecutionContext, next: () => Promise<unknown>): Promise<unknown> {
context.logger.info(`进入工具:${context.toolName}`);
try {
const result = await next();
context.logger.info(`退出工具:${context.toolName}`);
return result;
} catch (error) {
context.logger.error(`工具中出错:${error}`);
throw error;
}
}
}
在工具方法上使用 @UseMiddleware(...) 应用中间件:
import { Tool, UseMiddleware, z } from '@nitrostack/core';
import { LoggingMiddleware } from './logging.middleware.js';
export class StationTools {
@Tool({
name: 'fetch_logs',
description: '获取站台操作日志。',
inputSchema: z.object({}),
})
@UseMiddleware(LoggingMiddleware)
async fetchLogs() {
return { status: 'operational' };
}
}
5. 管道(PipeInterface、@Pipe 和 @UsePipes)
管道用于在输入参数到达工具处理程序方法之前对其进行转换或验证。
接口:
import { ArgumentMetadata } from '@nitrostack/core';
export interface PipeInterface<T = unknown, R = unknown> {
transform(value: T, metadata: ArgumentMetadata): R | Promise<R>;
}
示例:
import { Pipe, PipeInterface, ArgumentMetadata } from '@nitrostack/core';
@Pipe()
export class TrimPipe implements PipeInterface<Record<string, unknown>, Record<string, unknown>> {
transform(value: Record<string, unknown>, metadata: ArgumentMetadata) {
const trimmed: Record<string, unknown> = {};
for (const [key, val] of Object.entries(value)) {
trimmed[key] = typeof val === 'string' ? val.trim() : val;
}
return trimmed;
}
}
在工具方法上使用 @UsePipes(...) 应用管道:
import { Tool, UsePipes, z } from '@nitrostack/core';
import { TrimPipe } from './trim.pipe.js';
export class MessagingTools {
@Tool({
name: 'send_message',
description: '向其他站台发送消息。',
inputSchema: z.object({ text: z.string() }),
})
@UsePipes(TrimPipe)
async sendMessage(input: { text: string }) {
return { sentText: input.text };
}
}