Skip to content

Commit 2c5a131

Browse files
committed
feat(rest): add listenOnStart flag to control http listening for a rest 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().
1 parent 466f79b commit 2c5a131

File tree

2 files changed

+26
-0
lines changed

2 files changed

+26
-0
lines changed

packages/rest/src/__tests__/integration/rest.server.integration.ts

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -143,6 +143,17 @@ describe('RestServer (integration)', () => {
143143
await server.stop();
144144
});
145145

146+
it('disables listening if noListen is set to true', async () => {
147+
const server = await givenAServer({rest: {listenOnStart: false, port: 0}});
148+
await server.start();
149+
// No port is assigned
150+
expect(server.getSync(RestBindings.PORT)).to.eql(0);
151+
// No server url is set
152+
expect(server.url).to.be.undefined();
153+
expect(server.listening).to.be.false();
154+
await server.stop();
155+
});
156+
146157
it('does not throw an error when stopping an app that has not been started', async () => {
147158
const server = await givenAServer();
148159
await expect(server.stop()).to.fulfilled();

packages/rest/src/rest.server.ts

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -853,6 +853,13 @@ export class RestServer extends Context implements Server, HttpServerLike {
853853
const protocol = await this.get(RestBindings.PROTOCOL);
854854
const httpsOptions = await this.get(RestBindings.HTTPS_OPTIONS);
855855

856+
if (this.config.listenOnStart === false) {
857+
debug(
858+
'RestServer is not listening as listenOnStart flag is set to false.',
859+
);
860+
return;
861+
}
862+
856863
const serverOptions = {};
857864
if (protocol === 'https') Object.assign(serverOptions, httpsOptions);
858865
Object.assign(serverOptions, {port, host, protocol, path});
@@ -1015,6 +1022,13 @@ export interface RestServerResolvedOptions {
10151022
// eslint-disable-next-line @typescript-eslint/no-explicit-any
10161023
expressSettings: {[name: string]: any};
10171024
router: RestRouterOptions;
1025+
1026+
/**
1027+
* Set this flag to `false` to not listen on connections when the REST server
1028+
* is started. It's useful to mount a LoopBack REST server as a route to the
1029+
* facade Express application. If not set, the value is default to `true`.
1030+
*/
1031+
listenOnStart?: boolean;
10181032
}
10191033

10201034
/**
@@ -1039,6 +1053,7 @@ const DEFAULT_CONFIG: RestServerResolvedConfig = {
10391053
},
10401054
expressSettings: {},
10411055
router: {},
1056+
listenOnStart: true,
10421057
};
10431058

10441059
function resolveRestServerConfig(

0 commit comments

Comments
 (0)