Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 | 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 316x 316x 11x 132x 11x | import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import * as Joi from 'joi';
import { Request, Response } from 'express';
import { LoggerModule } from 'nestjs-pino';
import { GraphQLModule } from '@nestjs/graphql';
import { ApolloDriver, ApolloDriverConfig } from '@nestjs/apollo';
import { join } from 'path';
import depthLimit from 'graphql-depth-limit';
import { PrismaModule } from '@app/modules/prisma/prisma.module';
import { UsersModule } from '@app/modules/users/users.module';
import { ListingsModule } from '@app/modules/listings/listings.module';
import { SearchModule } from '@app/modules/search/search.module';
import { AuthModule } from '@app/modules/auth/auth.module';
import { ThrottlerModule, ThrottlerModuleOptions, ThrottlerStorage } from '@nestjs/throttler';
import { APP_GUARD, Reflector, APP_INTERCEPTOR } from '@nestjs/core';
import { ThrottlerLoggerGuard } from '@app/common/guards/throttler-logger.guard';
import { ThrottlerStorageRedisService } from '@nest-lab/throttler-storage-redis';
import { LoggerService } from '@app/common/services/logger.service';
// import Redis from 'ioredis';
import { AuditModule } from '@app/modules/audit/audit.module';
import { CacheModule } from '@nestjs/cache-manager';
// import { GqlAuthGuard } from '@app/common/guards/gql-auth.guard';
// import { JwtAuthGuard } from '@app/common/guards/jwt-auth.guard';
import { AgenciesModule } from '@app/modules/agencies/agencies.module';
import { AdminModule } from '@app/modules/admin/admin.module';
import { FiltersModule } from '@app/modules/filters/filters.module';
import { PrometheusModule } from '@willsoto/nestjs-prometheus';
import { MetricsInterceptor } from '@app/common/interceptors/metrics.interceptor';
import { IdempotencyInterceptor } from '@app/common/interceptors/idempotency.interceptor';
// import { GqlHttpExceptionFilter } from '@app/common/filters/gql-exception.filter';
import { HealthModule } from '@app/modules/health/health.module';
import { MediaModule } from '@app/modules/media/media.module';
import { BullMetricsService } from '@app/metrics/bullmq.metrics';
import { BullModule } from '@nestjs/bullmq';
import { ConfigService } from '@nestjs/config';
import { OpenHouseModule } from '@app/modules/open-houses/open-house.module';
import { BoostModule } from '@app/modules/boost/boost.module';
import { DevelopersModule } from '@app/modules/developers/developers.module';
import { JwksModule } from '@app/modules/jwks/jwks.module';
import { AuditInterceptor } from '@app/common/interceptors/audit.interceptor';
import { NullQueue } from '@app/utils/null-queue';
import { BullShutdownService } from '@app/common/services/bull-shutdown.service';
import { BillingModule } from '@app/modules/billing/billing.module';
import { QuickRentModule } from '@app/modules/quick-rent/quick-rent.module';
import { MortgagesModule } from '@app/modules/mortgages/mortgages.module';
import { PromotionsModule } from '@app/modules/promotions/promotions.module';
import { LeadsModule } from '@app/modules/leads/leads.module';
import { AnalyticsModule } from '@app/modules/analytics/analytics.module';
import { MessagingModule } from '@app/modules/messaging/messaging.module';
import { NotificationsModule } from '@app/modules/notifications/notifications.module';
const isDocsMode = process.env.SKIP_DB === '1';
const IS_TEST = process.env.NODE_ENV === 'test' || process.env.TEST_MODE === '1';
// These modules have dependencies on DB, Redis, ES, etc. and should be disabled in DOCS_MODE
const dynamicModules = [
PrismaModule,
UsersModule,
ListingsModule,
SearchModule,
AuthModule,
MediaModule,
AuditModule,
AgenciesModule,
AdminModule,
FiltersModule,
HealthModule,
// Exclude BoostModule during tests to avoid Bull workers
...(!IS_TEST ? [BoostModule] : []),
OpenHouseModule,
JwksModule,
// Disable Throttler entirely in tests to avoid 429s and flakiness
...(!IS_TEST
? [
ThrottlerModule.forRootAsync({
useFactory: () => ({
throttlers: [
{ name: 'strict', ttl: +process.env.RATE_LIMIT_TTL_STRICT! || 60000, limit: +process.env.RATE_LIMIT_LIMIT_STRICT! || 5 },
{ name: 'general', ttl: +process.env.RATE_LIMIT_TTL_GENERAL! || 60000, limit: +process.env.RATE_LIMIT_LIMIT_GENERAL! || 100 },
],
storage: new ThrottlerStorageRedisService(process.env.REDIS_URL!),
}),
}),
]
: []),
...(!IS_TEST
? [
PrometheusModule.register({
path: '/metrics',
defaultMetrics: { enabled: true },
}),
]
: []),
...(!IS_TEST
? [
BullModule.registerQueue(
{ name: 'listingIndex' },
{ name: 'media' },
{ name: 'media-gc' },
{ name: 'boost-expiry' },
{ name: 'listings-bulk-import' },
{ name: 'saved-search-alerts' },
),
]
: []),
];
@Module({
imports: [
// ────── ENV ────────────────────────────────────────────────
ConfigModule.forRoot({
// GLOBAL because sharing is caring ❤️
isGlobal: true,
envFilePath: ['.env', '.env.local'],
validationSchema: Joi.object({
NODE_ENV : Joi.string().valid('development', 'production', 'test').default('development'),
PORT : Joi.number().default(3000),
DATABASE_URL: Joi.string().uri().required().custom((value: string, _helpers: any) => {
// Enforce SSL mode for production
Iif (process.env.NODE_ENV === 'production' && !value.includes('sslmode=require')) {
// For postgres:// URLs, add sslmode=require if not present
Iif (value.startsWith('postgres://') || value.startsWith('postgresql://')) {
const url = new URL(value);
url.searchParams.set('sslmode', 'require');
return url.toString();
}
// For other formats, warn but don't fail validation
console.warn('[DATABASE_URL] Production environment should use sslmode=require');
}
return value;
}).messages({
'any.required': '🚨 DATABASE_URL is fucking mandatory!',
}),
REDIS_URL : Joi.string().uri().required(),
ELASTICSEARCH_NODE: Joi.string().uri().required(),
// ────── MEDIA STORAGE ──────────
R2_BUCKET: Joi.string().required(),
R2_REGION: Joi.string().required(),
R2_ACCESS_KEY_ID: Joi.string().required(),
R2_SECRET_ACCESS_KEY: Joi.string().required(),
// Optional Cloudflare R2 compatible endpoint
R2_ENDPOINT: Joi.string().uri().optional(),
// R2 signing configuration
R2_SIGNING_ENABLED: Joi.boolean().truthy('1', 'true').falsy('0', 'false').default(true),
// Media retention (days before soft-deleted media is permanently deleted)
MEDIA_RETENTION_DAYS: Joi.number().integer().min(1).default(30),
FRONTEND_URL: Joi.string().uri().required(),
LOG_LEVEL: Joi.string().valid('error', 'warn', 'info', 'debug', 'trace').default('info'),
// Upload limits (bytes)
UPLOAD_MAX_FILE_BYTES: Joi.number().integer().min(1024).default(50 * 1024 * 1024),
UPLOAD_MAX_FIELD_BYTES: Joi.number().integer().min(1024).default(10 * 1024 * 1024),
// Feature flags (default false)
BILLING_ENABLED : Joi.boolean().truthy('1', 'true').falsy('0', 'false').default(false),
QUICK_RENT_ENABLED: Joi.boolean().truthy('1', 'true').falsy('0', 'false').default(false),
MORTGAGE_ENABLED : Joi.boolean().truthy('1', 'true').falsy('0', 'false').default(false),
PROMOS_ENABLED : Joi.boolean().truthy('1', 'true').falsy('0', 'false').default(false),
// CLICK payment (optional)
CLICK_MERCHANT_ID : Joi.string().optional(),
CLICK_MERCHANT_SERVICE_ID: Joi.string().optional(),
CLICK_SECRET_KEY : Joi.string().optional(),
JWKS_KEYS: Joi.when('NODE_ENV', {
is: 'production',
then: Joi.string().min(1).required().messages({
'any.required': 'JWKS_KEYS base64 JSON is required in production. Set the env var or mount a secret.',
}),
otherwise: Joi.string().allow('').optional(),
}),
JWKS_KEYS_FILE: Joi.string().optional(),
JWKS_CURRENT_KID: Joi.string().optional(),
JWKS_REMOTE_URL: Joi.string().uri().optional(),
JWKS_REMOTE_TTL_MS: Joi.number().integer().min(60000).optional(),
// JWT signing/verification (required in production)
JWT_PRIVATE_KEY: Joi.when('NODE_ENV', {
is: 'production',
then: Joi.string().min(1).required(),
otherwise: Joi.string().allow('').optional(),
}),
JWT_PUBLIC_KEY: Joi.when('NODE_ENV', {
is: 'production',
then: Joi.string().min(1).required(),
otherwise: Joi.string().allow('').optional(),
}),
JWT_ISSUER: Joi.when('NODE_ENV', {
is: 'production',
then: Joi.string().min(1).required(),
otherwise: Joi.string().allow('').optional(),
}),
JWT_AUDIENCE: Joi.when('NODE_ENV', {
is: 'production',
then: Joi.string().min(1).required(),
otherwise: Joi.string().allow('').optional(),
}),
JWT_ALGORITHM: Joi.string().valid('RS256').default('RS256'),
// JWT_SECRET can be kept for fallback but not required
JWT_SECRET: Joi.string().min(32).optional(),
}),
}),
// ────── GRAPHQL ────────────────────────────────────────────
GraphQLModule.forRoot<ApolloDriverConfig>({
driver : ApolloDriver,
autoSchemaFile: join(process.cwd(), 'src/schema.gql'),
sortSchema : true,
playground : process.env.NODE_ENV !== 'production',
introspection : process.env.NODE_ENV !== 'production',
validationRules: [depthLimit(10)],
// context is required by the AuthGuard later
context: ({ req, res }: { req: Request; res: Response }) => ({ req, res }),
}),
// ────── DOMAIN MODULES ─────────────────────────────────────
CacheModule.register({ isGlobal: true, ttl: 60 }),
LoggerModule.forRoot({
pinoHttp:
process.env.NODE_ENV === 'production'
? {
level: 'warn',
redact: ['req.headers.authorization', 'req.body.password', '*.token'],
serializers: {
req(req: any) {
return {
id: req.id,
method: req.method,
url: req.url,
};
},
res(res: any) {
return {
statusCode: res.statusCode,
bytes: res.getHeader ? res.getHeader('content-length') : undefined,
};
},
},
}
: {
level: process.env.NODE_ENV === 'test' ? 'warn' : 'debug',
redact: ['req.headers.authorization', 'req.body.password', '*.token'],
// Avoid pretty transport in tests to eliminate potential open handles
...(process.env.NODE_ENV === 'test'
? {}
: {
transport: {
target: 'pino-pretty',
options: {
colorize: true,
translateTime: 'HH:MM:ss',
ignore: 'pid,hostname,context,req.headers,req.body,password',
},
},
}),
serializers: {
req(req: any) {
// Sample noisy health checks
Iif (req.url === '/health' && Math.random() > 0.05) {
req.log.level = 'debug';
}
return {
id: req.id,
method: req.method,
url: req.url,
};
},
res(res: any) {
return {
statusCode: res.statusCode,
bytes: res.getHeader ? res.getHeader('content-length') : undefined,
};
},
},
},
}),
// Conditionally import modules that require DB/Redis/etc.
...(!isDocsMode ? dynamicModules : []),
// Global BullMQ configuration (prod/dev only). Use resilient connection settings
...(!isDocsMode && !IS_TEST
? [
BullModule.forRootAsync({
inject: [ConfigService],
useFactory: (config: ConfigService) => {
const redisUrl = config.get<string>('REDIS_URL');
const url = new URL(redisUrl!);
const host = url.hostname;
const port = parseInt(url.port || '6379', 10);
const password = url.password || undefined;
return {
connection: {
host,
port,
password,
// Resilience: don't block startup; connect lazily and limit retries
lazyConnect: true as any,
maxRetriesPerRequest: null, // Explicitly set to null to fix deprecation warning
retryStrategy: (times: number) => (times > 3 ? null : Math.min(times * 200, 2000)),
enableOfflineQueue: false as any,
} as any,
};
},
}),
]
: []),
// Optional feature modules (gated by env flags)
...(!isDocsMode && process.env.BILLING_ENABLED === '1' ? [BillingModule] : []),
...(!isDocsMode && process.env.QUICK_RENT_ENABLED === '1' ? [QuickRentModule] : []),
...(!isDocsMode && process.env.MORTGAGE_ENABLED === '1' ? [MortgagesModule] : []),
...(!isDocsMode && process.env.PROMOS_ENABLED === '1' ? [PromotionsModule] : []),
// Developers/projects public directory/search is safe to load; CRUD guarded inside
...(!isDocsMode ? [DevelopersModule] : []),
LeadsModule,
AnalyticsModule,
MessagingModule,
NotificationsModule,
// Avoid Bull queue registration during tests to prevent workers/Redis connections
...(!IS_TEST
? [
BullModule.registerQueue(
{ name: 'quick-rent:payment-window-expired' },
{ name: 'notifications' },
{ name: 'analytics:daily' },
),
]
: []),
],
providers: [
// HTTP metrics interceptor – because we ♥ charts
{
provide: APP_INTERCEPTOR,
useClass: MetricsInterceptor,
},
// Idempotency for write endpoints
{
provide: APP_INTERCEPTOR,
useClass: IdempotencyInterceptor,
},
// Declarative audit logs interceptor
{
provide: APP_INTERCEPTOR,
useClass: AuditInterceptor,
},
// GraphQL exception filter should not handle HTTP; register within GQL context only.
...([]),
// Conditionally provide services that require DB/Redis/etc.
...(!isDocsMode
? [
{
provide: 'THROTTLER_OPTIONS',
useFactory: () => ({
throttlers: [
{
name: 'strict',
ttl: parseInt(process.env.RATE_LIMIT_TTL_STRICT || '60000', 10),
limit: parseInt(process.env.RATE_LIMIT_LIMIT_STRICT || '5', 10),
},
{
name: 'general',
ttl: parseInt(process.env.RATE_LIMIT_TTL_GENERAL || '60000', 10),
limit: parseInt(process.env.RATE_LIMIT_LIMIT_GENERAL || '100', 10),
},
],
}),
},
// Use Redis-backed throttler guard in prod/dev, but standard in-memory guard for tests
...(!IS_TEST
? [
{
provide: 'THROTTLER_STORAGE',
useFactory: () => new ThrottlerStorageRedisService(process.env.REDIS_URL!),
},
{
provide: APP_GUARD,
useFactory: (
options: ThrottlerModuleOptions,
storage: ThrottlerStorage,
reflector: Reflector,
logger: LoggerService,
) => new ThrottlerLoggerGuard(options, storage, reflector, logger),
inject: [
'THROTTLER_OPTIONS',
'THROTTLER_STORAGE',
Reflector,
LoggerService,
],
},
]
: []),
// Note: RolesGuard is applied per-route via @UseGuards to preserve guard order (auth before roles)
// ────── TEST ENV OVERRIDES ─────────────────────────────────┐
...(
process.env.NODE_ENV === 'test'
? [
'listingIndex',
'media',
'media-gc',
'boost-expiry',
'notifications',
'analytics:daily',
'billing:dunning',
'quick-rent:match',
'quick-rent:end-bid-window',
'quick-rent:collect-payment',
'quick-rent:reminders',
'quick-rent:payment-window-expired',
].map((name) => ({
provide: `BullQueue_${name}`,
useClass: NullQueue,
}))
: []
),
// Queue lag gauge service & graceful shutdown
BullShutdownService, // Always provide shutdown service for proper cleanup
...(process.env.NODE_ENV !== 'test' ? [BullMetricsService] : []),
]
: []),
],
})
export class AppModule {} |