Skip to content

Commit

Permalink
fix: @plugin inject undefined in web middleware (#667)
Browse files Browse the repository at this point in the history
  • Loading branch information
czy88840616 authored Oct 12, 2020
1 parent a613546 commit cacb2fa
Show file tree
Hide file tree
Showing 27 changed files with 188 additions and 75 deletions.
13 changes: 8 additions & 5 deletions packages/core/src/context/configuration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import {

import { dirname, isAbsolute, join } from 'path';
import { MAIN_MODULE_KEY, generateProvideId } from '@midwayjs/decorator';
import { IContainerConfiguration, IMidwayContainer, } from '../interface';
import { IContainerConfiguration, IMidwayContainer } from '../interface';
import { isPath, safeRequire } from '../common/util';
import { isClass, isFunction } from '../util';
import * as util from 'util';
Expand All @@ -19,7 +19,7 @@ const debug = util.debuglog('midway:container:configuration');

export class ContainerConfiguration implements IContainerConfiguration {
container: IMidwayContainer & {
bindClass(exports, namespace: string)
bindClass(exports, namespace: string);
};
namespace: string;
packageName: string;
Expand All @@ -41,7 +41,10 @@ export class ContainerConfiguration implements IContainerConfiguration {
// for package
const subContainerConfiguration = this.container.createConfiguration();
if (typeof importPackage === 'string') {
const subPackageDir = this.resolvePackageBaseDir(importPackage, baseDir);
const subPackageDir = this.resolvePackageBaseDir(
importPackage,
baseDir
);
debug(
`\n---------- start load configuration from sub package "${importPackage}" ----------`
);
Expand All @@ -52,7 +55,7 @@ export class ContainerConfiguration implements IContainerConfiguration {
} else {
// component is object
debug(
`\n---------- start load configuration from submodule" ----------`
'\n---------- start load configuration from submodule" ----------'
);
subContainerConfiguration.loadComponentObject(importPackage);
debug(
Expand Down Expand Up @@ -177,7 +180,7 @@ export class ContainerConfiguration implements IContainerConfiguration {
}

loadComponentObject(componentObject) {
if(!componentObject || !componentObject['Configuration']) {
if (!componentObject || !componentObject['Configuration']) {
return;
}

Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/context/container.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import {
getObjectDefProps,
TAGGED_PROP,
getProviderId,
generateProvideId
generateProvideId,
} from '@midwayjs/decorator';
import { IContainer } from '../interface';
import { ObjectDefinition } from '../definitions/objectDefinition';
Expand Down
42 changes: 25 additions & 17 deletions packages/core/src/context/midwayContainer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,10 @@ import {
generateProvideId,
MAIN_MODULE_KEY,
CONFIG_KEY,
ALL
ALL,
} from '@midwayjs/decorator';
import { ContainerConfiguration } from './configuration';
import {
FUNCTION_INJECT_KEY,
} from '..';
import { FUNCTION_INJECT_KEY } from '..';
import {
IApplicationContext,
IConfigService,
Expand Down Expand Up @@ -226,7 +224,11 @@ export class MidwayContainer extends Container implements IMidwayContainer {
}
}

registerObject(identifier: ObjectIdentifier, target: any, registerByUser = true) {
registerObject(
identifier: ObjectIdentifier,
target: any,
registerByUser = true
) {
if (registerByUser) {
this.midwayIdentifiers.push(identifier);
}
Expand Down Expand Up @@ -382,7 +384,9 @@ export class MidwayContainer extends Container implements IMidwayContainer {
}

async stop(): Promise<void> {
const cycles: Array<{ target: any, namespace: string }> = listModule(CONFIGURATION_KEY);
const cycles: Array<{ target: any; namespace: string }> = listModule(
CONFIGURATION_KEY
);
this.debugLogger(
'load lifecycle length => %s when stop.',
cycles && cycles.length
Expand Down Expand Up @@ -441,12 +445,14 @@ export class MidwayContainer extends Container implements IMidwayContainer {

this.registerImportObjects(
containerConfiguration.getImportObjects(),
containerConfiguration.namespace,
containerConfiguration.namespace
);
}

private async loadAndReadyLifeCycles() {
const cycles: Array<{ target: any, namespace: string }> = listModule(CONFIGURATION_KEY);
const cycles: Array<{ target: any; namespace: string }> = listModule(
CONFIGURATION_KEY
);
this.debugLogger('load lifecycle length => %s.', cycles && cycles.length);
for (const cycle of cycles) {
const providerId = getProviderId(cycle.target);
Expand All @@ -459,16 +465,18 @@ export class MidwayContainer extends Container implements IMidwayContainer {
* 2、每次 getAsync 的时候,去掉 namespace,同时还要查找当前全局的变量,性能差
* 3、一般只会在 onReady 的地方执行 registerObject(否则没有全局的意义),这个取巧的办法就是 onReady 传入一个代理,其中绑定当前的 namespace
*/
await inst.onReady(new Proxy(this, {
get: function (target, prop, receiver) {
if (prop === 'getCurrentNamespace' && cycle.namespace) {
return () => {
return cycle.namespace;
await inst.onReady(
new Proxy(this, {
get: function (target, prop, receiver) {
if (prop === 'getCurrentNamespace' && cycle.namespace) {
return () => {
return cycle.namespace;
};
}
}
return Reflect.get(target, prop, receiver);
},
}));
return Reflect.get(target, prop, receiver);
},
})
);
}
}
}
Expand Down
5 changes: 1 addition & 4 deletions packages/core/src/context/resolverHandler.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,4 @@
import {
CLASS_KEY_CONSTRUCTOR,
getClassMetadata,
} from '@midwayjs/decorator';
import { CLASS_KEY_CONSTRUCTOR, getClassMetadata } from '@midwayjs/decorator';
import { ManagedResolverFactory } from './managedResolverFactory';
import { MidwayContainer } from './midwayContainer';
import * as util from 'util';
Expand Down
8 changes: 2 additions & 6 deletions packages/core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ export {
getProviderId,
getObjectDefinition,
classNamed,
generateProvideId
generateProvideId,
} from '@midwayjs/decorator';
export * from './interface';
export { ContainerLoader } from './loader';
Expand All @@ -39,11 +39,7 @@ export { MidwayRequestContainer } from './context/requestContainer';
export { BaseFramework } from './baseFramework';
export * from './context/providerWrapper';
export * from './common/constants';
export {
safelyGet,
safeRequire,
parsePrefix,
} from './common/util';
export { safelyGet, safeRequire, parsePrefix } from './common/util';
export * from './features';
export * from './util/webRouterParam';
export { plainToClass, classToPlain } from 'class-transformer';
17 changes: 13 additions & 4 deletions packages/core/src/util/staticConfig.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,24 @@
import { join } from 'path';
import { CONFIGURATION_KEY, getClassMetadata, InjectionConfigurationOptions } from '@midwayjs/decorator';
import {
CONFIGURATION_KEY,
getClassMetadata,
InjectionConfigurationOptions,
} from '@midwayjs/decorator';
import { IConfigService, safeRequire } from '..';
import { MidwayConfigService } from '../service/configService';
import { isClass, isFunction } from './index';

export class StaticConfigLoader {

baseDir: string;
configService: IConfigService;

constructor(baseDir: string, currentEnvironment: string) {
this.baseDir = baseDir;
this.configService = new MidwayConfigService({getCurrentEnv() {return currentEnvironment}});
this.configService = new MidwayConfigService({
getCurrentEnv() {
return currentEnvironment;
},
});
}

async getSerializeConfig(): Promise<string> {
Expand All @@ -21,7 +28,9 @@ export class StaticConfigLoader {
if (mainModule && mainModule['Configuration']) {
mainConfiguration = mainModule['Configuration'];
} else {
mainConfiguration = safeRequire(join(this.baseDir, 'src', 'configuration.ts'));
mainConfiguration = safeRequire(
join(this.baseDir, 'src', 'configuration.ts')
);
}

const modules = this.getConfigurationExport(mainConfiguration);
Expand Down
7 changes: 6 additions & 1 deletion packages/decorator/src/common/decoratorManager.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
import 'reflect-metadata';
import { ObjectDefinitionOptions, TagClsMetadata } from '../interface';
import { MAIN_MODULE_KEY, OBJ_DEF_CLS, PRIVATE_META_DATA_KEY, TAGGED_CLS } from './constant';
import {
MAIN_MODULE_KEY,
OBJ_DEF_CLS,
PRIVATE_META_DATA_KEY,
TAGGED_CLS,
} from './constant';
import { classNamed } from './utils';

const debug = require('util').debuglog('decorator:manager');
Expand Down
3 changes: 1 addition & 2 deletions packages/decorator/src/web/paramMapping.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,5 +83,4 @@ export const Files = (property?: GetFilesStreamOptions) =>
createParamMapping(RouteParamTypes.FILESSTREAM)(property);
export const RequestPath = () =>
createParamMapping(RouteParamTypes.REQUEST_PATH)();
export const RequestIP = () =>
createParamMapping(RouteParamTypes.REQUEST_IP)();
export const RequestIP = () => createParamMapping(RouteParamTypes.REQUEST_IP)();
6 changes: 5 additions & 1 deletion packages/mock/src/client/rabbitMQ.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import { Channel } from 'amqplib';
import { debuglog } from 'util';

const queues = {};
const exchanges = {};
const eventListeners = [];
const EventEmitter = require('events').EventEmitter;
const debug = debuglog('midway:mock');

const createQueue = () => {
let messages = [];
Expand Down Expand Up @@ -307,7 +309,9 @@ let amqp = null;
try {
amqp = require('amqplib');
amqp.connect = connect;
} catch (err) {}
} catch (err) {
debug('can not found amqplib lib and skip');
}

export const createRabbitMQProducer = async function (
queueName: string,
Expand Down
2 changes: 1 addition & 1 deletion packages/rabbitmq/src/framework.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ export class MidwayRabbitMQFramework extends BaseFramework<
}

// get providerId
let providerId = getProviderId(module);
const providerId = getProviderId(module);
// get listenerInfo
const data: RabbitMQListenerOptions[][] = listPropertyDataFromClass(
MS_CONSUMER_KEY,
Expand Down
2 changes: 1 addition & 1 deletion packages/socketio/src/framework.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ export class MidwaySocketIOFramework extends BaseFramework<
// create room
const controllerModules = listModule(WS_CONTROLLER_KEY);
for (const module of controllerModules) {
let providerId = getProviderId(module);
const providerId = getProviderId(module);
if (providerId) {
await this.addNamespace(module, providerId);
}
Expand Down
2 changes: 1 addition & 1 deletion packages/web-express/src/framework.ts
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@ export class MidwayExpressFramework extends BaseFramework<

// implement @controller
for (const module of controllerModules) {
let providerId = getProviderId(module);
const providerId = getProviderId(module);
if (providerId) {
if (this.controllerIds.indexOf(providerId) > -1) {
throw new Error(`controller identifier [${providerId}] is exists!`);
Expand Down
2 changes: 1 addition & 1 deletion packages/web-koa/src/framework.ts
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ export abstract class MidwayKoaBaseFramework<

// implement @controller
for (const module of controllerModules) {
let providerId = getProviderId(module);
const providerId = getProviderId(module);
if (providerId) {
if (this.controllerIds.indexOf(providerId) > -1) {
throw new Error(`controller identifier [${providerId}] is exists!`);
Expand Down
24 changes: 24 additions & 0 deletions packages/web/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@
const { Bootstrap } = require('@midwayjs/bootstrap');
const { Framework } = require('./dist/index');
const pathMatching = require('egg-path-matching');
const { safelyGet } = require('@midwayjs/core');

const { CONFIG_KEY, LOGGER_KEY, PLUGIN_KEY } = require('@midwayjs/decorator');

class AppBootHook {
constructor(app) {
Expand Down Expand Up @@ -31,6 +34,27 @@ class AppBootHook {
this.app.options['webFramework'] = this.framework;
}

// register plugin
this.app.applicationContext.registerDataHandler(
PLUGIN_KEY,
(key, target) => {
return this.app[key];
}
);

// register config
this.app.applicationContext.registerDataHandler(CONFIG_KEY, key => {
return key ? safelyGet(key, this.app.config) : this.app.config;
});

// register logger
this.app.applicationContext.registerDataHandler(LOGGER_KEY, key => {
if (this.app.getLogger) {
return this.app.getLogger(key);
}
return this.app.coreLogger;
});

// 等 midway 加载完成后,再去 use 中间件
for (const name of this.appMiddleware) {
if (this.app.getApplicationContext().registry.hasDefinition(name)) {
Expand Down
30 changes: 2 additions & 28 deletions packages/web/src/framework.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,13 @@ import {
IMidwayBootstrapOptions,
MidwayFrameworkType,
MidwayProcessTypeEnum,
safelyGet,
} from '@midwayjs/core';
import {
CONFIG_KEY,
ControllerOption,
LOGGER_KEY,
PLUGIN_KEY,
} from '@midwayjs/decorator';
import { ControllerOption } from '@midwayjs/decorator';
import { IMidwayWebConfigurationOptions } from './interface';
import { MidwayKoaBaseFramework } from '@midwayjs/koa';
import { EggRouter } from '@eggjs/router';
import { resolve } from 'path';
import { Application, Router, Context } from 'egg';
import { Application, Context, Router } from 'egg';

export class MidwayWebFramework extends MidwayKoaBaseFramework<
IMidwayWebConfigurationOptions,
Expand Down Expand Up @@ -86,26 +80,6 @@ export class MidwayWebFramework extends MidwayKoaBaseFramework<
}

this.defineApplicationProperties(this.app);
// register plugin
this.containerLoader.registerHook(
PLUGIN_KEY,
(key: string, target: any) => {
return this.app[key];
}
);

// register config
this.containerLoader.registerHook(CONFIG_KEY, (key: string) => {
return key ? safelyGet(key, this.app.config) : this.app.config;
});

// register logger
this.containerLoader.registerHook(LOGGER_KEY, (key: string) => {
if (this.app.getLogger) {
return this.app.getLogger(key);
}
return this.app.coreLogger;
});
}

protected async afterInitialize(
Expand Down
4 changes: 2 additions & 2 deletions packages/web/src/utils.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import { isTypeScriptEnvironment } from '@midwayjs/bootstrap';
import { basename, join } from 'path';

const isTypeScriptEnv = isTypeScriptEnvironment();

export const parseNormalDir = (baseDir: string, isTypescript = true) => {
if (isTypescript) {
if (/src$/.test(baseDir) || /dist$/.test(baseDir)) {
baseDir = basename(baseDir);
}

const isTypeScriptEnv = isTypeScriptEnvironment();

if (isTypeScriptEnv) {
return {
baseDir: join(baseDir, 'src'),
Expand Down
Loading

0 comments on commit cacb2fa

Please sign in to comment.