This repository has been archived by the owner on Feb 2, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Initial implementation for a logger mixin that allows applications to bind a Logger automatically.
- Loading branch information
Showing
6 changed files
with
452 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,136 @@ | ||
# Mixins | ||
|
||
This directory contains source files for the mixins exported by this extension. | ||
|
||
## Overview | ||
|
||
Sometimes it's helpful to write partial classes and then combining them together to build more powerful classes. This pattern is called Mixins (mixing in partial classes) and is supported by LoopBack 4. | ||
|
||
LoopBack 4 supports mixins at an `Application` level. Your partial class can then be mixed into the `Application` class. A mixin class can modify or override existing methods of the class or add new ones! It is also possible to mixin multiple classes together as needed. | ||
|
||
### High level example | ||
```ts | ||
class MyApplication extends MyMixinClass(Application) { | ||
// Your code | ||
}; | ||
|
||
// Multiple Classes mixed together | ||
class MyApp extends MyMixinClass(MyMixinClass2(Application)) { | ||
// Your code | ||
} | ||
``` | ||
|
||
## Getting Started | ||
|
||
For hello-extensions we write a simple Mixin that allows the `Application` class to bind a `Logger` class from ApplicationOptions, Components, or `.logger()` method that is mixed in. `Logger` instances are bound to the key `loggers.${Logger.name}`. Once a Logger has been bound, the user can retrieve it by using [Dependency Injection](http://loopback.io/doc/en/lb4/Dependency-injection.html) and the key for the `Logger`. | ||
|
||
### What is a Logger? | ||
> A Logger class is provides a mechanism for logging messages of varying priority by providing an implementation for `Logger.info()` & `Logger.error()`. An example of a Logger is `console` which has `console.log()` and `console.error()`. | ||
#### An example Logger | ||
```ts | ||
class ColorLogger implements Logger { | ||
log(...args: LogArgs) { | ||
console.log('log :', ...args); | ||
} | ||
|
||
error(...args: LogArgs) { | ||
const data = args.join(' '); | ||
// log in red color | ||
console.log('\x1b[31m error: ' + data + '\x1b[0m'); | ||
} | ||
} | ||
``` | ||
|
||
## LoggerMixin | ||
A complete & functional implementation can be found in `logger.mixin.ts`. *Here are some key things to keep in mind when writing your own Mixin*. | ||
|
||
### constructor() | ||
A Mixin constructor must take an array of any type as it's argument. This would represent `ApplicationOptions` for our base class `Application` as well as any properties we would like for our Mixin. | ||
|
||
It is also important for the constructor to call `super(args)` so `Application` continues to work as expected. | ||
```ts | ||
constructor(...args: any[]) { | ||
super(args); | ||
} | ||
``` | ||
|
||
### Binding via `ApplicationOptions` | ||
As mentioned earlier, since our `args` represents `ApplicationOptions`, we can make it possible for users to pass in their `Logger` implementations in a `loggers` array on `ApplicationOptions`. We can then read the array and automatically bind these for the user. | ||
|
||
#### Example user experience | ||
```ts | ||
class MyApp extends LoggerMixin(Application){ | ||
constructor(...args: any[]) { | ||
super(...args); | ||
} | ||
}; | ||
|
||
const app = new MyApp({ | ||
loggers: [ColorLogger] | ||
}); | ||
``` | ||
|
||
#### Example Implementation | ||
To implement this, we would check `this.options` to see if it has a `loggers` array and if so, bind it by calling the `.logger()` method. (More on that below). | ||
```ts | ||
if (this.options.loggers) { | ||
for (const logger of this.options.loggers) { | ||
this.logger(logger); | ||
} | ||
} | ||
``` | ||
|
||
### Binding via `.logger()` | ||
As mentioned earlier, we can add a new function to our `Application` class called `.logger()` into which a user would pass in their `Logger` implementation so we can bind it to the `loggers.*` key for them. We just add this new method on our partial Mixin class. | ||
```ts | ||
logger(logClass: Logger) { | ||
const loggerKey = `loggers.${logClass.name}`; | ||
this.bind(loggerKey).toClass(logClass); | ||
} | ||
``` | ||
|
||
### Binding a `Logger` from a `Component` | ||
Our base class of `Application` already has a method that binds components. We can modify this method to continue binding a `Component` as usual but also binding any `Logger` instances provided by that `Component`. When modifying behavior of an existing method, we can ensure existing behavior by calling the `super.method()`. In our case the method is `.component()`. | ||
```ts | ||
component(component: Constructor<any>) { | ||
super.component(component); // ensures existing behavior from Application | ||
this.mountComponentLoggers(component); | ||
} | ||
``` | ||
|
||
We have now modified `.component()` to do it's thing and then call our method `mountComponentLoggers()`. In this method is where we check for `Logger` implementations declared by the component in a `loggers` array by retrieving the instance of the `Component`. Then if `loggers` array exists, we bind the `Logger` instances as normal (by leveraging our `.logger()` method). | ||
|
||
```ts | ||
mountComponentLoggers(component: Constructor<any>) { | ||
const componentKey = `components.${component.name}`; | ||
const compInstance = this.getSync(componentKey); | ||
|
||
if (compInstance.loggers) { | ||
for (const logger of compInstance.loggers) { | ||
this.logger(logger); | ||
} | ||
} | ||
} | ||
``` | ||
|
||
|
||
## Examples for using LoggerMixin | ||
``` | ||
// Using the app's .logger() function. | ||
class LoggingApplication extends LoggerMixin(Application) { | ||
constructor(...args: any[]) { | ||
super(...args); | ||
this.logger(ColorLogger); | ||
} | ||
} | ||
// Binding a Logger provided by a component | ||
class LoggingComponent implements Component{ | ||
loggers: [ColorLogger]; | ||
} | ||
const app = new LoggingApplication({ | ||
components: [LoggingComponent] // Logger from MyComponent will be bound to loggers.ColorLogger | ||
}); | ||
``` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,98 @@ | ||
// Copyright IBM Corp. 2017. All Rights Reserved. | ||
// Node module: loopback-next-extension-starter | ||
// This file is licensed under the MIT License. | ||
// License text available at https://opensource.org/licenses/MIT | ||
|
||
// tslint:disable:no-any | ||
|
||
import {Constructor} from '@loopback/context'; | ||
import {Logger} from '../types'; | ||
|
||
/** | ||
* A mixin class for Application that creates a .logger() | ||
* function to register a Logger automatically. Also overrides | ||
* component function to allow it to register Logger's automatically. | ||
* | ||
* ```ts | ||
* | ||
* class MyApplication extends LoggerMixin(Application) {} | ||
* ``` | ||
*/ | ||
export function LoggerMixin<T extends Constructor<any>>(superClass: T) { | ||
return class extends superClass { | ||
// A mixin class has to take in a type any[] argument! | ||
constructor(...args: any[]) { | ||
super(...args); | ||
if (!this.options) this.options = {}; | ||
|
||
if (this.options.loggers) { | ||
for (const logger of this.options.loggers) { | ||
this.logger(logger); | ||
} | ||
} | ||
} | ||
|
||
/** | ||
* Add a Logger to this application. | ||
* | ||
* @param Logger The Logger to add. | ||
* | ||
* ```ts | ||
* | ||
* class Logger { | ||
* log(...args: any) { | ||
* console.log(...args); | ||
* } | ||
* }; | ||
* | ||
* app.logger(Logger); | ||
* ``` | ||
*/ | ||
logger(logClass: Constructor<Logger>) { | ||
const loggerKey = `loggers.${logClass.name}`; | ||
this.bind(loggerKey).toClass(logClass); | ||
} | ||
|
||
/** | ||
* Add a component to this application. Also mounts | ||
* all the components Loggers. | ||
* | ||
* @param component The component to add. | ||
* | ||
* ```ts | ||
* | ||
* export class ProductComponent { | ||
* controllers = [ProductController]; | ||
* loggers = [ProductLogger]; | ||
* providers = { | ||
* [PRODUCT_PROVIDER]: ProductProvider, | ||
* }; | ||
* }; | ||
* | ||
* app.component(ProductComponent); | ||
* ``` | ||
*/ | ||
component(component: Constructor<any>) { | ||
super.component(component); | ||
this.mountComponentLoggers(component); | ||
} | ||
|
||
/** | ||
* Get an instance of a component and mount all it's | ||
* loggers. This function is intended to be used internally | ||
* by component() | ||
* | ||
* @param component The component to mount Logger's of | ||
*/ | ||
mountComponentLoggers(component: Constructor<any>) { | ||
const componentKey = `components.${component.name}`; | ||
const compInstance = this.getSync(componentKey); | ||
|
||
if (compInstance.loggers) { | ||
for (const logger of compInstance.loggers) { | ||
this.logger(logger); | ||
} | ||
} | ||
} | ||
}; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,16 @@ | ||
// Copyright IBM Corp. 2013,2017. All Rights Reserved. | ||
// Node module: loopback-next-extension-starter | ||
// This file is licensed under the MIT License. | ||
// License text available at https://opensource.org/licenses/MIT | ||
|
||
// Types and interfaces exposed by the extension go here | ||
|
||
// tslint:disable-next-line:no-any | ||
export type LogArgs = any[]; | ||
|
||
// A traditional Logger interface would have `.warn()` and `.info()` methods & | ||
// potentially others but they have been omitted to keep this example simple. | ||
export interface Logger { | ||
log(...args: LogArgs): void; | ||
error(...args: LogArgs): void; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,100 @@ | ||
// Copyright IBM Corp. 2013,2017. All Rights Reserved. | ||
// Node module: loopback-next-extension-starter | ||
// This file is licensed under the MIT License. | ||
// License text available at https://opensource.org/licenses/MIT | ||
|
||
import {Application, inject} from '@loopback/core'; | ||
import {RestComponent, RestServer, get, param} from '@loopback/rest'; | ||
import {sinon, Client, createClientForHandler} from '@loopback/testlab'; | ||
import {LoggerMixin, Logger, LogArgs} from '../../..'; | ||
|
||
describe('logger.mixin (acceptance)', () => { | ||
// tslint:disable-next-line:no-any | ||
let app: any; | ||
let server: RestServer; | ||
// tslint:disable-next-line:no-any | ||
let spy: any; | ||
|
||
beforeEach(createApp); | ||
beforeEach(createLogger); | ||
beforeEach(createController); | ||
beforeEach(getServerFromApp); | ||
beforeEach(() => { | ||
spy = sinon.spy(console, 'log'); | ||
}); | ||
|
||
afterEach(() => { | ||
spy.restore(); | ||
}); | ||
|
||
it('.log() logs request information', async () => { | ||
const client: Client = createClientForHandler(server.handleHttp); | ||
await client.get('/?name=John').expect(200, 'Hi John'); | ||
sinon.assert.calledWith(spy, sinon.match('log: hello() called with: John')); | ||
}); | ||
|
||
it('.error() logs request information', async () => { | ||
const client: Client = createClientForHandler(server.handleHttp); | ||
await client.get('/error?name=John').expect(200, 'Hi John'); | ||
sinon.assert.calledWith( | ||
spy, | ||
sinon.match('error: hello() called with: John'), | ||
); | ||
}); | ||
|
||
function createApp() { | ||
class LoggerApplication extends LoggerMixin(Application) { | ||
// tslint:disable-next-line:no-any | ||
constructor(...args: any[]) { | ||
super({ | ||
components: [RestComponent], | ||
}); | ||
} | ||
} | ||
|
||
app = new LoggerApplication(); | ||
} | ||
|
||
function createLogger() { | ||
class ColorLogger implements Logger { | ||
log(...args: LogArgs) { | ||
const data = 'log: ' + args.join(' '); | ||
console.log(data); | ||
} | ||
|
||
error(...args: LogArgs) { | ||
const data = args.join(' '); | ||
// log in red color | ||
console.log('\x1b[31m error: ' + data + '\x1b[0m'); | ||
} | ||
} | ||
|
||
app.logger(ColorLogger); | ||
} | ||
|
||
function createController() { | ||
class MyController { | ||
constructor(@inject('loggers.ColorLogger') protected log: Logger) {} | ||
|
||
@get('/') | ||
@param.query.string('name') | ||
hello(name: string) { | ||
this.log.log('hello() called with:', name); | ||
return `Hi ${name}`; | ||
} | ||
|
||
@get('/error') | ||
@param.query.string('name') | ||
helloError(name: string) { | ||
this.log.error('hello() called with:', name); | ||
return `Hi ${name}`; | ||
} | ||
} | ||
|
||
app.controller(MyController); | ||
} | ||
|
||
async function getServerFromApp() { | ||
server = await app.getServer(RestServer); | ||
} | ||
}); |
Oops, something went wrong.