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: add baseDir to context #19

Merged
merged 3 commits into from
Sep 29, 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
4 changes: 2 additions & 2 deletions .githooks/pre-commit/filter.sh
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
#!/bin/sh
EMAIL=$(git config user.email)
if [[ $EMAIL == *"alibaba-inc"* ]]
if [ $EMAIL == *"alibaba-inc"* ] || [ $EMAIL == *"taobao"* ]
then
echo "email with *.alibaba-inc.com are not allowed";
echo "email with *.alibaba-inc.com or *.taobao.com are not allowed";
exit 1;
else
echo "";
Expand Down
2 changes: 1 addition & 1 deletion .github/ISSUE_TEMPLATE.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ Thank you for reporting an issue.
2. 我们推荐如果是小问题(错别字修改,小的 bug fix)直接提交 PR。
3. 如果是一个新需求,请提供:详细需求描述,最好是有伪代码实现。
4. 如果是一个 BUG,请提供:复现步骤,错误日志以及相关配置,并尽量填写下面的模板中的条目。
5. 如果可以,请使用 `egg-init --type=simple bug` 提供一个最小可复现的代码仓库,方便我们排查问题。
5. 如果可以,请使用 `midway-init` 提供一个最小可复现的代码仓库,方便我们排查问题。
6. 扩展阅读:[如何向开源项目提交无法解答的问题](https://zhuanlan.zhihu.com/p/25795393)
-->

Expand Down
181 changes: 181 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,181 @@
# Contribution Guide

If you have any comment or advice, please report your [issue](https://github.com/midwayjs/midway/issues),
or make any change as you wish and submit an [PR](https://github.com/midwayjs/midway/pulls).

## Reporting New Issues

- Please specify what kind of issue it is.
- Before you report an issue, please search for related issues. Make sure you are not going to open a duplicate issue.
- Explain your purpose clearly in tags(see **Useful Tags**), title, or content.

Egg group members will confirm the purpose of the issue, replace more accurate tags for it, identify related milestone, and assign developers working on it.
Tags can be divided into two groups, `type` and `scope`.

- type: What kind of issue, e.g. `feature`, `bug`, `documentation`, `performance`, `support` ...
- scope: What did you modified. Which files are modified, e.g. `core: xx`, `plugin: xx`, `deps: xx`

### Useful Tags

- `support`: the issue asks helps from developers of our group. If you need helps to locate and handle problems or have any idea to improve Egg, mark it as `support`.
- `bug`: if you find a problem which possiblly could be a bug, please tag it as `bug`. Then our group members will review that issue. If it is confirmed as a bug by our group member, this issue will be tagged as `confirmed`.
- A confirmed bug will be resolved prior.
- If the bug has negative impact on running online application, it will be tagged as `critical`, which refers to top priority, and will be fixed ASAP!
- A bug will be fixed from lowest necessary version, e.g. A bug needs to be fixed from 0.9.x, then this issue will be tagged as `0.9`, `0.10`, `1.0`, `1.1`, referring that the bug is required to be fixed in those versions.
- `core: xx`: the issue is related to core, e.g. `core: loader` refers that the issue is related with `loader` config.
- `plugin: xx`: the issue is related to plugins. e.g. `plugin: session` refers that the issue is related to `session` plugin.
- `deps: xx`: the issue is related to `dependencies`, e.g. `deps:egg-cors` refers that the issue is related to `egg-cors`
- `chore: documentation`: the issue is about documentation. Need to modify documentation.

## Documentation

All features must be submitted along with documentations. The documentations should satify several requirements.

- Documentations must clarify one or more aspects of the feature, depending on the nature of feature: what it is, why it happens and how it works.
- It's better to include a series of procedues to explain how to fix the problem. You are also encourgaed to provide **simple, but self-explanatory** demo.
All demos should be compiled at [midwayjs/examples](https://github.com/midwayjs/midway-examples) repository.
- Please provide essential urls, such as application process, terminology explainations and references.

## Submitting Code

### Pull Request Guide

If you are developer of egg repo and you are willing to contribute, feel free to create a new branch, finish your modification and submit a PR. Egg group will review your work and merge it to master branch.

```bash
# Create a new branch for development. The name of branch should be semantic, avoiding words like 'update' or 'tmp'. We suggest to use feature/xxx, if the modification is about to implement a new feature.
$ git checkout -b branch-name

# Run the test after you finish your modification. Add new test cases or change old ones if you feel necessary
$ npm test

# If your modification pass the tests, congradulations it's time to push your work back to us. Notice that the commit message should be wirtten in the following format.
$ git add . # git add -u to delete files
$ git commit -m "fix(role): role.use must xxx"
$ git push origin branch-name
```

Then you can create a Pull Request at [egg](https://github.com/midwayjs/midway/pulls)

No one can garantee how much will be remembered about certain PR after some time. To make sure we can easily recap what happened previously, please provide the following information in your PR.

1. Need: What function you want to achieve (Generally, please point out which issue is related).
2. Updating Reason: Different with issue. Briefly describe your reason and logic about why you need to make such modification.
3. Related Testing: Briefly descirbe what part of testing is relevant to your modification.
4. User Tips: Notice for Egg users. You can skip this part, if the PR is not about update in API or potential compatibility problem.

### Style Guide

Eslint can help to identify styling issues that may exist in your code. Your code is required to pass the test from eslint. Run the test locally by `$ npm run lint`.

### Commit Message Format

You are encouraged to use [angular commit-message-format](https://github.com/angular/angular.js/blob/master/DEVELOPERS.md#-git-commit-guidelines) to write commit message. In this way, we could have a more trackable history and an automatically generated changelog.

```xml
<type>(<scope>): <subject>
<BLANK LINE>
<body>
<BLANK LINE>
<footer>
```

(1)type

Must be one of the following:

- feat: A new feature
- fix: A bug fix
- docs: Documentation-only changes
- style: Changes that do not affect the meaning of the code (white-space, formatting, missing semi-colons, etc)
- refactor: A code change that neither fixes a bug nor adds a feature
- perf: A code change that improves performance
- test: Adding missing tests
- chore: Changes to the build process or auxiliary tools and libraries such as documentation generation
- deps: Updates about dependencies

(2)scope

The scope could be anything specifying place of the commit change. For example $location, $browser, $compile, $rootScope, ngHref, ngClick, ngView, etc...

(3)subject

Use succinct words to describe what did you do in the commit change.

(4)body

Feel free to add more content in the body, if you think subject is not self-explanatory enough, such as what it is the purpose or reasone of you commit.

(5)footer

- **If the commit is a Breaking Change, please note it clearly in this part.**
- related issues, like `Closes #1, Closes #2, #3`
- If there is a change about an old feaure or a new feature, please associate `doc` and `midway-init`, like `midwayjs/midway-bin#123`

e.g.

```
fix($compile): [BREAKING_CHANGE] couple of unit tests for IE9

Older IEs serialize html uppercased, but IE9 does not...
Would be better to expect case insensitive, unfortunately jasmine does
not allow to user regexps for throw expectations.

Document change on midwayjs/midway#123

Closes #392

BREAKING CHANGE:

Breaks foo.bar api, foo.baz should be used instead
```

Look at [these files](https://docs.google.com/document/d/1QrDFcIiPjSLDn3EL15IJygNPiHORgU1_OOAqWjiDU5Y/edit) for more detials.

## Release

egg uses semantic versioning in release process based on [semver].

### Branch Strategy

`master` branch is the latest stable version. `next` branch is the next stable version working in progress.

- All new features will be added into `master` or `next` branch as well as all bug-fix except security issues. In such way, we can motivate developers to update to the latest stable version.
- If any API is discarded, it should be noted with `deprecate` in current stable version. The old version of API should be compatiable until the release of next stable version.
- `master` branch doesn't have publish tag. High-level framework can work with stable versions defined by semantic versioning.
- `next` branch is labelled with `next` tag, high-level framework can use `egg@next` to test the in-progress version.
- The LTS versions of Egg determined by Milestone. If a version is listed in Milestone, then it is a LTS version. We will patch it if there is any problem with it.

### Release Strategy

In the release of every stable version, there will be a PM who has the following responsibilities in different stages of the release.

#### Preparation

- Set up milestone. Confirm that request is related to milestone. Assign and update issues, like [1.x milestone].
- Create a `next` branch from `master` branch and tag it as `next`.

#### Before Release

- Confirm that performance test is passed and all issues in current Milestone are either closed or can be delayed to later versions.
- Open a new [Release Proposal MR], and write `History` as [node CHANGELOG]. Don't forget to correct content in documentation which is related to the releasing version. Commits can be generated automatically.
```
$ npm run commits
```
- Nominate PM for next stable version.

#### During Release

All tags mentioned above refere to adding tags from npm in `package.json`.

```json
"publishConfig": {
"tag": "next"
}
```

[semver]: http://semver.org/lang/zh-CN/
[Release proposal MR]: https://github.com/nodejs/node/pull/4181
[node CHANGELOG]: https://github.com/nodejs/node/blob/master/CHANGELOG.md
[1.x milestone]: https://github.com/midwayjs/midway/milestone/1
[『我是如何发布一个 npm 包的』]: https://fengmk2.com/blog/2016/how-i-publish-a-npm-package
73 changes: 68 additions & 5 deletions docs/guide.md
Original file line number Diff line number Diff line change
Expand Up @@ -272,7 +272,7 @@ const userService = await applicationContext.getAsync('user');

midway 使用 koa-router 作为路由的承载着,同时在 ts 的语法上做了一些简化,我们将路由和控制器放在了一起,使用装饰器来标注路由。

### 使用装饰器
### 路由装饰器

在新的 ts 体系中,我们的控制器目录为 `app/controller` ,我们在其中编写 `*.ts` 文件。例如下面的 `userController.ts` ,我们提供了一个获取用户的接口。

Expand Down Expand Up @@ -479,11 +479,13 @@ midway 默认使用 [injection](http://web.npm.alibaba-inc.com/package/injection

#### 注入插件

midway 可以使用 egg 和 midway 两者的插件,以往,我们通过 `midway.getPlugin` 或者 `app.xxx` 的方式来获取插件,而在新的情况下,我们可以通过 `@plugin` 装饰器来注入插件。
midway 除了支持 eggjs 原本的 app.xx 的插件用法,同时,也可以通过 `@plugin` 装饰器来注入插件。

比如我们提供了一个名字叫 `plugin2` 的插件,就可以通过属性注入的方式来修饰插件。

> 注意,由于在 midway 内部插件未放在 applicationContext 中,所以不能使用 @inject 来注入
:::warning 注意
注意,由于在 midway 内部插件未放在 applicationContext 中,所以不能使用 @inject 来注入
:::

```typescript
@provide()
Expand All @@ -496,7 +498,23 @@ export class BaseService {

```

这个时候我们就需要拿到插件的名字,我们会不断增加插件的 key 列表,请查看 [插件key](plugin_key)。
这个时候我们就需要拿到插件的名字。

#### 查找插件名

这个插件的名字和普通的插件名字,他是根据插件代码中的返回而定的。

midway 会将挂载到 app 上的属性名作为基础 key。

```js
module.exports = (app) => {
// egg 插件经常这么做
app.plugin1 = xxxx;
}
```

那么 plugin1 就是插件key,midway 会在给 app 赋值时自动将返回的对象挂载到插件上下文中,供 `@plugin` 装饰器调用。


#### 注入配置

Expand All @@ -516,7 +534,6 @@ export class BaseService {
config; // 1

}

```

通过这样,我们可以把 config 中的值直接注入到业务逻辑中。
Expand Down Expand Up @@ -742,6 +759,52 @@ export class BaseService {

```

::: tip
这个函数可以是异步的 (async)。
:::

比如如果应用希望自己使用 sequelize, 而 sequelize 的创建 model 的过程是个异步操作。

```ts
import { providerWrapper, IApplicationContext } from 'midway';
import * as Sequelize from 'sequelize';
import { Sequelize as SequelizeInstance } from 'sequelize';

// 可以直接写 async 方法
export async function factory(context: IApplicationContext) {

const instance = await context.getAsync<SequelizeInstance>('coreDB');

const UiKeyTraceModel = instance.define(name, {
gmtCreate: {
type: Sequelize.DATE,
allowNull: true,
field: 'gmt_create',
},
gmtModified: {
type: Sequelize.DATE,
allowNull: true,
field: 'gmt_modified',
}
}, {
timestamps: true,
createdAt: 'gmt_create',
updatedAt: 'gmt_modified',
freezeTableName: true,
tableName: 'xxxx'
});

return UiKeyTraceModel;
}

providerWrapper([
{
id: 'keyTraceModel',
provider: factory
}
]);
```

## 应用测试

经过大量的实践,我们沉淀出了一套标准的测试工具集。
Expand Down
2 changes: 2 additions & 0 deletions packages/midway-core/src/loader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,8 @@ export class MidwayLoader extends EggLoader {
const requestContext = new MidwayRequestContainer(this.applicationContext);
// put requestContext to applicationContext
this.applicationContext.registerObject('requestContext', requestContext);
this.applicationContext.registerObject('baseDir', this.baseDir);
this.applicationContext.registerObject('appDir', this.appDir);
// 如果没有关闭autoLoad 则进行load
if (!containerConfig.disableAutoLoad) {
this.applicationContext.load({
Expand Down
8 changes: 8 additions & 0 deletions packages/midway-mock/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,14 @@ mm2.app = (options) => {
}, options));
};

mm2.cluster = (options) => {
if (process.env.MIDWAY_BASE_DIR && !options.baseDir) options.baseDir = process.env.MIDWAY_BASE_DIR;
if (process.env.MIDWAY_FRAMEWORK_PATH && !options.framework) options.framework = process.env.MIDWAY_FRAMEWORK_PATH;
return mock.cluster(Object.assign({
framework: options.framework || 'midway',
typescript: !!require.extensions['.ts']
}, options));
};

class MockContainer {

Expand Down
2 changes: 1 addition & 1 deletion packages/midway-web/src/decorators/application.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import 'reflect-metadata';
import { scope, ScopeEnum } from 'injection';
import { WEB_ROUTER_PREFIX_CLS, WEB_ROUTER_PRIORITY } from './metaKeys';

export function controller(routerPrefix: string, priority: number = 0) {
export function controller(routerPrefix: string) {
return function (target: any): void {
Reflect.defineMetadata(WEB_ROUTER_PREFIX_CLS, routerPrefix, target);
scope(ScopeEnum.Request)(target);
Expand Down