Skip to content

Commit

Permalink
feat: add app event bind
Browse files Browse the repository at this point in the history
  • Loading branch information
richenlin committed Nov 8, 2023
1 parent 446daf2 commit 66e7a48
Show file tree
Hide file tree
Showing 5 changed files with 69 additions and 45 deletions.
8 changes: 4 additions & 4 deletions package-lock.json

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

4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@
"koa": "^2.14.2",
"koatty_config": "^1.1.6",
"koatty_container": "^1.8.1",
"koatty_core": "^1.7.10",
"koatty_core": "^1.8.1",
"koatty_exception": "^1.2.8",
"koatty_lib": "^1.3.4",
"koatty_loader": "^1.1.0",
Expand All @@ -91,4 +91,4 @@
"koatty_serve": "^2.0.4",
"koatty_trace": "^1.10.0"
}
}
}
32 changes: 14 additions & 18 deletions src/core/Bootstrap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,14 @@
*/
import "reflect-metadata";
import EventEmitter from "events";
import { Koatty } from 'koatty_core';
import { AppEvent, EventHookFunc, Koatty } from 'koatty_core';
import { Loader } from "./Loader";
import { Helper } from "../util/Helper";
import { Logger } from "../util/Logger";
import { IOCContainer, TAGGED_CLS } from "koatty_container";
import { BindProcessEvent, NewRouter, NewServe } from "koatty_serve";
import { checkRuntime, checkUTRuntime, KOATTY_VERSION } from "../util/Check";
import { APP_BOOT_HOOK, COMPONENT_SCAN, CONFIGURATION_SCAN, LOGO } from "./Constants";
import { COMPONENT_SCAN, CONFIGURATION_SCAN, LOGO } from "./Constants";

