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(rest): add redirect route #2314

Closed
wants to merge 2 commits into from
Closed
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
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);
bajtos marked this conversation as resolved.
Show resolved Hide resolved
// 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,8 +145,28 @@ describe('RestApplication (integration)', () => {
});
});

it('can app redirect routes with custom status', async () => {
givenApplication();
restApp.controller(DummyController);
restApp.redirect('/fake/html', '/html', 304);
await restApp.start();
client = createRestAppClient(restApp);
const response = await client.get('/fake/html').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);
}
});

class DummyController {
constructor() {}
@get('/html', {
responses: {},
})
ping(): string {
return 'Hi';
}
}
39 changes: 39 additions & 0 deletions packages/rest/src/__tests__/integration/rest.server.integration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -735,6 +735,39 @@ paths:
);
expect(response.body.servers).to.containEql({url: '/api'});
});

it('can redirect routes when it does not exist', 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');
});

it('can redirect routes', async () => {
server.controller(DummyController);
server.redirect('/hello', '/endpoint');
const response = await createClientForHandler(server.requestHandler)
.get('/api/hello')
.expect(303);
await createClientForHandler(server.requestHandler)
.get(response.header.location)
.expect(200, 'hello');
});

it('can server redirect routes with custom status', async () => {
server.controller(DummyController);
server.redirect('/hello', '/endpoint', 304);
const response = await createClientForHandler(server.requestHandler)
.get('/api/hello')
.expect(304);
await createClientForHandler(server.requestHandler)
.get(response.header.location)
.expect(200, 'hello');
});
});

async function givenAServer(
Expand Down Expand Up @@ -763,6 +796,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');
});
});
14 changes: 14 additions & 0 deletions packages/rest/src/rest.application.ts
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,20 @@ export class RestApplication extends Application implements HttpServerLike {
}
}

/**
* Redirect route by invoking a handler function.
*
* ```ts
* app.redirect('/explorer', '/explorer/');
* ```
*
* @param source URL path of the redirect endpoint
* @param target URL path of the endpoint
*/
redirect(source: string, target: string, statusCode?: number): Binding {
return this.restServer.redirect(source, target, 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
17 changes: 17 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 @@ -629,6 +630,22 @@ export class RestServer extends Context implements Server, HttpServerLike {
);
}

/**
* Redirect route by invoking a handler function.
*
* ```ts
* server.redirect('/explorer', '/explorer/');
* ```
*
* @param source URL path of the redirect endpoint
* @param target URL path of the endpoint
*/
redirect(source: string, target: string, statusCode?: number): Binding {
return this.route(
new RedirectRoute(source, this._basePath + target, 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(
public readonly sourcePath: string,
public targetPath: string,
public statusCode: number = 303,
This conversation was marked as resolved.
Show resolved Hide resolved
) {
this.sourcePath = sourcePath;
}

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

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

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