Skip to content

Commit

Permalink
feat: load default class early (#139)
Browse files Browse the repository at this point in the history
* feat: load default class early

* fix(logger): load appConfig dynamicly

* test(app): resolve conflict
  • Loading branch information
noahziheng authored Jul 18, 2022
1 parent f132863 commit e8e2d1c
Show file tree
Hide file tree
Showing 8 changed files with 55 additions and 27 deletions.
13 changes: 4 additions & 9 deletions src/application.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,14 @@ export class ArtusApplication implements Application {

protected lifecycleManager: LifecycleManager;
protected loaderFactory: LoaderFactory;
protected defaultClazzLoaded = false;

constructor(opts?: ApplicationInitOptions) {
this.container = new Container(opts?.containerName ?? ArtusInjectEnum.DefaultContainerName);
this.lifecycleManager = new LifecycleManager(this, this.container);
this.loaderFactory = LoaderFactory.create(this.container);

this.loadDefaultClass();

process.on('SIGINT', () => this.close(true));
process.on('SIGTERM', () => this.close(true));
}
Expand Down Expand Up @@ -54,25 +55,19 @@ export class ArtusApplication implements Application {
return this.container.get(ConfigurationHandler);
}

async loadDefaultClass() {
loadDefaultClass() {
// load Artus default clazz
this.container.set({ id: Container, value: this.container });
this.container.set({ id: ArtusInjectEnum.Application, value: this });
this.container.set({ id: ArtusInjectEnum.LifecycleManager, value: this.lifecycleManager });

// SEEME: 暂时使用 set 进行注入,后续考虑更改为 Loader
this.container.set({ type: ConfigurationHandler });
this.container.set({ type: ArtusLogger });
this.container.set({ type: Trigger });
this.container.set({ type: ExceptionHandler });

this.defaultClazzLoaded = true;
}

async load(manifest: Manifest, root: string = process.cwd()) {
if (!this.defaultClazzLoaded) {
await this.loadDefaultClass();
}

// Load user manifest
this.manifest = manifest;

Expand Down
2 changes: 2 additions & 0 deletions src/constant.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,3 +62,5 @@ export const DEFAULT_LOADER_LIST_WITH_ORDER = [
];

export const DEFAULT_CONFIG_DIR = 'src/config';

export const SHOULD_OVERWRITE_VALUE = 'shouldOverwrite';
5 changes: 4 additions & 1 deletion src/loader/impl/module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { Container, InjectableDefinition } from '@artus/injection';
import { DefineLoader } from '../decorator';
import { ManifestItem, Loader } from '../types';
import compatibleRequire from '../../utils/compatible_require';
import { SHOULD_OVERWRITE_VALUE } from '../../constant';

@DefineLoader('module')
class ModuleLoader implements Loader {
Expand All @@ -21,7 +22,9 @@ class ModuleLoader implements Loader {
opts.id = item.id;
}

if(!this.container.hasValue(opts)) {
const shouldOverwriteValue = Reflect.getMetadata(SHOULD_OVERWRITE_VALUE, moduleClazz);

if(shouldOverwriteValue || !this.container.hasValue(opts)) {
this.container.set(opts);
}
}
Expand Down
14 changes: 10 additions & 4 deletions src/logger/base.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,21 @@
import { Inject } from '@artus/injection';
import { Container, Inject } from '@artus/injection';
import { ArtusInjectEnum } from '../constant';
import { LoggerLevel, LOGGER_LEVEL_MAP } from './level';
import { Logger, LoggerOptions, LogOptions } from './types';

export class BaseLogger implements Logger {

@Inject(ArtusInjectEnum.Config)
private appConfig!: Record<string, any>;
@Inject()
private container!: Container;

protected get loggerOpts(): LoggerOptions {
return this.appConfig?.logger ?? {};
let appConfig: Record<string, any> = {};
try {
appConfig = this.container.get(ArtusInjectEnum.Config);
} catch(e) {
// do nothing
}
return appConfig?.logger ?? {};
}

protected checkLoggerLevel(level: LoggerLevel) {
Expand Down
15 changes: 9 additions & 6 deletions src/logger/decorator.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
import { Injectable, InjectableOption, ScopeEnum } from '@artus/injection';
import { ArtusInjectEnum } from '../constant';
import { ArtusInjectEnum, SHOULD_OVERWRITE_VALUE } from '../constant';

export const DefineLogger = (injectableOpts: InjectableOption = {}): ClassDecorator => {
return Injectable({
id: ArtusInjectEnum.Logger,
scope: ScopeEnum.SINGLETON,
...injectableOpts,
});
return (target: any) => {
Reflect.defineMetadata(SHOULD_OVERWRITE_VALUE, true, target);
return Injectable({
id: ArtusInjectEnum.Logger,
scope: ScopeEnum.SINGLETON,
...injectableOpts,
})(target);
};
};
13 changes: 8 additions & 5 deletions src/trigger/decorator.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
import { Injectable, ScopeEnum } from '@artus/injection';
import { ArtusInjectEnum } from '../constant';
import { ArtusInjectEnum, SHOULD_OVERWRITE_VALUE } from '../constant';

export function DefineTrigger(): ClassDecorator {
return (target:any) => Injectable({
id: ArtusInjectEnum.Trigger,
scope: ScopeEnum.SINGLETON,
})(target);
return (target:any) => {
Reflect.defineMetadata(SHOULD_OVERWRITE_VALUE, true, target);
return Injectable({
id: ArtusInjectEnum.Trigger,
scope: ScopeEnum.SINGLETON,
})(target);
};
}
17 changes: 16 additions & 1 deletion test/app.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import 'reflect-metadata';
import axios from 'axios';
import assert from 'assert';
import { ArtusInjectEnum, ConfigurationHandler, ExceptionHandler } from '../src';
import HttpTrigger from './fixtures/app_koa_with_ts/src/http_trigger';

describe('test/app.test.ts', () => {
describe('app koa with ts', () => {
Expand All @@ -16,10 +18,23 @@ describe('test/app.test.ts', () => {

try {
const {
app,
main,
isListening,
} = await import('./fixtures/app_koa_with_ts/src/bootstrap');
const app = await main();

// Check Artus Default Class Inject to Contianer
expect(() => app.container.get(ArtusInjectEnum.Application)).not.toThrow();
expect(() => app.container.get(ArtusInjectEnum.LifecycleManager)).not.toThrow();
expect(() => app.container.get(ArtusInjectEnum.Logger)).not.toThrow();
expect(() => app.container.get(ArtusInjectEnum.Trigger)).not.toThrow();
expect(() => app.container.get(ExceptionHandler)).not.toThrow();
expect(() => app.container.get(ConfigurationHandler)).not.toThrow();

await main();

expect(app.container.get(ArtusInjectEnum.Trigger)).toBeInstanceOf(HttpTrigger);

const testResponse = await axios.get('http://127.0.0.1:3000', {
headers: {
'x-hello-artus': 'true',
Expand Down
3 changes: 2 additions & 1 deletion test/fixtures/app_koa_with_ts/src/bootstrap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,9 @@ import path from 'path';
import { ArtusApplication } from '../../../../src';
import { server } from './app';

export const app: ArtusApplication = new ArtusApplication();

async function main() {
const app: ArtusApplication = new ArtusApplication();
await app.load({
items: [
{
Expand Down

0 comments on commit e8e2d1c

Please sign in to comment.