/**
* execute bootstrap
Expand Down Expand Up @@ -69,10 +69,10 @@ const executeBootstrap = async function (target: any, bootFunc: Function, isInit
const configurationMetas = Loader.GetConfigurationMetas(app, target);
Loader.LoadConfigs(app, configurationMetas);

// Load App ready hooks
Loader.LoadAppBootHooks(app, target);
// Load App event hooks
Loader.LoadAppEventHooks(app, target);
// app.emit("appBoot");
await asyncEvent(app, 'appBoot');
await asyncEvent(app, AppEvent.appBoot);

// Load Plugin
Logger.Log('Koatty', '', 'Load Plugins ...');
Expand All @@ -99,7 +99,7 @@ const executeBootstrap = async function (target: any, bootFunc: Function, isInit

// Emit app ready event
Logger.Log('Koatty', '', 'Emit App Ready ...');
await asyncEvent(app, 'appReady');
await asyncEvent(app, AppEvent.appReady);

// Load Routers
Logger.Log('Koatty', '', 'Load Routers ...');
Expand Down Expand Up @@ -177,7 +177,6 @@ export function Bootstrap(bootFunc?: Function): ClassDecorator {
};
}


/**
* Actively perform dependency injection
* Parse the decorator, return the instantiated app.
Expand Down Expand Up @@ -228,25 +227,22 @@ export function ConfigurationScan(scanPath?: string | string[]): ClassDecorator
};
}

// type AppBootHookFunc
export type AppBootHookFunc = (app: Koatty) => Promise<any>;

/**
* bind AppBootHookFunc
* @description: bind App event hook func
* example:
* export function TestDecorator(): ClassDecorator {
* return (target: any) => {
* BindAppBootHook((app: Koatty) => {
* BindEventHook(AppEvent.appBoot, (app: Koatty) => {
* // todo
* return Promise.resolve();
* }, target)
* }
* }
*
* @export
* @param {AppBootHookFunc} func
* @param {*} target
* @param {AppEvent} eventName
* @param {EventHookFunc} eventFunc
* @param {any} target
* @return {*}
*/
export function BindAppBootHook(func: AppBootHookFunc, target: any) {
IOCContainer.attachClassMetadata(TAGGED_CLS, APP_BOOT_HOOK, func, target);
export function BindEventHook(eventName: AppEvent, eventFunc: EventHookFunc, target: any) {
IOCContainer.attachClassMetadata(TAGGED_CLS, eventName, eventFunc, target);
}
2 changes: 0 additions & 2 deletions src/core/Constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,6 @@ export const COMPONENT_SCAN = 'COMPONENT_SCAN';
export const CONFIGURATION_SCAN = 'CONFIGURATION_SCAN';
export const PRIORITY_KEY = 'PRIORITY_KEY';

export const APP_BOOT_HOOK = "APP_BOOT_HOOK";

// tslint:disable: no-irregular-whitespace
export const LOGO = `
Expand Down
68 changes: 49 additions & 19 deletions src/core/Loader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,14 @@
*/
import * as path from "path";
import { Load } from "koatty_loader";
import { Koatty } from 'koatty_core';
import { AppEvent, AppEventArr, EventHookFunc, Koatty } from 'koatty_core';
import { LoadConfigs as loadConf } from "koatty_config";
import { Logger, LogLevelType, SetLogger } from "../util/Logger";
import { prevent } from "koatty_exception";
import { IMiddleware, IPlugin } from '../component/Component';
import { AppBootHookFunc } from "./Bootstrap";
import { checkClass, Helper } from "../util/Helper";
import { IOCContainer, TAGGED_CLS } from "koatty_container";
import { APP_BOOT_HOOK, COMPONENT_SCAN, CONFIGURATION_SCAN } from './Constants';
import { COMPONENT_SCAN, CONFIGURATION_SCAN } from './Constants';
import { BaseController } from "../component/BaseController";
import { TraceMiddleware } from "../middleware/TraceMiddleware";
import { PayloadMiddleware } from "../middleware/PayloadMiddleware";
Expand Down Expand Up @@ -66,10 +65,11 @@ export class Loader {
// define path
const rootPath = app.rootPath || process.cwd();
const appPath = app.appPath || path.resolve(rootPath, env.indexOf('ts-node') > -1 ? 'src' : 'dist');
const thinkPath = path.resolve(__dirname, '..');
const koattyPath = path.resolve(__dirname, '..');
Helper.define(app, 'rootPath', rootPath);
Helper.define(app, 'appPath', appPath);
Helper.define(app, 'thinkPath', thinkPath);
Helper.define(app, 'koattyPath', koattyPath);


//
if (Helper.isEmpty(app.name)) {
Expand All @@ -82,13 +82,12 @@ export class Loader {

process.env.ROOT_PATH = rootPath;
process.env.APP_PATH = appPath;
process.env.THINK_PATH = thinkPath;
process.env.KOATTY_PATH = koattyPath;

// Compatible with old version, will be deprecated
Helper.define(app, 'prevent', prevent);
Helper.define(app, 'root_path', rootPath);
Helper.define(app, 'app_path', appPath);
Helper.define(app, 'think_path', thinkPath);
Helper.define(app, 'thinkPath', koattyPath);
process.env.THINK_PATH = koattyPath;

}

Expand Down Expand Up @@ -193,20 +192,51 @@ export class Loader {


/**
* Load app ready hook funcs
* Load app event hook funcs
*
* @static
* @param {Koatty} app
* @param {*} target
* @memberof Loader
*/
public static LoadAppBootHooks(app: Koatty, target: any) {
const funcs = IOCContainer.getClassMetadata(TAGGED_CLS, APP_BOOT_HOOK, target);
if (Helper.isArray(funcs)) {
funcs.forEach((element: AppBootHookFunc): any => {
app.once('appBoot', () => element(app));
return null;
});
public static LoadAppEventHooks(app: Koatty, target: any) {
let eventFuncs: Map<string, EventHookFunc[]>;
for (const event of AppEventArr) {
let funcs: unknown;
switch (event) {
case AppEvent.appBoot:
funcs = IOCContainer.getClassMetadata(TAGGED_CLS, AppEvent.appBoot, target);
if (Helper.isArray(funcs)) {
eventFuncs.set(AppEvent.appBoot, funcs);
}
break;
case AppEvent.appReady:
funcs = IOCContainer.getClassMetadata(TAGGED_CLS, AppEvent.appReady, target);
if (Helper.isArray(funcs)) {
eventFuncs.set(AppEvent.appReady, funcs);
}
break;
case AppEvent.appStart:
funcs = IOCContainer.getClassMetadata(TAGGED_CLS, AppEvent.appStart, target);
if (Helper.isArray(funcs)) {
eventFuncs.set(AppEvent.appStart, funcs);
}
break;
case AppEvent.appStop:
funcs = IOCContainer.getClassMetadata(TAGGED_CLS, AppEvent.appStop, target);
if (Helper.isArray(funcs)) {
eventFuncs.set(AppEvent.appStop, funcs);
}
break;
default:
break;
}
}
// loop event emit
for (const [event, funcs] of eventFuncs) {
for (const func of funcs) {
app.once(event, () => func(app));
}
}
}

Expand All @@ -221,7 +251,7 @@ export class Loader {
public static LoadConfigs(app: Koatty, loadPath?: string[]) {
const frameConfig: any = {};
// Logger.Debug(`Load configuration path: ${app.thinkPath}/config`);
Load(["./config"], app.thinkPath, function (name: string, path: string, exp: any) {
Load(["./config"], app.koattyPath, function (name: string, path: string, exp: any) {
frameConfig[name] = exp;
});

Expand Down Expand Up @@ -249,7 +279,7 @@ export class Loader {
}

//Mount default middleware
Load(loadPath || ["./middleware"], app.thinkPath);
Load(loadPath || ["./middleware"], app.koattyPath);
//Mount application middleware
// const middleware: any = {};
const appMiddleware = IOCContainer.listClass("MIDDLEWARE") ?? [];
Expand Down

0 comments on commit 66e7a48

Please sign in to comment.