NestJS integration for SwaggerStats - a Datadog metrics integration for Swagger UI.
npm install swaggerstats-nestjs
This will automatically install the peer dependency swaggerstats-core
.
In your NestJS application's main.ts
file:
import { NestFactory } from '@nestjs/core';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
import { setupSwaggerStats } from 'swaggerstats-nestjs';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
// Set up SwaggerStats - this will start the metrics server
setupSwaggerStats(app, {
serviceName: 'your-service-name',
environment: 'development',
apiBasePath: '/api'
});
// 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);
// Add SwaggerStats config to the document (optional but recommended)
(document as any)['x-swaggerstats-config'] = {
serviceName: 'your-service-name',
apiBasePath: '/api'
};
// Import the SwaggerStats UI plugin
const SwaggerStatsPlugin = require('swaggerstats-nestjs/dist/swagger-ui-plugin');
// Set up Swagger UI with the SwaggerStats plugin
SwaggerModule.setup('api-docs', app, document, {
swaggerOptions: {
plugins: [SwaggerStatsPlugin]
}
});
await app.listen(3000);
}
bootstrap();
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: {} };
}
}
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,
// Datadog service information
datadogServiceName: 'my-nestjs-service',
datadogEnvironment: 'prod',
datadogMetricType: 'express.request',
// Metrics settings
cacheTtlSeconds: 3600,
// Server configuration
port: 3004,
host: 'localhost',
apiBasePath: '/api',
// Path transformation
pathTransformation: {
lowercase: true
}
};
MIT