swaggerstats-nestjs
v0.2.15
Published
NestJS integration for SwaggerStats - Datadog metrics integration for Swagger UI
Maintainers
Readme
SwaggerStats for NestJS
NestJS integration for SwaggerStats - a Datadog metrics integration for Swagger UI.
Installation
npm install swaggerstats-nestjsThis package depends on swaggerstats-core and exposes the same browser plugin.
Usage
Basic Setup
In your NestJS application's main.ts file:
import { NestFactory } from '@nestjs/core';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
import {
applySwaggerStatsDocumentConfig,
setupSwaggerStats,
SwaggerStatsPlugin,
} from 'swaggerstats-nestjs';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
// Mount SwaggerStats on the existing Nest app
setupSwaggerStats(app, {
datadogServiceName: 'your-service-name',
datadogEnvironment: 'development',
apiBasePath: '/api',
mountPath: '/swaggerstats',
});
// Configure Swagger
const config = new DocumentBuilder()
.setTitle('Your API')
.setDescription('API Description')
.setVersion('1.0')
.build();
// Create Swagger document
const document = SwaggerModule.createDocument(app, config);
applySwaggerStatsDocumentConfig(document);
// Set up Swagger UI with the SwaggerStats plugin
SwaggerModule.setup('api-docs', app, document, {
swaggerOptions: {
plugins: [SwaggerStatsPlugin]
}
});
await app.listen(3000);
}
bootstrap();Adding Metrics to Endpoints
Use the ApiSwaggerStats decorator to track usage of specific endpoints:
import { Controller, Get } from '@nestjs/common';
import { ApiSwaggerStats } from 'swaggerstats-nestjs';
@Controller('books')
export class BooksController {
@Get()
@ApiSwaggerStats({
autoInfer: true // Automatically detect the route
})
findAll() {
return { books: [] };
}
@Get(':id')
@ApiSwaggerStats({
// Map to a specific Datadog metric
datadogRoute: '/books/detail',
datadogMethod: 'GET'
})
findOne() {
return { book: {} };
}
}Configuration
Create a swaggerstats.config.js file in your project root:
module.exports = {
// Datadog API credentials
datadogApiKey: process.env.DATADOG_API_KEY,
datadogAppKey: process.env.DATADOG_APP_KEY,
datadogSite: process.env.DATADOG_SITE || 'datadoghq.com',
// Datadog service information
datadogServiceName: 'my-nestjs-service',
datadogEnvironment: 'prod',
datadogMetricType: 'express.request',
// Metrics settings
cacheTtlSeconds: 3600,
// Same-origin route configuration
mountPath: process.env.SWAGGER_STATS_MOUNT_PATH || '/swaggerstats',
apiBasePath: process.env.SWAGGER_STATS_API_BASE_PATH || '/api',
// Path transformation
pathTransformation: {
lowercase: true
}
};Datadog app keys need the timeseries_query permission in order to query the metrics API.
License
MIT
