Skip to content

WIP: EN translation #3

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

Closed
wants to merge 6 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
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
checklist
node_modules/
yarn.lock
.DS_Store
50 changes: 48 additions & 2 deletions docs/guide/README.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,53 @@
---
title: Guide
navTitle: Egg Guide
navTitle: Guide
toc: false
---

guide
In this guide, we'd thoroughly introduce you every bit of Egg. You can also find guides about the applicable situations of Egg, components how-to, common functions and properties, extendability and testing.

## MVC

Egg is a web application framework written in Node.js. It is designed based on the MVC principle, which is commonly seen among other web application frameworks written in Node.js, like Express.js.

Before you step into the details, we strongly recommend you to learn [the structure of an Egg application].

There're some basic concepts that you need to know:

- [Middleware]: Same as `Koa`'s middleware and similar to `Filter` in Java's world.
- [Controller]: Response to the incoming requests and performs interactions on the data models or calling the services.
- [Router]: Dispatches incoming requests to designated controllers.
- [Service]: A bunch of magic functions that contain your business logics.
- [Application]: A handy object includes the [configurations] of the application. It can be accessed globally.
- [Context]: Every user request has a context. It describes the request and defines the response.
- Besides, there're [Cookie], [Session], [Helper], etc.

## Features

Egg provides a range of utilities you can use in your day to day development.

- [Plugins]: The foundation of Egg's eco-system. You can extend your applications using plugins just in one minute.
- [Lifecycle]: Allow you to run your own code at different stages.
- [Logs]: Logging anything to anywhere. It is crucial for monitoring and debugging.
- [Error handling]: Make the application robust.
- [Security]: Be safe.
- Last but not least, [file uploading], [i18n].

[the structure of an Egg application]: ./directory.md
[Controller]: ./controller.md
[Service]: ./service.md
[Router]: ./router.md
[Cookie]: ./cookie.md
[Session]: ./session.md
[Application]: ./application.md
[Context]: ./context.md
[Middleware]: ./middleware.md
[Plugins]: ./plugin.md
[Lifecycle]: ./lifecycle.md
[configurations]: ./config.md
[Logs]: ./logger.md
[Error handling]: ./error_handler.md
[Helper]: ./helper.md
[Security]: ../ecosystem/security/
[file uploading]: ./upload.md
[i18n]: ./i18n.md
178 changes: 178 additions & 0 deletions docs/guide/application.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,178 @@
---
title: Application
---

## Use Cases

`Application` is an global object which inherits from [Koa.Application]. It can be used for extending functionalities which are meant to be shared across the application.

The Egg application would only instantiate the `Application` once in a process.

:::warning
For processes started by Egg, they all have an instance of `Application`.
:::

## How To Access

`Application` probably is the most common seen object in developing Egg applications.

```js
// app/controller/home.js
class HomeController extends Controller {
async index() {
// 从 `Controller/Service` 基类继承的属性: `this.app`
console.log(this.app.config.name);
// 从 ctx 对象上获取
console.log(this.ctx.app.config.name);
}
}
```

[Routers][Router] and [Middlewares][Middleware] and other files that loaded through the `Loader` can export a function and take the `app` as an argument.

*Router*

```js
// app/router.js
module.exports = app => {
const { router, controller } = app;
router.get('/', controller.home.index);
};
```

*Middleware*

```js
// app/middleware/response_time.js
module.exports = (options, app) => {
// 加载期传递 app 实例
console.log(app);

return async function responseTime(ctx, next) {};
};
```

## Common API

### app.config

[Configurations][Configuration] for the application.

### app.router

The [`Router`][Router] instance.

### app.controller

All the [`Controller`][Controller] instances.

### app.logger

The global logger for logging business unrelated information.

Go to [Logger] to see more.

### app.middleware

All [Middlewares][Middleware].

### app.server

An instance of [HTTP Server](https://nodejs.org/api/http.html#http_class_http_server) or [HTTPS Server](https://nodejs.org/api/https.html#https_class_https_server).

It can be accessed after the [lifecycle](./lifecycle.md) event `serverDidReady`.

### app.curl()

An instance of [HttpClient](./httpclient.md).

### app.createAnonymousContext()

You can create an anonymous request by calling this function if you need to access the [Context] instance.

```js
const ctx = app.createAnonymousContext();
await ctx.service.user.list();
```

## Extending

Egg supports extending `Application` using `app/extend/application.js`.

### Extend a Function

```js
// app/extend/application.js
module.exports = {
foo(param) {
// `this` points to the `app`
},
};
```

### Extend a Property

It is recommended to use *Symbol* and *Getter* to save properties that need to be instantiate.

```js
// app/extend/application.js
const NUNJUCKS = Symbol('Application#nunjucks');
const nunjuck = require('nunjuck');

module.exports = {
get nunjucks() {
if (!this[NUNJUCKS]) {
// `this` points to the `app`
this[NUNJUCKS] = new nunjucks.Environment(this.config.nunjucks);
}
return this[NUNJUCKS];
},

foo: 'bar',
};
```

### Writing Tests

We recommend you to keep your plugins high quality using [unit tests](../workflow/development/unittest.md).

```js
// test/app/extend/application.js
const { app, assert } = require('egg-mock');

describe('test/app/extend/application.js', () => {
it('should export nunjucks', () => {
assert(app.nunjucks);
assert(app.nunjucks.renderString('{{ name }}', { name: 'TZ' }) === 'TZ');
});
});
```

Find more on this topic in [Development - Unit Test](../workflow/development/unittest.md).

### Extend In Different Environment

You can choose when to activate certain plugins or extend files.

For example, `app/extend/application.unittest.js` will only be activated on `unittest` environment.

```js
// app/extend/application.unittest.js
module.exports = {
mockXX(k, v) {
},
};
```

Meanwhile, other objects like `Application`, `Context`, `Request`, `Response`, `Helper` can also be extended using this technique.

[Koa]: http://koajs.com
[Koa.Application]: http://koajs.com/#application
[Middleware]: ./middleware.md
[Context]: ./context.md
[Controller]: ./controller.md
[Service]: ./service.md
[Router]: ./router.md
[路由]: ./router.md
[Configuration]: ./config.md
[Logger]: ./logger.md
Loading