Skip to content

Commit

Permalink
fix: add metadata when configuration load controller (#483)
Browse files Browse the repository at this point in the history
  • Loading branch information
kurten authored Apr 30, 2020
1 parent e6a941d commit e4e3c57
Show file tree
Hide file tree
Showing 78 changed files with 1,109 additions and 67 deletions.
15 changes: 15 additions & 0 deletions .github/workflows/nodejs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,21 @@ jobs:
- run: npm install && npm install codecov
- run: npm run bootstrap
- run: npm run build --if-present
- run: npm run link
- run: npm run cov
- name: Upload coverage to Codecov
uses: codecov/codecov-action@v1
- name: Checkout Midway FaaS
uses: actions/checkout@v2
with:
repository: midwayjs/midway-faas
path: midway-faas
- run: |
cd midway-faas
npm install
npm run bootstrap
npm run build --if-present
cd packages/faas
npm link @midwayjs/core
npm link @midwayjs/decorator
npm run cov
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
"scripts": {
"autod": "lerna run autod",
"test": "lerna run test",
"link": "lerna run link",
"cov": "lerna run cov --concurrency=1",
"ci": "npm run build && npm run cov",
"purge": "npm run clean && rm -rf node_modules",
Expand Down
3 changes: 2 additions & 1 deletion packages/midway-core/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@
"lint": "../../node_modules/.bin/tslint --format prose -c ../../tslint.json --fix 'src/**/*.ts' 'test/**/*.ts'",
"test": "npm run lint && midway-bin clean && NODE_ENV=test midway-bin test --ts",
"cov": "midway-bin clean && midway-bin cov --ts",
"autod": "midway-bin autod"
"autod": "midway-bin autod",
"link": "npm link"
},
"keywords": [
"midway",
Expand Down
2 changes: 1 addition & 1 deletion packages/midway-core/src/common/constants.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
export const FUNCTION_INJECT_KEY = 'midway:function_inject_key';
export const MIDWAY_ALL_CONFIG = 'midway:all_config_inject_key';

export const PRIVATE_META_DATA_KEY = '__midway_private_meta_data__';
/**
* 静态参数
*
Expand Down
8 changes: 6 additions & 2 deletions packages/midway-core/src/context/midwayContainer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,12 @@ import {
listModule,
CONFIGURATION_KEY,
isProvide,
saveClassMetadata,
} from '@midwayjs/decorator';
import * as is from 'is-type-of';
import { join } from 'path';
import { ContainerConfiguration } from './configuration';
import { FUNCTION_INJECT_KEY } from '../common/constants';
import { FUNCTION_INJECT_KEY, PRIVATE_META_DATA_KEY } from '../common/constants';
import {
IConfigService,
IEnvironmentService,
Expand Down Expand Up @@ -86,7 +87,7 @@ export class MidwayContainer extends Container implements IMidwayContainer {
}) {
// 添加全局白名单
this.midwayIdentifiers.push(PIPELINE_IDENTIFIER);
this.midwayIdentifiers.push('ctx');
this.midwayIdentifiers.push(REQUEST_CTX_KEY);

// create main module configuration
const configuration = this.createConfiguration();
Expand Down Expand Up @@ -158,6 +159,9 @@ export class MidwayContainer extends Container implements IMidwayContainer {
if (is.class(module)) {
const providerId = isProvide(module) ? getProviderId(module) : null;
if (providerId) {
if (namespace) {
saveClassMetadata(PRIVATE_META_DATA_KEY, { namespace }, module);
}
this.bind(generateProvideId(providerId, namespace), module, {
namespace,
srcPath: filePath,
Expand Down
2 changes: 2 additions & 0 deletions packages/midway-core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ export {
listPreloadModule,
saveModule,
listModule,
resetModule,
clearAllModule,
getParamNames,
getProviderId,
Expand All @@ -36,4 +37,5 @@ export { MidwayContainer } from './context/midwayContainer';
export { MidwayRequestContainer } from './context/requestContainer';
export * from './context/providerWrapper';
export * from './common/constants';
export * as util from './common/util';
export * from './features';
17 changes: 6 additions & 11 deletions packages/midway-core/src/interface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -227,19 +227,14 @@ export interface IMiddleware<T> {
}

export interface IMidwayCoreApplication {
isTsMode: boolean;
baseDir: string;
appDir: string;
env?: string;
isTypeScriptMode(): boolean;
getBaseDir(): string;
getAppDir(): string;
getEnv(): string;
/**
* application/agent
*/
type?: string;
applicationContext: IMidwayContainer;
/**
* middlewares
*/
middleware: any[];

getType(): string;
getApplicationContext(): IMidwayContainer;
getConfig(key?: string): any;
}
8 changes: 0 additions & 8 deletions packages/midway-core/src/loader.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
import * as path from 'path';
import { MidwayContainer } from './context/midwayContainer';
import { Container } from './context/container';
import { IMidwayCoreApplication } from './interface';
import { APPLICATION_KEY } from '@midwayjs/decorator';

function buildLoadDir(baseDir, dir) {
if (!path.isAbsolute(dir)) {
Expand Down Expand Up @@ -47,12 +45,6 @@ export class ContainerLoader {
this.applicationContext.registerDataHandler(hookKey, hookHandler);
}

bindApp(app: IMidwayCoreApplication) {
this.applicationContext.registerDataHandler(APPLICATION_KEY, () => {
return app;
});
}

loadDirectory(loadOpts: {
baseDir?: string;
loadDir?: string[];
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ class AutoConfiguraion implements ILifeCycle {
test: IMidwayCoreApplication;

async onReady() {
if (this.test.baseDir !== 'hello this is basedir') {
if (this.test.getBaseDir() !== 'hello this is basedir') {
throw new Error('midway core application error');
}
}
Expand Down
12 changes: 9 additions & 3 deletions packages/midway-core/test/loader.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import {
LOGGER_KEY,
PLUGIN_KEY,
Provide,
APPLICATION_KEY,
} from '@midwayjs/decorator';
import * as assert from 'assert';
import * as path from 'path';
Expand Down Expand Up @@ -94,9 +95,9 @@ describe('/test/loader.test.ts', () => {
loader.initialize();
loader.loadDirectory();
const tt: any = {
baseDir: 'hello this is basedir'
getBaseDir() { return 'hello this is basedir'; }
};
loader.bindApp(tt);
loader.registerHook(APPLICATION_KEY, () => tt);
await loader.refresh();
// register handler for container
loader.registerHook(CONFIG_KEY, (key, target) => {
Expand All @@ -122,7 +123,7 @@ describe('/test/loader.test.ts', () => {
assert(baseService.config === 'hello');
assert(baseService.logger === console);
assert(baseService.plugin2.b === 2);
assert(baseService.test.baseDir === 'hello this is basedir');
assert(baseService.test.getBaseDir() === 'hello this is basedir');
});

it('load ts file support constructor inject', async () => {
Expand Down Expand Up @@ -230,6 +231,11 @@ describe('/test/loader.test.ts', () => {
});
loader.initialize();
loader.loadDirectory();
loader.registerHook(APPLICATION_KEY, () => ({
getBaseDir() {
return 'base dir';
}
}));
await loader.refresh();

const appCtx = loader.getApplicationContext();
Expand Down
3 changes: 2 additions & 1 deletion packages/midway-decorator/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@
"test": "npm run lint && midway-bin clean && NODE_ENV=test midway-bin test --ts",
"cov": "midway-bin cov --ts",
"ci": "npm run test",
"autod": "midway-bin autod"
"autod": "midway-bin autod",
"link": "npm link"
},
"dependencies": {
"camelcase": "^5.0.0",
Expand Down
3 changes: 2 additions & 1 deletion packages/midway-web/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,8 @@
"mz-modules": "^2.1.0",
"pedding": "^1.1.0",
"react": "^16.2.0",
"react-dom": "^16.2.0"
"react-dom": "^16.2.0",
"egg-view-nunjucks": "^2.2.0"
},
"dependencies": {
"@eggjs/router": "^2.0.0",
Expand Down
43 changes: 35 additions & 8 deletions packages/midway-web/src/loader/webLoader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,22 @@ import {
RouterParamValue,
WEB_ROUTER_KEY,
WEB_ROUTER_PARAM_KEY,
getClassMetadata, getPropertyDataFromClass, getProviderId, listModule, PLUGIN_KEY, LOGGER_KEY, APPLICATION_KEY
getClassMetadata,
getPropertyDataFromClass,
getProviderId,
listModule,
PLUGIN_KEY,
LOGGER_KEY,
APPLICATION_KEY
} from '@midwayjs/decorator';
import { EggAppInfo } from 'egg';
import * as extend from 'extend2';
import * as fs from 'fs';
import { ContainerLoader, MidwayContainer } from '@midwayjs/core';
import { ContainerLoader, MidwayContainer, PRIVATE_META_DATA_KEY } from '@midwayjs/core';
import * as path from 'path';
import { Middleware, MiddlewareParamArray, MidwayLoaderOptions, WebMiddleware } from '../interface';
import { isTypeScriptEnvironment } from '../utils';
import { generateProvideId } from '@midwayjs/core/dist/common/util';

const graphviz = require('graphviz');
const debug = require('debug')(`midway:loader:${process.pid}`);
Expand Down Expand Up @@ -64,12 +71,11 @@ export class MidwayWebLoader extends EggLoader {
// 在 super constructor 中会调用到getAppInfo,之后会被赋值
// 如果是typescript会加上 dist 或者 src 目录
this.containerLoader = new ContainerLoader({
baseDir: this.appDir,
baseDir: this.baseDir,
isTsMode: this.isTsMode,
});
this.containerLoader.initialize();
this.applicationContext.registerObject('appDir', this.appDir);

// 外部给容器里设置环境
const envService = this.applicationContext.getEnvironmentService();
envService.setCurrentEnvironment(this.appInfo.env);
Expand All @@ -92,9 +98,26 @@ export class MidwayWebLoader extends EggLoader {
return this.options.logger;
});
// register app
this.containerLoader.registerHook(APPLICATION_KEY, (key: string) => {
return this.app;
});
this.containerLoader.registerHook(APPLICATION_KEY, () => new Proxy(this.app, {
get: (obj, prop) => {
if (prop === 'getBaseDir') {
return () => this.baseDir;
}
if (prop === 'getAppDir') {
return () => this.appDir;
}
if (prop === 'isTypeScriptMode') {
return () => this.isTsMode;
}
if (prop === 'getEnv') {
return () => this.appInfo.env;
}
if (prop === 'getType') {
return () => this.app.type;
}
return obj[prop];
}
}));
}

// loadPlugin -> loadConfig -> afterLoadConfig
Expand Down Expand Up @@ -319,7 +342,11 @@ export class MidwayWebLoader extends EggLoader {

// implement @controller
for (const module of controllerModules) {
const providerId = getProviderId(module);
let providerId = getProviderId(module);
const meta = getClassMetadata(PRIVATE_META_DATA_KEY, module);
if (providerId && meta) {
providerId = generateProvideId(providerId, meta.namespace);
}
if (providerId) {
if (this.controllerIds.indexOf(providerId) > -1) {
throw new Error(`controller identifier [${providerId}] is exists!`);
Expand Down
44 changes: 44 additions & 0 deletions packages/midway-web/test/enhance.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -299,6 +299,13 @@ describe('/test/enhance.test.ts', () => {
.expect('success')
.expect(200);
});

it('configuration package controller should be ok', async () => {
await app.httpRequest()
.get('/book/1')
.expect('[{"id":1,"name":"小森林","ISBN":"9787541089329","desc":"《小森林》是知名漫画家五十岚大介的经典作品,也是豆瓣高分电影《小森林》原著,讲述一位平凡女孩在田园生活中寻找自我的故事。"}]')
.expect(200);
});
});

describe('load ts file and use third party module', () => {
Expand Down Expand Up @@ -520,4 +527,41 @@ describe('/test/enhance.test.ts', () => {
.expect('11114444', done);
});
});

describe('shoule egg hackernew be ok', () => {
let app;
before(() => {
app = utils.app('enhance/base-app-hackernews', {
typescript: false,
});
return app.ready();
});

after(() => app.close());

it('news should be ok', async () => {
await app.httpRequest()
.get('/news')
.expect((res) => res.text.includes('<a href="/news/user/pseudolus">pseudolus</a>'))
.expect('Content-Type', /html/)
.expect(200);
});

it('new item should be ok', async () => {
await app.httpRequest()
.get('/news/item/1')
.expect((res) => res.text.includes('<a class="title" target="_blank" href="http://ycombinator.com">Y Combinator</a>'))
.expect('Content-Type', /html/)
.expect(200);
});

it('user should be ok', async () => {
// stevage
await app.httpRequest()
.get('/news/user/stevage')
.expect((res) => res.text.includes('Profile: stevage | egg - HackerNews'))
.expect('Content-Type', /html/)
.expect(200);
});
});
});

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading

0 comments on commit e4e3c57

Please sign in to comment.