Skip to content

Commit

Permalink
chore: added http exception filter and configured cors
Browse files Browse the repository at this point in the history
  • Loading branch information
jonasexplore committed Jun 19, 2022
1 parent 36312d5 commit 012a32d
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 2 deletions.
20 changes: 20 additions & 0 deletions src/main.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,30 @@
import { HttpException, HttpStatus } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { HttpExceptionFilter } from './modules/http';

async function bootstrap() {
const app = await NestFactory.create(AppModule, {
logger: ['error', 'warn', 'debug', 'verbose', 'log'],
cors: true,
});

app.useGlobalFilters(new HttpExceptionFilter());

const AllowedDomains = process.env.ALLOWED_DOMAINS.split(',') || [];

app.enableCors({
origin: (origin, callback) => {
if (AllowedDomains.includes(origin)) {
callback(null, true);
} else {
callback(
new HttpException('Not allowed by CORS', HttpStatus.BAD_GATEWAY),
);
}
},
});

await app.listen(process.env.PORT || 3333);
}
bootstrap();
19 changes: 17 additions & 2 deletions src/modules/events/events.gateway.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,11 @@
import { CACHE_MANAGER, Inject, Injectable, Logger } from '@nestjs/common';
import {
CACHE_MANAGER,
HttpException,
HttpStatus,
Inject,
Injectable,
Logger,
} from '@nestjs/common';
import {
MessageBody,
WebSocketServer,
Expand All @@ -20,7 +27,15 @@ import {

@WebSocketGateway({
cors: {
origin: '*',
origin: (origin, callback) => {
if ((process.env.ALLOWED_DOMAINS.split(',') || []).includes(origin)) {
callback(null, true);
} else {
callback(
new HttpException('Not allowed by CORS', HttpStatus.BAD_GATEWAY),
);
}
},
},
})
@Injectable()
Expand Down

0 comments on commit 012a32d

Please sign in to comment.