Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: allow LB4 app with lifecycle observers to be mounted to Express #3879

Merged
merged 2 commits into from
Oct 7, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 2 additions & 0 deletions examples/express-composition/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ if (require.main === module) {
// useful when used with OpenAPI-to-GraphQL to locate your application
setServersFromRequest: true,
},
// Use the LB4 application as a route. It should not be listening.
listenOnStart: false,
},
};
application.main(config).catch(err => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,10 @@
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT

import {Client} from '@loopback/testlab';
import {setupExpressApplication} from './test-helper';
import {Client, expect} from '@loopback/testlab';
import {HelloObserver} from '../../observers';
import {ExpressServer} from '../../server';
import {setupExpressApplication} from './test-helper';

describe('ExpressApplication', () => {
let server: ExpressServer;
Expand Down Expand Up @@ -58,4 +59,12 @@ describe('ExpressApplication', () => {
.expect(/url\: '\.\/openapi\.json'\,/)
.expect(/<title>LoopBack API Explorer/);
});

it('triggers life cycle start', async () => {
const observer: HelloObserver = await server.lbApp.get(
'lifeCycleObservers.HelloObserver',
);
expect(observer.events.length).to.be.above(0);
expect(observer.events[0]).to.match(/hello-start$/);
});
});
37 changes: 37 additions & 0 deletions examples/express-composition/src/observers/hello.observer.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
// Copyright IBM Corp. 2019. All Rights Reserved.
// Node module: @loopback/example-express-composition
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT

import {
lifeCycleObserver, // The decorator
LifeCycleObserver,
} from '@loopback/core';

/**
* This class will be bound to the application as a `LifeCycleObserver` during
* `boot`
*/
@lifeCycleObserver()
export class HelloObserver implements LifeCycleObserver {
events: string[] = [];
/*
constructor(
@inject(CoreBindings.APPLICATION_INSTANCE) private app: Application,
) {}
*/

/**
* This method will be invoked when the application starts
*/
async start(): Promise<void> {
this.events.push(`${new Date()}: hello-start`);
}

/**
* This method will be invoked when the application stops
*/
async stop(): Promise<void> {
this.events.push(`${new Date()}: hello-stop`);
}
}
6 changes: 6 additions & 0 deletions examples/express-composition/src/observers/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
// Copyright IBM Corp. 2019. All Rights Reserved.
// Node module: @loopback/example-express-composition
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT

export * from './hello.observer';
13 changes: 8 additions & 5 deletions examples/express-composition/src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,18 @@
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT

import {NoteApplication} from './application';
import {ApplicationConfig} from '@loopback/core';
import {Request, Response} from 'express';
import * as express from 'express';
import * as path from 'path';
import pEvent from 'p-event';
import {Request, Response} from 'express';
import * as http from 'http';
import pEvent from 'p-event';
import * as path from 'path';
import {NoteApplication} from './application';

export class ExpressServer {
private app: express.Application;
public readonly lbApp: NoteApplication;
private server: http.Server;
private server?: http.Server;

constructor(options: ApplicationConfig = {}) {
this.app = express();
Expand All @@ -40,6 +40,7 @@ export class ExpressServer {
}

public async start() {
await this.lbApp.start();
const port = this.lbApp.restServer.config.port || 3000;
const host = this.lbApp.restServer.config.host || '127.0.0.1';
this.server = this.app.listen(port, host);
Expand All @@ -49,7 +50,9 @@ export class ExpressServer {
// For testing purposes
public async stop() {
if (!this.server) return;
await this.lbApp.stop();
this.server.close();
await pEvent(this.server, 'close');
this.server = undefined;
}
}
11 changes: 11 additions & 0 deletions packages/rest/src/__tests__/integration/rest.server.integration.ts
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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