Skip to content

Commit

Permalink
feat(rest): add listenOnStart flag to control http listening for a re…
Browse files Browse the repository at this point in the history
…st server

The REST server can be mounted as a route for a facade Express application.
In such cases, we need to tell the REST server not to listen during start().
  • Loading branch information
raymondfeng committed Oct 7, 2019
1 parent 466f79b commit 2c5a131
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 0 deletions.
11 changes: 11 additions & 0 deletions packages/rest/src/__tests__/integration/rest.server.integration.ts
Expand Up @@ -143,6 +143,17 @@ describe('RestServer (integration)', () => {
await server.stop();
});

it('disables listening if noListen is set to true', async () => {
const server = await givenAServer({rest: {listenOnStart: false, port: 0}});
await server.start();
// No port is assigned
expect(server.getSync(RestBindings.PORT)).to.eql(0);
// No server url is set
expect(server.url).to.be.undefined();
expect(server.listening).to.be.false();
await server.stop();
});

it('does not throw an error when stopping an app that has not been started', async () => {
const server = await givenAServer();
await expect(server.stop()).to.fulfilled();
Expand Down
15 changes: 15 additions & 0 deletions packages/rest/src/rest.server.ts
Expand Up @@ -853,6 +853,13 @@ export class RestServer extends Context implements Server, HttpServerLike {
const protocol = await this.get(RestBindings.PROTOCOL);
const httpsOptions = await this.get(RestBindings.HTTPS_OPTIONS);

if (this.config.listenOnStart === false) {
debug(
'RestServer is not listening as listenOnStart flag is set to false.',
);
return;
}

const serverOptions = {};
if (protocol === 'https') Object.assign(serverOptions, httpsOptions);
Object.assign(serverOptions, {port, host, protocol, path});
Expand Down Expand Up @@ -1015,6 +1022,13 @@ export interface RestServerResolvedOptions {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expressSettings: {[name: string]: any};
router: RestRouterOptions;

/**
* Set this flag to `false` to not listen on connections when the REST server
* is started. It's useful to mount a LoopBack REST server as a route to the
* facade Express application. If not set, the value is default to `true`.
*/
listenOnStart?: boolean;
}

/**
Expand All @@ -1039,6 +1053,7 @@ const DEFAULT_CONFIG: RestServerResolvedConfig = {
},
expressSettings: {},
router: {},
listenOnStart: true,
};

function resolveRestServerConfig(
Expand Down

0 comments on commit 2c5a131

Please sign in to comment.