#Use ConfigService in @WebSocketGateway decorator

6 messages · Page 1 of 1 (latest)

ashen light
#

Hi,
First time posting here, glad to meet you all.

I was wondering about something. With my team, we are currently using a websocket gateway for the first time and we want to access to an environment variable to configure CORS.

It looks like something like that :

import { config } from '../../config/configuration';

@WebSocketGateway({
  cors: {
    credentials: true,
    methods: ['GET'],
    origin: config.client_base_url,
  },
})
export class EventsGateway implements OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect {

Where config is an export of our custom configuration file :

const configuration = (): CustomConfiguration => ({...})
export const config = configuration();

I would like to know if it is possible to use ConfigService instead of this workaround with configuration file.

Thanks for your help 🙂

upper pivot
#

that EventsGateway is a provider, right?

ashen light
#

Yes, it is

upper pivot
#

thus you can inject providers into it, like any other provider.
I'm not sure if we need to add the @Injectable() decorator to it tho. I bet not

ashen light
#

We're currently using it. I just missed my copy/paste with it 😅

@Injectable()
@WebSocketGateway({
  cors: {
    credentials: true,
    methods: ['GET'],
    origin: configService.get('client_base_url'),
  },
})
export class EventsGateway implements OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect {
  @WebSocketServer()
  server: Server;

  constructor(private readonly configService ConfigService){}
#

You mean it should work with something like this ☝️