Хранение api в .env файле

pull/3/head
DmitriyA 2025-02-26 10:28:09 +00:00
parent 1bfa621c27
commit c4ece458e4
5 changed files with 29 additions and 24 deletions

View File

@ -8,4 +8,6 @@ RUN npm install
COPY . . COPY . .
ENV NODE_ENV=development
CMD ["npm", "run", "start:dev"] CMD ["npm", "run", "start:dev"]

View File

@ -23,9 +23,11 @@
"@nestjs/axios": "^4.0.0", "@nestjs/axios": "^4.0.0",
"@nestjs/common": "^11.0.1", "@nestjs/common": "^11.0.1",
"@nestjs/core": "^11.0.1", "@nestjs/core": "^11.0.1",
"@nestjs/config": "^4.0.0",
"@nestjs/platform-express": "^11.0.1", "@nestjs/platform-express": "^11.0.1",
"axios": "^1.7.9", "axios": "^1.7.9",
"reflect-metadata": "^0.2.2", "reflect-metadata": "^0.2.2",
"dotenv": "^16.3.1",
"rxjs": "^7.8.1" "rxjs": "^7.8.1"
}, },
"devDependencies": { "devDependencies": {
@ -72,4 +74,4 @@
"coverageDirectory": "../coverage", "coverageDirectory": "../coverage",
"testEnvironment": "node" "testEnvironment": "node"
} }
} }

View File

@ -2,9 +2,15 @@ import { Module } from '@nestjs/common';
import { HttpModule } from '@nestjs/axios'; import { HttpModule } from '@nestjs/axios';
import { PrometheusService } from './prometheus.service'; import { PrometheusService } from './prometheus.service';
import { MetricsController } from './metrics.controller'; import { MetricsController } from './metrics.controller';
import { ConfigModule } from '@nestjs/config';
@Module({ @Module({
imports: [HttpModule], // Используем новый HttpModule imports: [
ConfigModule.forRoot({
isGlobal: true,
envFilePath: '.env',
}),
HttpModule],
controllers: [MetricsController], controllers: [MetricsController],
providers: [PrometheusService], providers: [PrometheusService],
}) })

View File

@ -1,6 +1,7 @@
import { NestFactory } from '@nestjs/core'; import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module'; import { AppModule } from './app.module';
async function bootstrap() { async function bootstrap() {
const app = await NestFactory.create(AppModule); const app = await NestFactory.create(AppModule);

View File

@ -1,15 +1,20 @@
import { Injectable } from '@nestjs/common'; import { Injectable } from '@nestjs/common';
import { HttpService } from '@nestjs/axios'; import { HttpService } from '@nestjs/axios';
import { ConfigService } from '@nestjs/config';
import { lastValueFrom } from 'rxjs'; import { lastValueFrom } from 'rxjs';
import { PrometheusMetric } from './prometheus-metric.interface'; import { PrometheusMetric } from './prometheus-metric.interface';
@Injectable() @Injectable()
export class PrometheusService { export class PrometheusService {
private readonly prometheusUrl = 'http://192.168.2.37:9090/api/v1'; private readonly prometheusUrl: string;
constructor(private readonly httpService: HttpService) { } constructor(
private readonly httpService: HttpService,
//Получаем тип метрики private readonly configService: ConfigService
) {
this.prometheusUrl = this.configService.get<string>('PROMETHEUS_API', 'http://localhost:9090');
console.log('Prometheus API URL:', this.prometheusUrl);
}
async fetchMetricType(metric: string): Promise<string | null> { async fetchMetricType(metric: string): Promise<string | null> {
try { try {
@ -20,20 +25,13 @@ export class PrometheusService {
); );
const metadata = response.data.data[metric]; const metadata = response.data.data[metric];
return metadata?.length ? metadata[0].type : null;
if (metadata && metadata.length > 0) {
return metadata[0].type; // Возвращаем тип метрики
}
return null;
} catch (error) { } catch (error) {
console.error(`Ошибка при получении типа метрики ${metric}:`, error); console.error(`Ошибка при получении типа метрики ${metric}:`, error);
return null; return null;
} }
} }
//Данные конкретной метрики, включая ее тип
async fetchMetrics(metric: string): Promise<PrometheusMetric[]> { async fetchMetrics(metric: string): Promise<PrometheusMetric[]> {
const response = await lastValueFrom( const response = await lastValueFrom(
this.httpService.get(`${this.prometheusUrl}/query`, { this.httpService.get(`${this.prometheusUrl}/query`, {
@ -41,27 +39,23 @@ export class PrometheusService {
}) })
); );
const metricType = await this.fetchMetricType(metric); // Получаем тип const metricType = await this.fetchMetricType(metric);
return response.data.data.result.map((entry): PrometheusMetric => ({ return response.data.data.result.map((entry): PrometheusMetric => ({
...entry.metric, ...entry.metric,
timestamp: entry.value[0] * 1000, // Преобразуем в миллисекунды timestamp: entry.value[0] * 1000,
value: parseFloat(entry.value[1]), // Преобразуем в число value: parseFloat(entry.value[1]),
type: metricType || 'unknown', // Добавляем тип метрики type: metricType || 'unknown',
})); }));
} }
//Получаем данные всех метрик
async fetchAllMetrics(): Promise<string[]> { async fetchAllMetrics(): Promise<string[]> {
const response = await lastValueFrom( const response = await lastValueFrom(
this.httpService.get(`${this.prometheusUrl}/label/__name__/values`) this.httpService.get(`${this.prometheusUrl}/label/__name__/values`)
); );
return response.data.data; // Это массив с именами метрик return response.data.data;
} }
// Получаем список всех метрик
async fetchAllMetricsWithValues(): Promise<any[]> { async fetchAllMetricsWithValues(): Promise<any[]> {
const metricNames = await this.fetchAllMetrics(); const metricNames = await this.fetchAllMetrics();
const promises = metricNames.map(async (metric) => { const promises = metricNames.map(async (metric) => {
@ -70,4 +64,4 @@ export class PrometheusService {
}); });
return Promise.all(promises); return Promise.all(promises);
} }
} }