Skip to content

Commit

Permalink
chore: remove js test case
Browse files Browse the repository at this point in the history
  • Loading branch information
czy88840616 committed Mar 5, 2019
1 parent 2be03ff commit 3504391
Show file tree
Hide file tree
Showing 3 changed files with 118 additions and 218 deletions.
1 change: 1 addition & 0 deletions packages/midway-web/src/loader/loader.ts
Expand Up @@ -39,6 +39,7 @@ export class AgentWorkerLoader extends MidwayWebLoader {
load() {
this.loadAgentExtend();
this.loadApplicationContext();
this.loadContextExtend();
this.loadCustomAgent();
this.app.beforeStart(async () => {
await this.refreshContext();
Expand Down
269 changes: 117 additions & 152 deletions packages/midway-web/src/loader/webLoader.ts
Expand Up @@ -40,146 +40,19 @@ export class MidwayWebLoader extends EggLoader {
return this.app.options.typescript;
}

// loadPlugin -> loadConfig -> afterLoadConfig
loadConfig() {
this.loadPlugin();
super.loadConfig();
}

protected async loadMidwayController(): Promise<void> {
const controllerModules = listModule(CONTROLLER_KEY);

// implement @controller
for (const module of controllerModules) {
const providerId = getProviderId(module);
if (providerId) {
if (this.controllerIds.indexOf(providerId) > -1) {
throw new Error(`controller identifier [${providerId}] is exists!`);
}
this.controllerIds.push(providerId);
await this.preRegisterRouter(module, providerId);
}
}

// implement @priority
if (this.prioritySortRouters.length) {
this.prioritySortRouters = this.prioritySortRouters.sort((routerA, routerB) => {
return routerB.priority - routerA.priority;
});

this.prioritySortRouters.forEach((prioritySortRouter) => {
this.app.use(prioritySortRouter.router.middleware());
});
}
}

/**
* 从xml加载controller
*/
protected async preloadControllerFromXml(): Promise<void> {
const ids = this.applicationContext.controllersIds;
if (Array.isArray(ids) && ids.length > 0) {
for (const id of ids) {
const controllers = await this.applicationContext.getAsync(id);
const app = this.app;
if (Array.isArray(controllers.list)) {
controllers.list.forEach(c => {
const newRouter = new Router({
sensitive: true,
}, app);
c.expose(newRouter);

app.use(newRouter.middleware());
});
}
}
}
}

protected async preRegisterRouter(target, controllerId) {
const app = this.app;
const controllerOption: ControllerOption = getClassMetadata(CONTROLLER_KEY, target);
let newRouter;
if (controllerOption.prefix) {
newRouter = new Router({
sensitive: true,
}, app);
newRouter.prefix(controllerOption.prefix);
// implement @middleware
const middlewares = controllerOption.routerOptions.middleware;
if (middlewares && middlewares.length) {
for (const middleware of middlewares) {
const middlewareImpl: WebMiddleware = await this.applicationContext.getAsync(middleware);
if (middlewareImpl && middlewareImpl.resolve) {
newRouter.use(middlewareImpl.resolve());
}
}
}

// implement @get @post
const webRouterInfo: RouterOption[] = getClassMetadata(WEB_ROUTER_KEY, target);
if (webRouterInfo && typeof webRouterInfo[Symbol.iterator] === 'function') {
for (const webRouter of webRouterInfo) {
// get middleware
const middlewares = webRouter.middleware;
const methodMiddlwares = [];
if (middlewares && middlewares.length) {
for (const middleware of middlewares) {
const middlewareImpl: WebMiddleware = await this.applicationContext.getAsync(middleware);
if (middlewareImpl && middlewareImpl.resolve) {
methodMiddlwares.push(middlewareImpl.resolve());
}
}
}

const routerArgs = [
webRouter.routerName,
webRouter.path,
...methodMiddlwares,
this.generateController(`${controllerId}.${webRouter.method}`)
].concat(methodMiddlwares);

// apply controller from request context
newRouter[webRouter.requestMethod].apply(newRouter, routerArgs);
}
}
}

// sort for priority
if (newRouter) {
const priority = getClassMetadata(PRIORITY_KEY, target);
this.prioritySortRouters.push({
priority: priority || 0,
router: newRouter,
});
}
get applicationContext() {
return this.containerLoader.getApplicationContext();
}

/**
* wrap controller string to middleware function
* @param controllerMapping like xxxController.index
*/
public generateController(controllerMapping: string) {
const mappingSplit = controllerMapping.split('.');
const controllerId = mappingSplit[0];
const methodName = mappingSplit[1];
return async (ctx, next) => {
const controller = await ctx.requestContext.getAsync(controllerId);
return controller[methodName].call(controller, ctx, next);
};
get pluginContext() {
return this.containerLoader.getPluginContext();
}

public async refreshContext(): Promise<void> {
// 虽然有点hack,但是将就着用吧
if (Array.isArray(this.config.configLocations)) {
this.applicationContext.configLocations = this.config.configLocations;
this.applicationContext.props.putObject(this.config);
}

await this.containerLoader.refresh();
await this.preloadControllerFromXml();
// loadPlugin -> loadConfig -> afterLoadConfig
protected loadConfig() {
this.loadPlugin();
super.loadConfig();
}

// Get the real plugin path
protected getPluginPath(plugin) {
if (plugin.path) {
Expand Down Expand Up @@ -218,7 +91,7 @@ export class MidwayWebLoader extends EggLoader {
throw new Error(`Can not find plugin ${name} in "${lookupDirs.join(', ')}"`);
}

private registerTypescriptDirectory() {
protected registerTypescriptDirectory() {
const app = this.app;
// 处理 ts 的初始路径
this.appDir = this.baseDir = app.options.baseDir;
Expand All @@ -238,34 +111,30 @@ export class MidwayWebLoader extends EggLoader {
}
}

getEggPaths() {
protected getEggPaths() {
if (!this.appDir) {
// register appDir here
this.registerTypescriptDirectory();
}
return super.getEggPaths();
}

getServerEnv() {
protected getServerEnv() {
let serverEnv;

const envPath = path.join(this.appDir, 'config/env');
if (fs.existsSync(envPath)) {
serverEnv = fs.readFileSync(envPath, 'utf8').trim();
}

if (!serverEnv) {
serverEnv = process.env.EGG_SERVER_ENV || process.env.MIDWAY_SERVER_ENV;
}

if (!serverEnv) {
serverEnv = super.getServerEnv();
}

return serverEnv;
}

getAppInfo() {
protected getAppInfo() {
if (!this.appInfo) {
const appInfo = super.getAppInfo();
// ROOT == HOME in prod env
Expand All @@ -277,15 +146,7 @@ export class MidwayWebLoader extends EggLoader {
return this.appInfo;
}

get applicationContext() {
return this.containerLoader.getApplicationContext();
}

get pluginContext() {
return this.containerLoader.getPluginContext();
}

loadApplicationContext() {
protected loadApplicationContext() {
// this.app.options.container 测试用例编写方便点
const containerConfig = this.config.container || this.app.options.container || {};
// 在 super constructor 中会调用到getAppInfo,之后会被赋值
Expand Down Expand Up @@ -315,4 +176,108 @@ export class MidwayWebLoader extends EggLoader {
return this.options.logger;
});
}

protected async preRegisterRouter(target, controllerId) {
const app = this.app;
const controllerOption: ControllerOption = getClassMetadata(CONTROLLER_KEY, target);
let newRouter;
if (controllerOption.prefix) {
newRouter = new Router({
sensitive: true,
}, app);
newRouter.prefix(controllerOption.prefix);
// implement @middleware
const middlewares = controllerOption.routerOptions.middleware;
if (middlewares && middlewares.length) {
for (const middleware of middlewares) {
const middlewareImpl: WebMiddleware = await this.applicationContext.getAsync(middleware);
if (middlewareImpl && middlewareImpl.resolve) {
newRouter.use(middlewareImpl.resolve());
}
}
}

// implement @get @post
const webRouterInfo: RouterOption[] = getClassMetadata(WEB_ROUTER_KEY, target);
if (webRouterInfo && typeof webRouterInfo[Symbol.iterator] === 'function') {
for (const webRouter of webRouterInfo) {
// get middleware
const middlewares = webRouter.middleware;
const methodMiddlwares = [];
if (middlewares && middlewares.length) {
for (const middleware of middlewares) {
const middlewareImpl: WebMiddleware = await this.applicationContext.getAsync(middleware);
if (middlewareImpl && middlewareImpl.resolve) {
methodMiddlwares.push(middlewareImpl.resolve());
}
}
}

const routerArgs = [
webRouter.routerName,
webRouter.path,
...methodMiddlwares,
this.generateController(`${controllerId}.${webRouter.method}`)
].concat(methodMiddlwares);

// apply controller from request context
newRouter[webRouter.requestMethod].apply(newRouter, routerArgs);
}
}
}

// sort for priority
if (newRouter) {
const priority = getClassMetadata(PRIORITY_KEY, target);
this.prioritySortRouters.push({
priority: priority || 0,
router: newRouter,
});
}
}

protected async refreshContext(): Promise<void> {
await this.containerLoader.refresh();
}
/**
* wrap controller string to middleware function
* @param controllerMapping like xxxController.index
*/
public generateController(controllerMapping: string) {
const mappingSplit = controllerMapping.split('.');
const controllerId = mappingSplit[0];
const methodName = mappingSplit[1];
return async (ctx, next) => {
const controller = await ctx.requestContext.getAsync(controllerId);
return controller[methodName].call(controller, ctx, next);
};
}

public async loadMidwayController(): Promise<void> {
const controllerModules = listModule(CONTROLLER_KEY);

// implement @controller
for (const module of controllerModules) {
const providerId = getProviderId(module);
if (providerId) {
if (this.controllerIds.indexOf(providerId) > -1) {
throw new Error(`controller identifier [${providerId}] is exists!`);
}
this.controllerIds.push(providerId);
await this.preRegisterRouter(module, providerId);
}
}

// implement @priority
if (this.prioritySortRouters.length) {
this.prioritySortRouters = this.prioritySortRouters.sort((routerA, routerB) => {
return routerB.priority - routerA.priority;
});

this.prioritySortRouters.forEach((prioritySortRouter) => {
this.app.use(prioritySortRouter.router.middleware());
});
}
}

}

0 comments on commit 3504391

Please sign in to comment.