Skip to content

Commit

Permalink
fix: load functional config (#1017)
Browse files Browse the repository at this point in the history
  • Loading branch information
czy88840616 authored Apr 29, 2021
1 parent 183d20a commit 51566c0
Show file tree
Hide file tree
Showing 15 changed files with 163 additions and 33 deletions.
41 changes: 19 additions & 22 deletions packages/core/src/baseFramework.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,9 @@ import {
} from '@midwayjs/logger';
import { dirname, isAbsolute, join } from 'path';
import { createMidwayLogger } from './logger';
import { safeRequire } from './util';
import { MidwayRequestContainer } from './context/requestContainer';
import { FunctionalConfiguration } from './functional/configuration';
import { MidwayInformationService } from './service/informationService';

function buildLoadDir(baseDir, dir) {
if (!isAbsolute(dir)) {
Expand All @@ -48,14 +48,11 @@ export abstract class BaseFramework<
OPT extends IConfigurationOptions
> implements IMidwayFramework<APP, OPT> {
protected isTsMode = true;
protected baseDir: string;
protected appDir: string;
protected applicationContext: IMidwayContainer;
protected logger: ILogger;
protected appLogger: ILogger;
public configurationOptions: OPT;
public app: APP;
protected pkg: Record<string, unknown>;
protected defaultContext = {};
protected BaseContextLoggerClass: any;
protected isMainFramework: boolean;
Expand All @@ -71,11 +68,6 @@ export abstract class BaseFramework<
}

public async initialize(options: IMidwayBootstrapOptions): Promise<void> {
this.baseDir = options.baseDir;
if (!options.appDir) {
options.appDir = setupAppDir(options.baseDir);
}
this.appDir = options.appDir;
this.isMainFramework = options.isMainFramework;

/**
Expand Down Expand Up @@ -129,8 +121,9 @@ export abstract class BaseFramework<
}

protected async initializeInfo(options: IMidwayBootstrapOptions) {
if (!this.pkg) {
this.pkg = safeRequire(join(this.appDir, 'package.json'));
if (!this.applicationContext.getInformationService()) {
const informationService = new MidwayInformationService(options);
this.applicationContext.setInformationService(informationService);
}
}

Expand All @@ -149,15 +142,18 @@ export abstract class BaseFramework<
}

protected async containerInitialize(options: IMidwayBootstrapOptions) {
if (!options.appDir) {
options.appDir = setupAppDir(options.baseDir);
}
/**
* initialize container
*/
if (options.applicationContext) {
this.applicationContext = options.applicationContext;
} else {
this.applicationContext = new MidwayContainer(this.baseDir, undefined);
this.applicationContext.registerObject('baseDir', this.baseDir);
this.applicationContext.registerObject('appDir', this.appDir);
this.applicationContext = new MidwayContainer(options.baseDir, undefined);
this.applicationContext.registerObject('baseDir', options.baseDir);
this.applicationContext.registerObject('appDir', options.appDir);
this.applicationContext.registerObject('isTsMode', this.isTsMode);
}

Expand Down Expand Up @@ -188,11 +184,10 @@ export abstract class BaseFramework<
if (options.disableAutoLoad) return;

// use baseDir in parameter first
const baseDir = options.baseDir || this.baseDir;
const defaultLoadDir = this.isTsMode ? [baseDir] : [];
const defaultLoadDir = this.isTsMode ? [options.baseDir] : [];
this.applicationContext.load({
loadDir: (options.loadDir || defaultLoadDir).map(dir => {
return buildLoadDir(baseDir, dir);
return buildLoadDir(options.baseDir, dir);
}),
pattern: options.pattern,
ignore: options.ignore,
Expand Down Expand Up @@ -289,11 +284,11 @@ export abstract class BaseFramework<
}

public getAppDir(): string {
return this.appDir;
return this.applicationContext.getInformationService().getAppDir();
}

public getBaseDir(): string {
return this.baseDir;
return this.applicationContext.getInformationService().getBaseDir();
}

protected defineApplicationProperties(
Expand All @@ -302,11 +297,13 @@ export abstract class BaseFramework<
) {
const defaultApplicationProperties = {
getBaseDir: () => {
return this.baseDir;
return this.getApplicationContext()
.getInformationService()
.getBaseDir();
},

getAppDir: () => {
return this.appDir;
return this.getApplicationContext().getInformationService().getAppDir();
},

getEnv: () => {
Expand Down Expand Up @@ -493,7 +490,7 @@ export abstract class BaseFramework<
}

public getProjectName() {
return (this.pkg?.['name'] as string) || '';
return this.applicationContext.getInformationService().getProjectName();
}

public getFrameworkName() {
Expand Down
10 changes: 10 additions & 0 deletions packages/core/src/context/midwayContainer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ import {
IConfigService,
IContainerConfiguration,
IEnvironmentService,
IInformationService,
IMidwayContainer,
IObjectDefinitionMetadata,
REQUEST_CTX_KEY,
Expand Down Expand Up @@ -83,6 +84,7 @@ export class MidwayContainer
private likeMainConfiguration: IContainerConfiguration[] = [];
protected configService: IConfigService;
protected environmentService: IEnvironmentService;
protected informationService: IInformationService;
protected aspectService;
private directoryFilterArray: ResolveFilter[] = [];

Expand Down Expand Up @@ -568,6 +570,14 @@ export class MidwayContainer
return this.environmentService;
}

getInformationService() {
return this.informationService;
}

setInformationService(informationService) {
this.informationService = informationService;
}

getAspectService() {
return this.aspectService;
}
Expand Down
1 change: 1 addition & 0 deletions packages/core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ export { plainToClass, classToPlain } from 'class-transformer';
export { createConfiguration } from './functional/configuration';
export { MidwayConfigService } from './service/configService';
export { MidwayEnvironmentService } from './service/environmentService';
export { MidwayInformationService } from './service/informationService';
export * from './logger';
export * from './util/contextUtil';
/**
Expand Down
11 changes: 11 additions & 0 deletions packages/core/src/interface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -273,6 +273,8 @@ export interface IMidwayContainer extends IApplicationContext {
addConfiguration(configuration: IContainerConfiguration);
getConfigService(): IConfigService;
getEnvironmentService(): IEnvironmentService;
getInformationService(): IInformationService;
setInformationService(service: IInformationService): void;
getAspectService(): IAspectService;
getCurrentEnv(): string;
getResolverHandler(): IResolverHandler;
Expand All @@ -287,6 +289,15 @@ export interface IConfigService {
clearAllConfig();
}

export interface IInformationService {
getPkg(): any;
getProjectName(): any;
getBaseDir(): string;
getAppDir(): string;
getHome(): string;
getRoot(): string;
}

export interface IEnvironmentService {
getCurrentEnvironment(): string;
setCurrentEnvironment(environment: string);
Expand Down
6 changes: 6 additions & 0 deletions packages/core/src/loader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
listModule,
} from '@midwayjs/decorator';
import { ILifeCycle, IMidwayContainer } from './interface';
import { MidwayInformationService } from './service/informationService';

function buildLoadDir(baseDir, dir) {
if (!path.isAbsolute(dir)) {
Expand Down Expand Up @@ -38,6 +39,11 @@ export class ContainerLoader {

initialize() {
this.applicationContext = new MidwayContainer(this.baseDir, undefined);
this.applicationContext.setInformationService(
new MidwayInformationService({
baseDir: this.baseDir,
})
);
this.applicationContext.disableConflictCheck = this.disableConflictCheck;
this.applicationContext.registerObject('baseDir', this.baseDir);
this.applicationContext.registerObject('isTsMode', this.isTsMode);
Expand Down
10 changes: 6 additions & 4 deletions packages/core/src/logger.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { createLogger, LoggerOptions } from '@midwayjs/logger';
import { IMidwayFramework, MIDWAY_LOGGER_WRITEABLE_DIR } from './interface';
import { isDevelopmentEnvironment, getUserHome } from './util';
import { isDevelopmentEnvironment } from './util';
import { join } from 'path';

export const createMidwayLogger = (
Expand All @@ -12,9 +12,11 @@ export const createMidwayLogger = (
framework.getCurrentEnvironment()
);
const loggerOptions: LoggerOptions = {
dir: isDevelopmentEnv
? join(framework.getAppDir(), 'logs', framework.getProjectName())
: join(getUserHome(), 'logs', framework.getProjectName()),
dir: join(
framework.getApplicationContext().getInformationService().getRoot(),
'logs',
framework.getProjectName()
),
level: isDevelopmentEnv ? 'info' : 'warn',
};
if (process.env[MIDWAY_LOGGER_WRITEABLE_DIR]) {
Expand Down
12 changes: 11 additions & 1 deletion packages/core/src/service/configService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -121,8 +121,18 @@ export class MidwayConfigService implements IConfigService {
}
let result = exports;
if (isFunction(exports)) {
const informationService = this.container.getInformationService();
// eslint-disable-next-line prefer-spread
result = await exports.apply(null, [].concat(this.container));
result = exports.apply(null, [
{
pkg: informationService.getPkg(),
name: informationService.getProjectName(),
baseDir: informationService.getBaseDir(),
appDir: informationService.getAppDir(),
HOME: informationService.getHome(),
root: informationService.getRoot(),
},
]);
}
return result;
}
Expand Down
5 changes: 2 additions & 3 deletions packages/core/src/service/environmentService.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
import { IEnvironmentService } from '../interface';
import { isDevelopmentEnvironment } from '../util';
import { isDevelopmentEnvironment, getCurrentEnvironment } from '../util';

export class MidwayEnvironmentService implements IEnvironmentService {
environment: string;

getCurrentEnvironment() {
if (!this.environment) {
this.environment =
process.env['MIDWAY_SERVER_ENV'] || process.env['NODE_ENV'] || 'prod';
this.environment = getCurrentEnvironment();
}
return this.environment;
}
Expand Down
48 changes: 48 additions & 0 deletions packages/core/src/service/informationService.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import { IInformationService } from '../interface';
import {
getCurrentEnvironment,
getUserHome,
isDevelopmentEnvironment,
safeRequire,
} from '../util';
import { dirname, join } from 'path';

export class MidwayInformationService implements IInformationService {
protected pkg: Record<string, unknown>;
private readonly appDir: string;
private readonly baseDir: string;

constructor(options: { baseDir?: string; appDir?: string }) {
this.baseDir = options.baseDir;
this.appDir = options.appDir;
if (!this.appDir) {
this.appDir = dirname(this.baseDir);
}
this.pkg = safeRequire(join(this.appDir, 'package.json')) || {};
}

getAppDir(): string {
return this.appDir;
}

getBaseDir(): string {
return this.baseDir;
}

getHome(): string {
return getUserHome();
}

getPkg(): any {
return this.pkg;
}

getProjectName(): string {
return (this.pkg?.['name'] as string) || '';
}

getRoot(): string {
const isDevelopmentEnv = isDevelopmentEnvironment(getCurrentEnvironment());
return isDevelopmentEnv ? this.getAppDir() : this.getHome();
}
}
4 changes: 4 additions & 0 deletions packages/core/src/util/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,10 @@ export const isDevelopmentEnvironment = env => {
return ['local', 'test', 'unittest'].includes(env);
};

export const getCurrentEnvironment = () => {
return process.env['MIDWAY_SERVER_ENV'] || process.env['NODE_ENV'] || 'prod';
};

export const safeRequire = (p, enabledCache = true) => {
if (p.startsWith(`.${sep}`) || p.startsWith(`..${sep}`)) {
p = resolve(dirname(module.parent.filename), p);
Expand Down
8 changes: 8 additions & 0 deletions packages/core/test/services/configService.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,16 @@ import { resolve, join } from 'path';
import { MidwayContainer } from '../../src';
import { MidwayConfigService } from '../../src/service/configService';
import * as mm from 'mm';
import { MidwayInformationService } from '../../dist/service/informationService';

describe('/test/services/configService.test.ts', () => {
const informationService = new MidwayInformationService({
baseDir: join(__dirname, 'fixtures/default_case'),
appDir: join(__dirname, 'fixtures/default_case'),
})
it('configService should be ok', () => {
const container = new MidwayContainer();
container.setInformationService(informationService);
const cfg = new MidwayConfigService(container);
cfg.isReady = true;
cfg.configuration = {t: 1};
Expand All @@ -24,6 +30,7 @@ describe('/test/services/configService.test.ts', () => {

it('load config should be ok', async () => {
const container = new MidwayContainer();
container.setInformationService(informationService);
const cfg = new MidwayConfigService(container);
const configFile = resolve(join(__dirname, '../fixtures/config', 'config.default'));
const result = await cfg.loadConfig(configFile);
Expand Down Expand Up @@ -52,6 +59,7 @@ describe('/test/services/configService.test.ts', () => {

it('load should be ok', async () => {
const container = new MidwayContainer();
container.setInformationService(informationService);
const cfg = new MidwayConfigService(container);

cfg.addObject({bb: 222});
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"name": "test-demo"
}
33 changes: 33 additions & 0 deletions packages/core/test/services/informationService.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { join } from 'path';
import { MidwayInformationService } from '../../src';
import { getUserHome } from '../../src/util';

describe('/test/services/informationService.test.ts', () => {
it('informationService should be ok', () => {
process.env.NODE_ENV = 'local';
const informationService = new MidwayInformationService({
baseDir: join(__dirname, 'fixtures/default_case'),
appDir: join(__dirname, 'fixtures/default_case'),
});
expect(informationService.getAppDir()).toEqual(join(__dirname, 'fixtures/default_case'));
expect(informationService.getBaseDir()).toEqual(join(__dirname, 'fixtures/default_case'));
expect(informationService.getHome()).toEqual(getUserHome());
expect(informationService.getProjectName()).toEqual('test-demo');
expect(informationService.getPkg()).toEqual({
name: 'test-demo'
});
expect(informationService.getRoot()).toEqual(informationService.getAppDir());
process.env.NODE_ENV = undefined;
});

it('should find appDir with dirname', () => {
process.env.NODE_ENV = 'prod';
const informationService = new MidwayInformationService({
baseDir: join(__dirname, 'fixtures/default_case/src'),
});
expect(informationService.getAppDir()).toEqual(join(__dirname, 'fixtures/default_case'));
expect(informationService.getBaseDir()).toEqual(join(__dirname, 'fixtures/default_case/src'));
expect(informationService.getRoot()).toEqual(informationService.getHome());
process.env.NODE_ENV = undefined;
});
});
Loading

0 comments on commit 51566c0

Please sign in to comment.