Skip to content

Commit

Permalink
docs: migrate missing pages from loopback.io
Browse files Browse the repository at this point in the history
  • Loading branch information
shimks committed Mar 15, 2018
1 parent a219da3 commit a0579ff
Show file tree
Hide file tree
Showing 18 changed files with 978 additions and 248 deletions.
28 changes: 15 additions & 13 deletions docs/site/Application.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,13 +32,17 @@ tasks as a part of your setup:
import {Application} from '@loopback/core';
import {RestComponent, RestServer} from '@loopback/rest';
import {SamoflangeController, DoohickeyController} from './controllers';
import {WidgetApi} from './apidef/';

export class WidgetApplication extends Application {
constructor() {
// This is where you would pass configuration to the base constructor
// (as well as handle your own!)
super();
super({
rest: {
port: 8080
}
});

const app = this; // For clarity.
// You can bind to the Application-level context here.
// app.bind('foo').to(bar);
Expand All @@ -47,17 +51,6 @@ export class WidgetApplication extends Application {
app.controller(DoohickeyController);
}

async start() {
// This is where you would asynchronously retrieve servers, providers and
// other components to configure them before launch.
const server = await app.getServer(RestServer);
server.bind('rest.port').to(8080);
server.api(WidgetApi);
// The superclass start method will call start on all servers that are
// bound to the application.
return await super.start();
}

async stop() {
// This is where you would do whatever is necessary before stopping your
// app (graceful closing of connections, flushing buffers, etc)
Expand Down Expand Up @@ -191,6 +184,15 @@ export class MyApplication extends RestApplication {
## Tips for application setup
Here are some tips to help avoid common pitfalls and mistakes.

### Extend from `RestApplication` when using `RestServer`
If you want to use `RestServer` from our `@loopback/rest` package, we recommend you extend
`RestApplication` in your app instead of manually binding `RestServer` or
`RestComponent`. `RestApplication` already uses `RestComponent` and makes
useful functions in `RestServer` like `handler()` available at the app level.
This means you can call these `RestServer` functions to do all of your
server-level setups in the app constructor without having to explicitly retrieve
an instance of your server.

### Use unique bindings
Use binding names that are prefixed with a unique string that does not overlap
with loopback's bindings. As an example, if your application is built for
Expand Down
19 changes: 14 additions & 5 deletions docs/site/Best-practices-with-Loopback-4.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,21 @@ permalink: /doc/en/lb4/Best-practices-with-Loopback-4.html
summary:
---

{% include important.html content="
The API-first approach for building LoopBack
applications is not yet fully supported. Therefore, some of the sections in this
page are outdated and may not work out of the box. They will be revisited after
our MVP release.
" %}

LoopBack 4 is more than just a framework: It’s an ecosystem that encourages developers to follow best practices through predefined standards. This section will walk through some important guidelines by building an example API for a catalog of products.

Our best practice follows an "API first" and test-driven development approach:

1. [**Defining and validating the API**](./Defining-and-validating-the-API.md): This section guides you through constructing your API first before any internal logic is added.
2. [**Testing the API**](./Testing-the-API.md): This section describes the process of writing smoke test for your API and its spec.
3. [**Defining your testing strategy**](./Defining-your-testing-strategy.md): This section discusses the advantages and the process of building a strong testing suite.
4. [**Implementing features**](./Implementing-features.md): This section demonstrates how the tests for each feature of your application should be written, and how to write the logic to make these tests pass. In the example, the tests for the controller, model, repository, data source, and sequence are written and then implemented.
5. [**Preparing the API for consumption**](./Preparing-the-API-for-consumption.md): This section shows how the endpoints can be physically tested using the Swagger UI.
1. **Defining the API**: There are two possible approaches to take in this section
- [**Defining the API using code-first approach**](./Defining-the-API-using-code-first-approach.md): This section guides you through setting up a skeleton of your application so that its full OpenAPI specification can be automatically generated.
- [**Defining the API using design-first approach**](./Defining-the-API-using-design-first-approach.md): This section guides you through constructing your API first before any internal logic is added. __*Not fully supported*__
- [**Testing the API**](./Testing-the-API.md): This section describes the process of writing smoke test for your API and its spec. __*Not fully supported*__
2. [**Defining your testing strategy**](./Defining-your-testing-strategy.md): This section discusses the advantages and the process of building a strong testing suite.
3. [**Implementing features**](./Implementing-features.md): This section demonstrates how the tests for each feature of your application should be written, and how to write the logic to make these tests pass. In the example, the tests for the controller, model, repository, data source, and sequence are written and then implemented.
4. [**Preparing the API for consumption**](./Preparing-the-API-for-consumption.md): This section shows how the endpoints can be physically tested using the Swagger UI.
238 changes: 238 additions & 0 deletions docs/site/Booting-an-Application.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,238 @@
---
lang: en
title: 'Booting an Application'
keywords: LoopBack 4.0, LoopBack 4
tags:
sidebar: lb4_sidebar
permalink: /doc/en/lb4/Booting-an-Application.html
summary:
---

## What does Booting an Application mean?

A typical LoopBack application is made up of many artifacts in different files,
organized in different folders. **Booting an Application** means:

* Discovering artifacts automatically based on a convention (a specific folder
containing files with a given suffix)
* Processing those artifacts (this usually means automatically binding them to the Application's Context)

`@loopback/boot` provides a Bootstrapper that uses Booters to automatically
discover and bind artifacts, all packaged in an easy-to-use Mixin.

### What is an artifact?

An artifact is any LoopBack construct usually defined in code as a Class. LoopBack
constructs include Controllers, Repositories, Models, etc.

## Usage

### @loopback/cli

New projects generated using `@loopback/cli` or `lb4` are automatically enabled
to use `@loopback/boot` for booting the Application using the conventions
followed by the CLI.

### Adding to existing project

See [Using the BootMixin](#using-the-bootmixin) to add Boot to your Project manually.

---

The rest of this page describes the inner workings of `@loopback/boot` for advanced use
cases, manual usage or using `@loopback/boot` as a standalone package (with custom
booters).

## BootMixin

Boot functionality can be added to a LoopBack 4 Application by mixing it with the
`BootMixin`. The Mixin adds the `BootComponent` to your Application as well as
convenience methods such as `app.boot()` and `app.booters()`. The Mixin also allows
Components to set the property `booters` as an Array of `Booters`. They will be bound
to the Application and called by the `Bootstrapper`.

Since this is a convention-based Bootstrapper, it is important to set a `projectRoot`,
as all other artifact paths will be resolved relative to this path.

_Tip_: `application.ts` will likely be at the root of your project, so its path can be
used to set the `projectRoot` by using the `__dirname` variable. _(See example below)_

### Using the BootMixin

`Booter` and `Binding` types must be imported alongside `BootMixin` to allow TypeScript
to infer types and avoid errors. _If using `tslint` with the `no-unused-variable` rule,
you can disable it for the import line by adding `// tslint:disable-next-line:no-unused-variable`
above the import statement_.

```ts
import {BootMixin, Booter, Binding} from "@loopback/boot";

class MyApplication extends BootMixin(Application) {
constructor(options?: ApplicationConfig) {
super(options);
// Setting the projectRoot
this.projectRoot = __dirname;
// Set project conventions
this.bootOptions: BootOptions = {
controllers: {
dirs: ['controllers'],
extensions: ['.controller.js'],
nested: true,
}
}
}
}
```

Now just call `app.boot()` from `index.ts` before starting your Application using `app.start()`.

#### app.boot()

A convenience method to retrieve the `Bootstrapper` instance bound to the
Application and calls its `boot` function. This should be called before an
Application's `start()` method is called. _This is an `async` function and should
be called with `await`._

```ts
class MyApp extends BootMixin(Application) {}

async main() {
const app = new MyApp();
app.projectRoot = __dirname;
await app.boot();
await app.start();
}
```

#### app.booters()

A convenience method to manually bind `Booters`. You can pass any number of `Booter`
classes to this method and they will all be bound to the Application using the
prefix (`booters.`) and tag (`booter`) used by the `Bootstrapper`.

```ts
// Binds MyCustomBooter to `booters.MyCustomBooter`
// Binds AnotherCustomBooter to `booters.AnotherCustomBooter`
// Both will have the `booter` tag set.
app.booters(MyCustomBooter, AnotherCustomBooter);
```

## BootComponent

This component is added to an Application by `BootMixin` if used. This Component:

* Provides a list of default `booters` as a property of the component
* Binds the conventional Bootstrapper to the Application

_If using this as a standalone component without the `BootMixin`, you will need to
bind the `booters` of a component manually._

```ts
app.component(BootComponent);
```

## Bootstrapper

A Class that acts as the "manager" for Booters. The Bootstrapper is designed to be
bound to an Application as a `SINGLETON`. The Bootstrapper class provides a `boot()`
method. This method is responsible for getting all bound `Booters` and running
their `phases`. A `phase` is a method on a `Booter` class.

Each `boot()` method call creates a new `Context` that sets the `app` context
as its parent. This is done so each `Context` for `boot` gets a new instance of
`booters` but the same context can be passed into `boot` so selective `phases` can be
run in different calls of `boot`.

The Bootstrapper can be configured to run specific booters or boot phases
by passing in `BootExecOptions`. **This is experimental and subject to change. Hence,
this functionality is not exposed when calling `boot()` via `BootMixin`**.

To use `BootExecOptions`, you must directly call `bootstrapper.boot()` instead of `app.boot()`.
You can pass in the `BootExecOptions` object with the following properties:

| Property | Type | Description |
| ---------------- | ----------------------- | ------------------------------------------------ |
| `booters` | `Constructor<Booter>[]` | Array of Booters to bind before running `boot()` |
| `filter.booters` | `string[]` | Names of Booter classes that should be run |
| `filter.phases` | `string[]` | Names of Booter phases to run |

### Example

```ts
import { BootMixin, Booter, Binding, Bootstrapper } from "@loopback/boot";

class MyApp extends BootMixin(Application) {}
const app = new MyApp();
app.projectRoot = __dirname;

const bootstrapper: Bootstrapper = await this.get(
BootBindings.BOOTSTRAPPER_KEY
);
bootstrapper.boot({
booters: [MyCustomBooter],
filter: {
booters: ["MyCustomBooter"],
phases: ["configure", "discover"] // Skip the `load` phase.
}
});
```

## Booters

A Booter is a class that is responsible for booting an artifact. A Booter does its
work in `phases` which are called by the Bootstrapper. The following Booters are
a part of the `@loopback/boot` package and loaded automatically via `BootMixin`.

### Controller Booter

This Booter's purpose is to discover [Controller](Controllers.html) type Artifacts and to bind
them to the Application's Context.

You can configure the conventions used in your
project for a Controller by passing a `controllers` object on `BootOptions` property
of your Application. The `controllers` object supports the following options:

| Options | Type | Default | Description |
| ------------ | -------------------- | -------------------- | ------------------------------------------------------------------------------------------------------------- |
| `dirs` | `string \| string[]` | `['controllers']` | Paths relative to projectRoot to look in for Controller artifacts |
| `extensions` | `string \| string[]` | `['.controller.js']` | File extensions to match for Controller artifacts |
| `nested` | `boolean` | `true` | Look in nested directories in `dirs` for Controller artifacts |
| `glob` | `string` | | A `glob` pattern string. This takes precendence over above 3 options (which are used to make a glob pattern). |

### Repository Booter

This Booter's purpose is to discover [Repository](Repository.html) type Artifacts and to bind
them to the Application's Context. The use of this Booter requires `RepositoryMixin`
from `@loopback/repository` to be mixed into your Application class.

You can configure the conventions used in your
project for a Repository by passing a `repositories` object on `BootOptions` property
of your Application. The `repositories` object supports the following options:

| Options | Type | Default | Description |
| ------------ | -------------------- | -------------------- | ------------------------------------------------------------------------------------------------------------- |
| `dirs` | `string \| string[]` | `['repositories']` | Paths relative to projectRoot to look in for Repository artifacts |
| `extensions` | `string \| string[]` | `['.repository.js']` | File extensions to match for Repository artifacts |
| `nested` | `boolean` | `true` | Look in nested directories in `dirs` for Repository artifacts |
| `glob` | `string` | | A `glob` pattern string. This takes precendence over above 3 options (which are used to make a glob pattern). |

### Custom Booters

A custom Booter can be written as a Class that implements the `Booter` interface. The Class
must implement methods that corresponds to a `phase` name. The `phases` are called
by the Bootstrapper in a pre-determined order (unless overridden by `BootExecOptions`).
The next phase is only called once the previous phase has been completed for all Booters.

#### Phases

**configure**

Used to configure the `Booter` with its default options.

**discover**

Used to discover the artifacts supported by the `Booter` based on convention.

**load**

Used to bind the discovered artifacts to the Application.
2 changes: 1 addition & 1 deletion docs/site/Context.md
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ store along with the key. For example:
// app level
const app = new Application();
app.bind('hello').to('world'); // ContextKey='hello', ContextValue='world'
console.log(app.getSync('hello')); // => 'world'
console.log(app.getSync<string>('hello')); // => 'world'
```

In this case, we bind the 'world' string ContextValue to the 'hello' ContextKey.
Expand Down
6 changes: 3 additions & 3 deletions docs/site/Decorators.md
Original file line number Diff line number Diff line change
Expand Up @@ -290,7 +290,7 @@ Syntax: `@inject.tag(tag: string | RegExp)`.
.bind('store.locations.sj')
.to('San Jose')
.tag('store:location');
const store: Store = ctx.getSync('store');
const store = ctx.getSync<Store>('store');
// `store.locations` is now `['San Francisco', 'San Jose']`
```

Expand All @@ -305,13 +305,13 @@ Syntax: `@inject.context()`.

const ctx = new Context();
ctx.bind('my-component').toClass(MyComponent);
const component: MyComponent = ctx.getSync('my-component');
const component = ctx.getSync<MyComponent>('my-component');
// `component.ctx` should be the same as `ctx`
```

**NOTE**: It's recommended to use `@inject` with specific keys for dependency injection if possible. Use `@inject.context` only when the code need to access the current context object for advanced use cases.

For more information, see the [Dependency Injection](Dependency-Injection.htm) section under [LoopBack Core Concepts](Concepts.md)
For more information, see the [Dependency Injection](Dependency-Injection.md) section under [LoopBack Core Concepts](Concepts.md)

## Authentication Decorator

Expand Down
Loading

0 comments on commit a0579ff

Please sign in to comment.