Skip to content

Commit

Permalink
feat(rest): support controllers added after start
Browse files Browse the repository at this point in the history
A short-term workaround for the missing feature tracked by
#433

Signed-off-by: Miroslav Bajtoš <[email protected]>
  • Loading branch information
bajtos committed Dec 9, 2019
1 parent 38d4601 commit 6ce2228
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 0 deletions.
5 changes: 5 additions & 0 deletions packages/rest/src/rest.application.ts
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,11 @@ export class RestApplication extends Application implements HttpServerLike {
this.restServer.basePath(path);
}

controller<T>(controllerCtor: ControllerClass<T>, name?: string): Binding {
this.restServer.invalidateRoutingCache();
return super.controller(controllerCtor, name);
}

/**
* Register a new Controller-based route.
*
Expand Down
13 changes: 13 additions & 0 deletions packages/rest/src/rest.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -464,6 +464,11 @@ export class RestServer extends Context implements Server, HttpServerLike {
response.redirect(302, fullUrl);
}

// workaround for https://github.com/strongloop/loopback-next/issues/433
invalidateRoutingCache(): void {
delete this._httpHandler;
}

/**
* Register a controller class with this server.
*
Expand All @@ -482,6 +487,9 @@ export class RestServer extends Context implements Server, HttpServerLike {
*
*/
controller(controllerCtor: ControllerClass<ControllerInstance>): Binding {
this.invalidateRoutingCache();
// FIXME(bajtos) This code is never used, a typical LB4 app is binding
// controller via `app.controller()` API
return this.bind('controllers.' + controllerCtor.name).toClass(
controllerCtor,
);
Expand Down Expand Up @@ -564,6 +572,8 @@ export class RestServer extends Context implements Server, HttpServerLike {
controllerFactory?: ControllerFactory<T>,
methodName?: string,
): Binding {
this.invalidateRoutingCache();

if (typeof routeOrVerb === 'object') {
const r = routeOrVerb;
// Encode the path to escape special chars
Expand Down Expand Up @@ -703,6 +713,9 @@ export class RestServer extends Context implements Server, HttpServerLike {
let spec = this.getSync<OpenApiSpec>(RestBindings.API_SPEC);
const defs = this.httpHandler.getApiDefinitions();

// Apply shallow-clone to prevent modification of user-provided API_SPEC
spec = {...spec};

// Apply deep clone to prevent getApiSpec() callers from
// accidentally modifying our internal routing data
spec.paths = cloneDeep(this.httpHandler.describeApiPaths());
Expand Down

0 comments on commit 6ce2228

Please sign in to comment.