Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 19 additions & 7 deletions libs/bootstrap/src/bootstrap.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Logger } from '@nestjs/common';
import { Logger, VersioningType } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { NestFactory } from '@nestjs/core';
import { setupThrottler } from './setups/throttler';
Expand All @@ -23,7 +23,8 @@ export async function bootstrapApp(options: BootstrapOptions) {

const {
appModule,
apiPrefix = 'api/v1',
apiPrefix,
version = 'v1',
serviceName = 'App',
portEnvKey = 'PORT',
defaultPort = 3000,
Expand Down Expand Up @@ -62,6 +63,15 @@ export async function bootstrapApp(options: BootstrapOptions) {
});

if (apiPrefix) app.setGlobalPrefix(apiPrefix);
if (version) {
const hasV = version.startsWith('v');

app.enableVersioning({
type: VersioningType.URI,
prefix: hasV ? 'v' : '',
defaultVersion: hasV ? version.slice(1) : version,
});
}
if (useCors) setupCors(app, origins);
if (swaggerOptions) {
const { path = 'docs', ...metadata } = swaggerOptions;
Expand Down Expand Up @@ -96,7 +106,11 @@ export async function bootstrapApp(options: BootstrapOptions) {
if (setupApp) setupApp(app);

await app.listen(port, '0.0.0.0', (_err, address) => {
const baseUrl = `${address}${apiPrefix ? '/' + apiPrefix : ''}`;
const prefix = [apiPrefix, version].filter(Boolean).join('/');
const baseUrl = `${address}${prefix ? '/' + prefix : ''}`;

const swaggerBase = `${address}${apiPrefix ? '/' + apiPrefix : ''}`;
const swaggerPath = swaggerOptions?.path ?? 'docs';

if (_err) {
logger.error(_err);
Expand All @@ -107,10 +121,8 @@ export async function bootstrapApp(options: BootstrapOptions) {
logger.verbose(`Environment: ${process.env.NODE_ENV || 'development'}`);
logger.verbose(`API Endpoint: ${baseUrl}`);
logger.verbose(`Health Check: ${baseUrl}/health`);
logger.verbose(`Swagger UI: ${baseUrl}/${swaggerOptions?.path ?? 'docs'}`);
logger.verbose(
`OpenAPI (Specs): ${baseUrl}/${swaggerOptions?.path ?? 'docs'}/s/{json,yaml}`,
);
logger.verbose(`Swagger UI: ${swaggerBase}/${swaggerPath}`);
logger.verbose(`OpenAPI (Specs): ${swaggerBase}/${swaggerPath}/s/{json,yaml}`);
logger.verbose(`Boot Time: ${startupTime}ms`);
});
}
1 change: 1 addition & 0 deletions libs/bootstrap/src/interfaces/options.interface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ export interface SwaggerOptions extends SwaggerMetadata, SwaggerInfrastructure {

export interface BootstrapOptions {
apiPrefix?: string;
version?: string;
appModule: Type<unknown>;
defaultPort?: number;
portEnvKey?: keyof Config;
Expand Down
12 changes: 9 additions & 3 deletions libs/bootstrap/src/setups/swagger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,15 @@ export async function setupSwagger(app: NestFastifyApplication, options: Swagger
.setVersion(version)
.addBearerAuth();

if (port) builder.addServer(`http://localhost:${port}`, 'Local');
if (stage) builder.addServer(`https://api.${stage}`, 'Staging');
if (domain) builder.addServer(`https://api.${domain}`, 'Production');
if ((!stage || !domain) && port) {
builder.addServer(`http://localhost:${port}`, 'Local');
}
if (stage) {
builder.addServer(`https://api.${stage}`, 'Staging');
}
if (domain) {
builder.addServer(`https://api.${domain}`, 'Production');
}

const document = SwaggerModule.createDocument(app, builder.build(), {
extraModels: [GlobalErrorResponse.Output],
Expand Down
2 changes: 1 addition & 1 deletion src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { AppModule } from './modules/app/app.module';
bootstrapApp({
serviceName: 'Tracker Monolit',
appModule: AppModule,
apiPrefix: 'api/v1',
version: 'v1',
defaultPort: 2000,
portEnvKey: 'PORT',
swaggerOptions: {
Expand Down
1 change: 0 additions & 1 deletion src/modules/auth/strategies/cookie.strategy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@ export class CookieStrategy extends PassportStrategy(Strategy, 'cookie') {
}

validate(_req: FastifyRequest, payload: JwtPayload) {
console.log(_req, payload);
if (!payload || !payload.jti) {
throw new BaseException(
{
Expand Down
35 changes: 34 additions & 1 deletion src/shared/error/filter.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,10 @@
import { type ArgumentsHost, Catch, ExceptionFilter, HttpStatus } from '@nestjs/common';
import {
type ArgumentsHost,
Catch,
ExceptionFilter,
HttpException,
HttpStatus,
} from '@nestjs/common';
import { ZodValidationException } from 'nestjs-zod';
import type { FastifyReply, FastifyRequest } from 'fastify';
import { DatabaseError } from 'pg';
Expand All @@ -20,6 +26,10 @@ export class GlobalExceptionFilter implements ExceptionFilter {
return this.parseHttp(exception, host);
}

if (exception instanceof HttpException) {
return this.parseNestHttp(exception, host);
}

if (exception instanceof DrizzleQueryError) {
return this.parseDatabase(exception, host);
}
Expand Down Expand Up @@ -93,6 +103,29 @@ export class GlobalExceptionFilter implements ExceptionFilter {
);
};

private parseNestHttp = async (exception: HttpException, host: ArgumentsHost) => {
const { request, response } = this.getCtxBase(host);
const status = exception.getStatus();
const res = exception.getResponse();

const message =
typeof res === 'object' && res['message'] ? res['message'] : exception.message;

const code =
typeof res === 'object' && res['error']
? res['error'].toUpperCase().replace(/\s+/g, '_')
: 'HTTP_EXCEPTION';

return response.status(status).send(
this.formatErrorResponse(request, status, {
code,
message,
stack: exception.stack,
details: [],
}),
);
};

private handleUnknownError(exception: any, host: ArgumentsHost) {
const { request, response } = this.getCtxBase(host);
const status = HttpStatus.INTERNAL_SERVER_ERROR;
Expand Down
Loading