nest icon indicating copy to clipboard operation
nest copied to clipboard

Be able to use a random port for the TCP server

Open PieterScheffers opened this issue 1 year ago • 1 comments

In the docs from Node net server:

If port is omitted or is 0, the operating system will assign an arbitrary unused port, which can be retrieved by using server.address().port after the 'listening' event has been emitted.

In the current code 0 is handled as a falsey value, which means the TCP server uses the TCP_DEFAULT_PORT value (3000) instead of letting the OS determine a random port.

Using a random free port is especially handy when running tests.

To get the port I am currently using the following function:

export const getAppTcpAddress = (app: INestMicroservice) => {
  const serverTcp = (app as NestMicroservice)?.['server']
  if (!(serverTcp instanceof ServerTCP)) return null

  const server = serverTcp?.['server']
  if (!(server instanceof Server)) return null

  return server.address()
}

PR Checklist

Please check if your PR fulfills the following requirements:

  • [x] The commit message follows our guidelines: https://github.com/nestjs/nest/blob/master/CONTRIBUTING.md
  • [ ] Tests for the changes have been added (for bug fixes / features)
  • [ ] Docs have been added / updated (for bug fixes / features)

PR Type

What kind of change does this PR introduce?

  • [ ] Bugfix
  • [ ] Feature
  • [ ] Code style update (formatting, local variables)
  • [x] Refactoring (no functional changes, no api changes)
  • [ ] Build related changes
  • [ ] CI related changes
  • [ ] Other... Please describe:

What is the current behavior?

Issue Number: N/A

What is the new behavior?

Does this PR introduce a breaking change?

  • [x] Yes
  • [ ] No

Other information

PieterScheffers avatar Nov 16 '23 10:11 PieterScheffers

Pull Request Test Coverage Report for Build b4a45066-ea2a-4421-90c5-fe0060375bc8

  • 1 of 1 (100.0%) changed or added relevant line in 1 file are covered.
  • No unchanged relevant lines lost coverage.
  • Overall coverage remained the same at 92.26%

Totals Coverage Status
Change from base Build 23ebebfc-1ad4-4b2b-8c07-2691151ef178: 0.0%
Covered Lines: 6687
Relevant Lines: 7248

💛 - Coveralls

coveralls avatar Nov 16 '23 10:11 coveralls