-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.module.ts
More file actions
70 lines (68 loc) · 2.42 KB
/
app.module.ts
File metadata and controls
70 lines (68 loc) · 2.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import {
MiddlewareConsumer,
Module,
NestModule,
type NestMiddleware,
Injectable,
} from '@nestjs/common';
import { APP_GUARD } from '@nestjs/core';
import type { Request, Response, NextFunction } from 'express';
import { AwsModule } from './modules/aws.module.js';
import { DiscordModule } from './modules/discord.module.js';
import { ConfigService } from './services/ConfigService.js';
import { GamesController } from './controllers/games.controller.js';
import { ConfigController } from './controllers/config.controller.js';
import { CostsController } from './controllers/costs.controller.js';
import { LogsController } from './controllers/logs.controller.js';
import { FilesController } from './controllers/files.controller.js';
import { DiscordController } from './controllers/discord.controller.js';
import { EnvController } from './controllers/env.controller.js';
import { ApiTokenGuard } from './guards/api-token.guard.js';
import { logger } from './logger.js';
/** Request logger middleware — emits one line per request with status + latency. */
@Injectable()
class RequestLoggerMiddleware implements NestMiddleware {
use(req: Request, res: Response, next: NextFunction): void {
const start = Date.now();
res.on('finish', () => {
const ms = Date.now() - start;
const level = res.statusCode >= 500 ? 'error' : res.statusCode >= 400 ? 'warn' : 'http';
logger.log(level, `${req.method} ${req.path}`, {
status: res.statusCode,
ms,
query: Object.keys(req.query).length ? req.query : undefined,
});
});
next();
}
}
/**
* Root Nest module. Wires the feature modules (`AwsModule`, `DiscordModule`) to
* the HTTP controllers and installs `ApiTokenGuard` as an `APP_GUARD` so every
* `/api/*` route is bearer-token-gated without per-controller opt-in.
*/
@Module({
imports: [AwsModule, DiscordModule],
controllers: [
GamesController,
ConfigController,
CostsController,
LogsController,
FilesController,
DiscordController,
EnvController,
],
providers: [
{
provide: APP_GUARD,
useFactory: (config: ConfigService) => new ApiTokenGuard(config),
inject: [ConfigService],
},
],
})
export class AppModule implements NestModule {
/** Attaches the request logger to every route so each HTTP call emits one structured line. */
configure(consumer: MiddlewareConsumer): void {
consumer.apply(RequestLoggerMiddleware).forRoutes('*');
}
}