Skip to content
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions docs/site/Routes.md
Original file line number Diff line number Diff line change
Expand Up @@ -201,3 +201,28 @@ class MySequence extends DefaultSequence {
}
}
```

## Implementing HTTP redirects

Both `RestServer` and `RestApplication` classes provide API for registering
routes that will redirect clients to a given URL.

Example use:

{% include code-caption.html content="src/application.ts" %}

```ts
import {RestApplication} from '@loopback/rest';

export class MyApplication extends RestApplication {
constructor(options: ApplicationConfig = {}) {
super(options);

// Use the default status code 303 See Other
this.redirect('/', '/home');

// Specify a custom status code 301 Moved Permanently
this.redirect('/stats', '/status', 301);
}
}
```
Original file line number Diff line number Diff line change
Expand Up @@ -735,6 +735,53 @@ describe('Routing', () => {
.get('/greet/world')
.expect(200, 'HELLO WORLD');
});

it('gives precedence to redirect routes over controller methods', async () => {
class MyController {
@get('/hello', {
responses: {},
})
hello(): string {
return 'hello';
}
@get('/hello/world')
helloWorld() {
return `hello world`;
}
}
const app = givenAnApplication();
const server = await givenAServer(app);
server.basePath('/api');
server.redirect('/test/hello', '/hello/world');
givenControllerInApp(app, MyController);
const response = await whenIMakeRequestTo(server)
.get('/api/test/hello')
.expect(303);
// new request to verify the redirect target
await whenIMakeRequestTo(server)
.get(response.header.location)
.expect(200, 'hello world');
});

it('gives precedence to redirect routes over route methods', async () => {
const app = new RestApplication();
app.route(
'get',
'/greet/{name}',
anOperationSpec()
.withParameter({name: 'name', in: 'path', type: 'string'})
.build(),
(name: string) => `hello ${name}`,
);
app.redirect('/hello/john', '/greet/john');
const response = await whenIMakeRequestTo(app)
.get('/hello/john')
.expect(303);
// new request to verify the redirect target
await whenIMakeRequestTo(app)
.get(response.header.location)
.expect(200, 'hello john');
});
});

/* ===== HELPERS ===== */
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import {anOperationSpec} from '@loopback/openapi-spec-builder';
import {Client, createRestAppClient, expect} from '@loopback/testlab';
import * as fs from 'fs';
import * as path from 'path';
import {RestApplication, RestServer, RestServerConfig} from '../..';
import {RestApplication, RestServer, RestServerConfig, get} from '../..';

const ASSETS = path.resolve(__dirname, '../../../fixtures/assets');

Expand Down Expand Up @@ -145,6 +145,24 @@ describe('RestApplication (integration)', () => {
});
});

it('creates a redirect route with a custom status code', async () => {
givenApplication();

class PingController {
@get('/ping')
ping(): string {
return 'Hi';
}
}
restApp.controller(PingController);

restApp.redirect('/custom/ping', '/ping', 304);
await restApp.start();
client = createRestAppClient(restApp);
const response = await client.get('/custom/ping').expect(304);
await client.get(response.header.location).expect(200, 'Hi');
});

function givenApplication(options?: {rest: RestServerConfig}) {
options = options || {rest: {port: 0, host: '127.0.0.1'}};
restApp = new RestApplication(options);
Expand Down
41 changes: 41 additions & 0 deletions packages/rest/src/__tests__/integration/rest.server.integration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -703,6 +703,30 @@ paths:
await server.stop();
});

it('creates a redirect route with the default status code', async () => {
const server = await givenAServer();
server.controller(DummyController);
server.redirect('/page/html', '/html');
const response = await createClientForHandler(server.requestHandler)
.get('/page/html')
.expect(303);
await createClientForHandler(server.requestHandler)
.get(response.header.location)
.expect(200, 'Hi');
});

it('creates a redirect route with a custom status code', async () => {
const server = await givenAServer();
server.controller(DummyController);
server.redirect('/page/html', '/html', 304);
const response = await createClientForHandler(server.requestHandler)
.get('/page/html')
.expect(304);
await createClientForHandler(server.requestHandler)
.get(response.header.location)
.expect(200, 'Hi');
});

describe('basePath', () => {
const root = ASSETS;
let server: RestServer;
Expand Down Expand Up @@ -751,6 +775,17 @@ paths:
);
expect(response.body.servers).to.containEql({url: '/api'});
});

it('controls redirect locations', async () => {
server.controller(DummyController);
server.redirect('/page/html', '/html');
const response = await createClientForHandler(server.requestHandler)
.get('/api/page/html')
.expect(303);
await createClientForHandler(server.requestHandler)
.get(response.header.location)
.expect(200, 'Hi');
});
});

async function givenAServer(
Expand Down Expand Up @@ -779,6 +814,12 @@ paths:
ping(): string {
return 'Hi';
}
@get('/endpoint', {
responses: {},
})
hello(): string {
return 'hello';
}
}

class DummyXmlController {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
// Copyright IBM Corp. 2017,2018. All Rights Reserved.
// Node module: @loopback/rest
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT

import {expect} from '@loopback/testlab';
import {Application} from '@loopback/core';
import {RestServer, RestComponent} from '../../..';

describe('RestServer.redirect()', () => {
it('binds the redirect route', async () => {
const app = new Application();
app.component(RestComponent);
const server = await app.getServer(RestServer);
server.redirect('/test', '/test/');
let boundRoutes = server.find('routes.*').map(b => b.key);
expect(boundRoutes).to.containEql('routes.get %2Ftest');
});
});
22 changes: 22 additions & 0 deletions packages/rest/src/rest.application.ts
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,28 @@ export class RestApplication extends Application implements HttpServerLike {
}
}

/**
* Register a route redirecting callers to a different URL.
*
* ```ts
* app.redirect('/explorer', '/explorer/');
* ```
*
* @param fromPath URL path of the redirect endpoint
* @param toPathOrUrl Location (URL path or full URL) where to redirect to.
* If your server is configured with a custom `basePath`, then the base path
* is prepended to the target location.
* @param statusCode HTTP status code to respond with,
* defaults to 303 (See Other).
*/
redirect(
fromPath: string,
toPathOrUrl: string,
statusCode?: number,
): Binding {
return this.restServer.redirect(fromPath, toPathOrUrl, statusCode);
}

/**
* Set the OpenAPI specification that defines the REST API schema for this
* application. All routes, parameter definitions and return types will be
Expand Down
25 changes: 25 additions & 0 deletions packages/rest/src/rest.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ import {
RouteEntry,
RoutingTable,
StaticAssetsRoute,
RedirectRoute,
} from './router';
import {DefaultSequence, SequenceFunction, SequenceHandler} from './sequence';
import {
Expand Down Expand Up @@ -666,6 +667,30 @@ export class RestServer extends Context implements Server, HttpServerLike {
);
}

/**
* Register a route redirecting callers to a different URL.
*
* ```ts
* server.redirect('/explorer', '/explorer/');
* ```
*
* @param fromPath URL path of the redirect endpoint
* @param toPathOrUrl Location (URL path or full URL) where to redirect to.
* If your server is configured with a custom `basePath`, then the base path
* is prepended to the target location.
* @param statusCode HTTP status code to respond with,
* defaults to 303 (See Other).
*/
redirect(
fromPath: string,
toPathOrUrl: string,
statusCode?: number,
): Binding {
return this.route(
new RedirectRoute(fromPath, this._basePath + toPathOrUrl, statusCode),
);
}

// The route for static assets
private _staticAssetRoute = new StaticAssetsRoute();

Expand Down
1 change: 1 addition & 0 deletions packages/rest/src/router/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ export * from './base-route';
export * from './controller-route';
export * from './handler-route';
export * from './static-assets-route';
export * from './redirect-route';

// routers
export * from './rest-router';
Expand Down
42 changes: 42 additions & 0 deletions packages/rest/src/router/redirect-route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import {RouteEntry, ResolvedRoute} from '.';
import {RequestContext} from '../request-context';
import {OperationObject, SchemasObject} from '@loopback/openapi-v3-types';
import {OperationArgs, OperationRetval, PathParameterValues} from '../types';

export class RedirectRoute implements RouteEntry, ResolvedRoute {
// ResolvedRoute API
readonly pathParams: PathParameterValues = [];
readonly schemas: SchemasObject = {};

// RouteEntry implementation
readonly verb: string = 'get';
readonly path: string = this.sourcePath;
readonly spec: OperationObject = {
description: 'LoopBack Redirect route',
'x-visibility': 'undocumented',
responses: {},
};

constructor(
private readonly sourcePath: string,
private readonly targetLocation: string,
private readonly statusCode: number = 303,
) {}

async invokeHandler(
{response}: RequestContext,
args: OperationArgs,
): Promise<OperationRetval> {
response.redirect(this.statusCode, this.targetLocation);
}

updateBindings(requestContext: RequestContext) {
// no-op
}

describe(): string {
return `RedirectRoute from "${this.sourcePath}" to "${
this.targetLocation
}"`;
}
}