Skip to content

Commit

Permalink
feat: support importConfigs and add test case
Browse files Browse the repository at this point in the history
  • Loading branch information
czy88840616 committed Feb 4, 2020
1 parent 228bf1e commit 753cfb4
Show file tree
Hide file tree
Showing 15 changed files with 122 additions and 48 deletions.
3 changes: 2 additions & 1 deletion packages/midway-core/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,8 @@
"license": "MIT",
"devDependencies": {
"chai": "^4.2.0",
"midway-bin": "^1.16.3"
"midway-bin": "^1.16.3",
"mm": "^2.5.0"
},
"dependencies": {
"@midwayjs/decorator": "^1.16.3",
Expand Down
4 changes: 4 additions & 0 deletions packages/midway-core/src/container.ts
Original file line number Diff line number Diff line change
Expand Up @@ -353,6 +353,10 @@ export class MidwayContainer extends Container implements IMidwayContainer {

async ready() {
super.ready();
// register handler for container
this.registerDataHandler(MidwayHandlerKey.CONFIG, (key: string) => {
return this.configService.getConfiguration(key);
});
// 加载配置
await this.configService.load();
}
Expand Down
2 changes: 1 addition & 1 deletion packages/midway-core/src/interface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ export interface IConfigService {
add(configFilePaths: string[]);
addObject(obj: object);
load();
getConfiguration();
getConfiguration(configKey?: string);
}

export interface IEnvironmentService {
Expand Down
9 changes: 5 additions & 4 deletions packages/midway-core/src/service/configService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import * as extend from 'extend2';
import * as is from 'is-type-of';
import { basename } from 'path';
import { IConfigService, IMidwayContainer } from '../interface';
import { safelyGet } from '../util';

const debug = require('debug')('midway:config');

Expand Down Expand Up @@ -78,12 +79,12 @@ export class MidwayConfigService implements IConfigService {
}
}
this.configuration = target;
this.isReady = true;
}

async getConfiguration() {
if (!this.isReady) {
await this.load();
this.isReady = true;
getConfiguration(configKey) {
if (configKey) {
return safelyGet(configKey, this.configuration);
}
return this.configuration;
}
Expand Down
2 changes: 1 addition & 1 deletion packages/midway-core/src/service/environmentService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ export class MidwayEnvironmentService implements IEnvironmentService {

getCurrentEnvironment() {
if (!this.environment) {
this.environment = process['MIDWAY_SERVER_ENV'] || process['NODE_ENV'] || 'production';
this.environment = process.env['MIDWAY_SERVER_ENV'] || process.env['NODE_ENV'] || 'production';
}
return this.environment;
}
Expand Down
31 changes: 31 additions & 0 deletions packages/midway-core/src/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,3 +18,34 @@ export const isPath = (p): boolean => {
}
return false;
};

/**
* safelyGet(['a','b'],{a: {b: 2}}) // => 2
* safelyGet(['a','b'],{c: {b: 2}}) // => undefined
* safelyGet(['a','1'],{a: {"1": 2}}) // => 2
* safelyGet(['a','1'],{a: {b: 2}}) // => undefined
* safelyGet('a.b',{a: {b: 2}}) // => 2
* safelyGet('a.b',{c: {b: 2}}) // => undefined
*/
export function safelyGet(list: string | string[], obj?: object): any {
if (arguments.length === 1) {
return (_obj: object) => safelyGet(list, _obj);
}

if (typeof obj === 'undefined' || typeof obj !== 'object' || obj === null) {
return void 0;
}
const pathArrValue = typeof list === 'string' ? list.split('.') : list;
let willReturn: any = obj;

for (const key of pathArrValue) {
if (typeof willReturn === 'undefined' || willReturn === null) {
return void 0;
} else if (typeof willReturn !== 'object') {
return void 0;
}
willReturn = willReturn[key];
}

return willReturn;
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import { Configuration } from '@midwayjs/decorator';

@Configuration({
imports: ['../../midway-plugin-mock/src'],
imports: [
'../../midway-plugin-mock/src',
'../../midway-plugin-ok/src'
],
})
export class AutoConfiguraion {}
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { Provide } from '@midwayjs/decorator';

@Provide()
export class ArticleManager {
export class ReplaceManager {
async getOne() {
return 'ok';
return 'one article';
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export = {
ok: {
text: 'ok'
}
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export = {
ok: {
text: 'ok1'
}
};
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
import { Configuration } from '@midwayjs/decorator';

@Configuration({
namespace: 'ok'
namespace: 'ok',
importConfigs: [
'./config/config.default',
'./config/config.local'
]
})
export class AutoConfiguraion {}
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { Config, Provide } from '@midwayjs/decorator';

@Provide()
export class ReplaceManager {

@Config('ok.text')
config;

async getOne() {
return this.config;
}
}
44 changes: 44 additions & 0 deletions packages/midway-core/test/loader.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
import * as assert from 'assert';
import * as path from 'path';
import { ContainerLoader, MidwayRequestContainer } from '../src';
import * as mm from 'mm';

@Provide()
class TestModule {
Expand Down Expand Up @@ -194,4 +195,47 @@ describe('/test/loader.test.ts', () => {
const baseService: any = await appCtx.getAsync('baseService');
assert(await baseService.getInformation() === 'harry,one article');
});

it('should load config.*.ts by default env', async () => {
const loader = new ContainerLoader({
baseDir: path.join(__dirname, './fixtures/app-with-configuration/base-app-decorator/src'),
});
loader.initialize();
loader.loadDirectory();
await loader.refresh();

const appCtx = loader.getApplicationContext();
const replaceManager: any = await appCtx.getAsync('replaceManager');
assert(await replaceManager.getOne() === 'ok');
});

it('should load config.*.ts by process.env', async () => {
mm(process.env, 'NODE_ENV', 'local');
const loader = new ContainerLoader({
baseDir: path.join(__dirname, './fixtures/app-with-configuration/base-app-decorator/src'),
});
loader.initialize();
loader.loadDirectory();
await loader.refresh();

const appCtx = loader.getApplicationContext();
const replaceManager: any = await appCtx.getAsync('replaceManager');
assert(await replaceManager.getOne() === 'ok1');
mm.restore();
});

it('should load config.*.ts by process.env MIDWAY_SERVER_ENV', async () => {
mm(process.env, 'MIDWAY_SERVER_ENV', 'local');
const loader = new ContainerLoader({
baseDir: path.join(__dirname, './fixtures/app-with-configuration/base-app-decorator/src'),
});
loader.initialize();
loader.loadDirectory();
await loader.refresh();

const appCtx = loader.getApplicationContext();
const replaceManager: any = await appCtx.getAsync('replaceManager');
assert(await replaceManager.getOne() === 'ok1');
mm.restore();
});
});
7 changes: 1 addition & 6 deletions packages/midway-web/src/loader/webLoader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import * as fs from 'fs';
import { ContainerLoader, MidwayContainer, MidwayHandlerKey, getClassMetadata, getPropertyDataFromClass, getProviderId, listModule } from '@midwayjs/core';
import * as path from 'path';
import { Middleware, MiddlewareParamArray, MidwayLoaderOptions, WebMiddleware } from '../interface';
import { isTypeScriptEnvironment, safelyGet } from '../utils';
import { isTypeScriptEnvironment } from '../utils';

const debug = require('debug')(`midway:loader:${process.pid}`);
const EggLoader = require('egg-core').EggLoader;
Expand Down Expand Up @@ -79,11 +79,6 @@ export class MidwayWebLoader extends EggLoader {
// 如果没有关闭autoLoad 则进行load
this.containerLoader.loadDirectory(containerConfig);

// register handler for container
this.containerLoader.registerHook(MidwayHandlerKey.CONFIG, (key: string) => {
return safelyGet(key, this.config);
});

this.containerLoader.registerHook(MidwayHandlerKey.PLUGIN, (key: string) => {
return this.app[key] || this.pluginContext.get(key);
});
Expand Down
31 changes: 0 additions & 31 deletions packages/midway-web/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,34 +45,3 @@ export function getMethodNames(obj: object): string[] {
export function isTypeScriptEnvironment(): boolean {
return !!require.extensions['.ts'] || process.env.MIDWAY_TS_MODE === 'true';
}

/**
* safelyGet(['a','b'],{a: {b: 2}}) // => 2
* safelyGet(['a','b'],{c: {b: 2}}) // => undefined
* safelyGet(['a','1'],{a: {"1": 2}}) // => 2
* safelyGet(['a','1'],{a: {b: 2}}) // => undefined
* safelyGet('a.b',{a: {b: 2}}) // => 2
* safelyGet('a.b',{c: {b: 2}}) // => undefined
*/
export function safelyGet(list: string | string[], obj?: object): any {
if (arguments.length === 1) {
return (_obj: object) => safelyGet(list, _obj);
}

if (typeof obj === 'undefined' || typeof obj !== 'object' || obj === null) {
return void 0;
}
const pathArrValue = typeof list === 'string' ? list.split('.') : list;
let willReturn: any = obj;

for (const key of pathArrValue) {
if (typeof willReturn === 'undefined' || willReturn === null) {
return void 0;
} else if (typeof willReturn !== 'object') {
return void 0;
}
willReturn = willReturn[key];
}

return willReturn;
}

0 comments on commit 753cfb4

Please sign in to comment.