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

refactor(rest): introduce RequestContext #1316

Merged
merged 2 commits into from
May 15, 2018
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
1 change: 1 addition & 0 deletions .prettierignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,6 @@ packages/cli/generators/*/templates
packages/cli/test/integration/.sandbox
packages/*/dist*
examples/*/dist*
sandbox/**/dist*
*.json
*.md
24 changes: 12 additions & 12 deletions docs/site/Sequence.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,14 +24,14 @@ instances handle requests and responses. The `DefaultSequence` looks like this:

```ts
class DefaultSequence {
async handle(request: ParsedRequest, response: ServerResponse) {
async handle(context: RequestContext) {
try {
const route = this.findRoute(request);
const params = await this.parseParams(request, route);
const route = this.findRoute(context.request);
const params = await this.parseParams(context.request, route);
const result = await this.invoke(route, params);
await this.send(response, result);
} catch (err) {
await this.reject(response, err);
await this.send(context.response, result);
} catch (error) {
await this.reject(context, error);
}
}
}
Expand Down Expand Up @@ -61,15 +61,15 @@ Actions:

```ts
class MySequence extends DefaultSequence {
async handle(request: ParsedRequest, response: ServerResponse) {
async handle(context: RequestContext) {
// findRoute() produces an element
const route = this.findRoute(request);
const route = this.findRoute(context.request);
// parseParams() uses the route element and produces the params element
const params = await this.parseParams(request, route);
const params = await this.parseParams(context.request, route);
// invoke() uses both the route and params elements to produce the result (OperationRetVal) element
const result = await this.invoke(route, params);
// send() uses the result element
await this.send(response, result);
await this.send(context.response, result);
}
}
```
Expand All @@ -91,9 +91,9 @@ class MySequence extends DefaultSequence {
log(msg: string) {
console.log(msg);
}
async handle(request: ParsedRequest, response: ServerResponse) {
async handle(context: RequestContext) {
this.log('before request');
await super.handle(request, response);
await super.handle(context);
this.log('after request');
}
}
Expand Down
2 changes: 1 addition & 1 deletion examples/hello-world/src/application.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ export class HelloWorldApplication extends RestApplication {
// returns the same HTTP response: Hello World!
// Learn more about the concept of Sequence in our docs:
// http://loopback.io/doc/en/lb4/Sequence.html
this.handler((sequence, request, response) => {
this.handler(({response}, sequence) => {
sequence.send(response, 'Hello World!');
});
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,7 @@ import {
InvokeMethod,
Send,
Reject,
ParsedRequest,
ServerResponse,
RequestContext,
} from '@loopback/rest';
import {get, param} from '@loopback/openapi-v3';
import {
Expand All @@ -31,7 +30,7 @@ import {
createClientForHandler,
expect,
} from '@loopback/testlab';
import {Context, inject} from '@loopback/context';
import {inject} from '@loopback/context';
import chalk from 'chalk';

const SequenceActions = RestBindings.SequenceActions;
Expand Down Expand Up @@ -204,7 +203,6 @@ describe('log extension acceptance test', () => {
function createSequence() {
class LogSequence implements SequenceHandler {
constructor(
@inject(RestBindings.Http.CONTEXT) public ctx: Context,
@inject(SequenceActions.FIND_ROUTE) protected findRoute: FindRoute,
@inject(SequenceActions.PARSE_PARAMS)
protected parseParams: ParseParams,
Expand All @@ -214,23 +212,25 @@ describe('log extension acceptance test', () => {
@inject(EXAMPLE_LOG_BINDINGS.LOG_ACTION) protected logger: LogFn,
) {}

async handle(req: ParsedRequest, res: ServerResponse) {
async handle(context: RequestContext): Promise<void> {
const {request, response} = context;

// tslint:disable-next-line:no-any
let args: any = [];
// tslint:disable-next-line:no-any
let result: any;

try {
const route = this.findRoute(req);
args = await this.parseParams(req, route);
const route = this.findRoute(request);
args = await this.parseParams(request, route);
result = await this.invoke(route, args);
this.send(res, result);
} catch (err) {
this.reject(res, req, err);
result = err;
this.send(response, result);
} catch (error) {
this.reject(context, error);
result = error;
}

await this.logger(req, args, result);
await this.logger(request, args, result);
}
}

Expand Down
16 changes: 8 additions & 8 deletions examples/todo/src/sequence.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,13 @@ import {Context, inject} from '@loopback/context';
import {
FindRoute,
InvokeMethod,
ParsedRequest,
ParseParams,
Reject,
RequestContext,
RestBindings,
Send,
SequenceHandler,
} from '@loopback/rest';
import {ServerResponse} from 'http';

const SequenceActions = RestBindings.SequenceActions;

Expand All @@ -28,14 +27,15 @@ export class MySequence implements SequenceHandler {
@inject(SequenceActions.REJECT) public reject: Reject,
) {}

async handle(req: ParsedRequest, res: ServerResponse) {
async handle(context: RequestContext) {
try {
const route = this.findRoute(req);
const args = await this.parseParams(req, route);
const {request, response} = context;
const route = this.findRoute(request);
const args = await this.parseParams(request, route);
const result = await this.invoke(route, args);
this.send(res, result);
} catch (err) {
this.reject(res, req, err);
this.send(response, result);
} catch (error) {
this.reject(context, error);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,6 @@
import {Application} from '@loopback/core';
import {
RestBindings,
ServerResponse,
ParsedRequest,
ParseParams,
FindRoute,
InvokeMethod,
Expand All @@ -16,6 +14,7 @@ import {
SequenceHandler,
RestServer,
RestComponent,
RequestContext,
} from '@loopback/rest';
import {api, get} from '@loopback/openapi-v3';
import {Client, createClientForHandler} from '@loopback/testlab';
Expand Down Expand Up @@ -137,19 +136,20 @@ describe('Basic Authentication', () => {
protected authenticateRequest: AuthenticateFn,
) {}

async handle(req: ParsedRequest, res: ServerResponse) {
async handle(context: RequestContext) {
try {
const route = this.findRoute(req);
const {request, response} = context;
const route = this.findRoute(request);

// Authenticate
await this.authenticateRequest(req);
await this.authenticateRequest(request);

// Authentication successful, proceed to invoke controller
const args = await this.parseParams(req, route);
const args = await this.parseParams(request, route);
const result = await this.invoke(route, args);
this.send(res, result);
} catch (err) {
this.reject(res, req, err);
this.send(response, result);
} catch (error) {
this.reject(context, error);
return;
}
}
Expand Down
17 changes: 8 additions & 9 deletions packages/cli/generators/app/templates/src/sequence.ts.ejs
Original file line number Diff line number Diff line change
@@ -1,36 +1,35 @@
import {Context, inject} from '@loopback/context';
import {inject} from '@loopback/context';
import {
FindRoute,
InvokeMethod,
ParsedRequest,
ParseParams,
Reject,
RequestContext,
RestBindings,
Send,
SequenceHandler,
} from '@loopback/rest';
import {ServerResponse} from 'http';

const SequenceActions = RestBindings.SequenceActions;

export class MySequence implements SequenceHandler {
constructor(
@inject(RestBindings.Http.CONTEXT) public ctx: Context,
@inject(SequenceActions.FIND_ROUTE) protected findRoute: FindRoute,
@inject(SequenceActions.PARSE_PARAMS) protected parseParams: ParseParams,
@inject(SequenceActions.INVOKE_METHOD) protected invoke: InvokeMethod,
@inject(SequenceActions.SEND) public send: Send,
@inject(SequenceActions.REJECT) public reject: Reject,
) {}

async handle(req: ParsedRequest, res: ServerResponse) {
async handle(context: RequestContext) {
try {
const route = this.findRoute(req);
const args = await this.parseParams(req, route);
const {request, response} = context;
const route = this.findRoute(request);
const args = await this.parseParams(request, route);
const result = await this.invoke(route, args);
this.send(res, result);
this.send(response, result);
} catch (err) {
this.reject(res, req, err);
this.reject(context, err);
}
}
}
2 changes: 1 addition & 1 deletion packages/rest/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ Here's a basic "Hello World" application using `@loopback/rest`:
import {RestApplication, RestServer} from '@loopback/rest';

const app = new RestApplication();
app.handler((sequence, request, response) => {
app.handler(({request, response}, sequence) => {
sequence.send(response, 'hello world');
});

Expand Down
2 changes: 1 addition & 1 deletion packages/rest/docs.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"index.ts",
"src/http-handler.ts",
"src/index.ts",
"src/internal-types.ts",
"src/types.ts",
"src/keys.ts",
"src/parser.ts",
"src/rest.application.ts",
Expand Down
22 changes: 8 additions & 14 deletions packages/rest/src/http-handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,10 @@ import {
ControllerClass,
ControllerFactory,
} from './router/routing-table';
import {ParsedRequest} from './internal-types';
import {ParsedRequest} from './types';

import {RestBindings} from './keys';
import {RequestContext} from './request-context';

export class HttpHandler {
protected _routes: RoutingTable = new RoutingTable();
Expand Down Expand Up @@ -67,22 +68,15 @@ export class HttpHandler {
response: ServerResponse,
): Promise<void> {
const parsedRequest: ParsedRequest = parseRequestUrl(request);
const requestContext = this._createRequestContext(parsedRequest, response);
const requestContext = new RequestContext(
parsedRequest,
response,
this._rootContext,
);

const sequence = await requestContext.get<SequenceHandler>(
RestBindings.SEQUENCE,
);
await sequence.handle(parsedRequest, response);
}

protected _createRequestContext(
req: ParsedRequest,
res: ServerResponse,
): Context {
const requestContext = new Context(this._rootContext);
requestContext.bind(RestBindings.Http.REQUEST).to(req);
requestContext.bind(RestBindings.Http.RESPONSE).to(res);
requestContext.bind(RestBindings.Http.CONTEXT).to(requestContext);
return requestContext;
await sequence.handle(requestContext);
}
}
3 changes: 2 additions & 1 deletion packages/rest/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,8 @@ export {writeResultToResponse} from './writer';
export {HttpErrors};

export * from './http-handler';
export * from './internal-types';
export * from './request-context';
export * from './types';
export * from './keys';
export * from './rest.application';
export * from './rest.component';
Expand Down
2 changes: 1 addition & 1 deletion packages/rest/src/keys.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import {
ParseParams,
Reject,
Send,
} from './internal-types';
} from './types';

// NOTE(bajtos) The following import is required to satisfy TypeScript compiler
// tslint:disable-next-line:no-unused-variable
Expand Down
6 changes: 1 addition & 5 deletions packages/rest/src/parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,7 @@ import {
} from '@loopback/openapi-v3-types';
import {REQUEST_BODY_INDEX} from '@loopback/openapi-v3';
import {promisify} from 'util';
import {
OperationArgs,
ParsedRequest,
PathParameterValues,
} from './internal-types';
import {OperationArgs, ParsedRequest, PathParameterValues} from './types';
import {ResolvedRoute} from './router/routing-table';
type HttpError = HttpErrors.HttpError;

Expand Down
2 changes: 1 addition & 1 deletion packages/rest/src/providers/bind-element.provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
// License text available at https://opensource.org/licenses/MIT

import {Context, inject, Provider, Binding} from '@loopback/context';
import {BindElement} from '../internal-types';
import {BindElement} from '../types';
import {RestBindings} from '../keys';

export class BindElementProvider implements Provider<BindElement> {
Expand Down
3 changes: 1 addition & 2 deletions packages/rest/src/providers/find-route.provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,9 @@
// License text available at https://opensource.org/licenses/MIT

import {Context, inject, Provider} from '@loopback/context';
import {FindRoute} from '../internal-types';
import {FindRoute, ParsedRequest} from '../types';
import {HttpHandler} from '../http-handler';
import {RestBindings} from '../keys';
import {ParsedRequest} from '../internal-types';
import {ResolvedRoute} from '../router/routing-table';

export class FindRouteProvider implements Provider<FindRoute> {
Expand Down
2 changes: 1 addition & 1 deletion packages/rest/src/providers/get-from-context.provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
// License text available at https://opensource.org/licenses/MIT

import {Context, inject, Provider, BoundValue} from '@loopback/context';
import {GetFromContext} from '../internal-types';
import {GetFromContext} from '../types';
import {RestBindings} from '../keys';

export class GetFromContextProvider implements Provider<GetFromContext> {
Expand Down
2 changes: 1 addition & 1 deletion packages/rest/src/providers/invoke-method.provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
// License text available at https://opensource.org/licenses/MIT

import {Context, inject, Provider} from '@loopback/context';
import {InvokeMethod, OperationArgs, OperationRetval} from '../internal-types';
import {InvokeMethod, OperationArgs, OperationRetval} from '../types';
import {RestBindings} from '../keys';
import {RouteEntry} from '../router/routing-table';

Expand Down
2 changes: 1 addition & 1 deletion packages/rest/src/providers/log-error.provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

import {Provider} from '@loopback/context';
import {ServerRequest} from 'http';
import {LogError} from '../internal-types';
import {LogError} from '../types';

export class LogErrorProvider implements Provider<LogError> {
value(): LogError {
Expand Down
Loading