Skip to content

Commit

Permalink
fix: fix export service method (#477)
Browse files Browse the repository at this point in the history
* fix: fix export service method

* fix: fix absolute config path

* fix: undefined handler

Co-authored-by: lellansin <lellansin@gmail.com>
  • Loading branch information
czy88840616 and Lellansin authored Apr 21, 2020
1 parent fdf2814 commit 586b0be
Show file tree
Hide file tree
Showing 4 changed files with 134 additions and 40 deletions.
77 changes: 60 additions & 17 deletions packages/midway-core/src/context/configuration.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,19 @@
import { CONFIGURATION_KEY, InjectionConfigurationOptions, getClassMetadata, LIFECYCLE_IDENTIFIER_PREFIX, classNamed, saveModule, saveProviderId } from '@midwayjs/decorator';
import {
CONFIGURATION_KEY,
InjectionConfigurationOptions,
getClassMetadata,
LIFECYCLE_IDENTIFIER_PREFIX,
classNamed,
saveModule,
saveProviderId,
} from '@midwayjs/decorator';
import * as is from 'is-type-of';
import { dirname, isAbsolute, join } from 'path';
import { IContainerConfiguration, IMidwayContainer, MAIN_MODULE_KEY } from '../interface';
import {
IContainerConfiguration,
IMidwayContainer,
MAIN_MODULE_KEY,
} from '../interface';
import { isPath, safeRequire, generateProvideId } from '../common/util';

const debug = require('debug')('midway:container:configuration');
Expand Down Expand Up @@ -44,9 +56,15 @@ export class ContainerConfiguration implements IContainerConfiguration {
addImportConfigs(importConfigs: string[], baseDir: string) {
debug('import configs %j baseDir => %s.', importConfigs, baseDir);
if (importConfigs && importConfigs.length) {
this.container.getConfigService().add(importConfigs.map(importConfigPath => {
return join(baseDir || this.container.baseDir, importConfigPath);
}));
this.container.getConfigService().add(
importConfigs.map(importConfigPath => {
if (isAbsolute(importConfigPath)) {
return importConfigPath;
} else {
return join(baseDir || this.container.baseDir, importConfigPath);
}
})
);
}
}

Expand All @@ -60,8 +78,14 @@ export class ContainerConfiguration implements IContainerConfiguration {
}
try {
return dirname(require.resolve(packageName));
} catch (e) { /* ignore */ }
return join(baseDir || this.container.baseDir, '../node_modules', packageName);
} catch (e) {
/* ignore */
}
return join(
baseDir || this.container.baseDir,
'../node_modules',
packageName
);
}

load(packageName: string) {
Expand All @@ -73,15 +97,19 @@ export class ContainerConfiguration implements IContainerConfiguration {
isSubDir = true;
pkg = safeRequire(join(packageBaseDir, '../', 'package.json'));
}
debug('safeRequire package.json name-version => %s, from %s.',
pkg ? `${pkg.name}-${pkg.version}` : undefined, packageBaseDir);
debug(
'safeRequire package.json name-version => %s, from %s.',
pkg ? `${pkg.name}-${pkg.version}` : undefined,
packageBaseDir
);

let configuration;
let cfgFile;
let loadDir;
if (pkg) {
if (this.namespace !== MAIN_MODULE_KEY) {
this.namespace = pkg.midwayNamespace !== undefined ? pkg.midwayNamespace : pkg.name;
this.namespace =
pkg.midwayNamespace !== undefined ? pkg.midwayNamespace : pkg.name;
}
if (pkg.main && !isSubDir) {
packageBaseDir = dirname(join(packageBaseDir, pkg.main));
Expand All @@ -101,8 +129,12 @@ export class ContainerConfiguration implements IContainerConfiguration {
this.addLoadDir(loadDir);
debug('add loadDir => %s namespace => %s.', loadDir, this.namespace);
}
debug('packageName => %s namespace => %s configuration file => %s.',
packageName, this.namespace, configuration ? true : false);
debug(
'packageName => %s namespace => %s configuration file => %s.',
packageName,
this.namespace,
configuration ? true : false
);
this.loadConfiguration(configuration, packageBaseDir, cfgFile);
}

Expand All @@ -117,11 +149,17 @@ export class ContainerConfiguration implements IContainerConfiguration {
);
debug('configuration export %j.', configurationOptions);
if (configurationOptions) {
if (this.namespace !== MAIN_MODULE_KEY && configurationOptions.namespace !== undefined) {
if (
this.namespace !== MAIN_MODULE_KEY &&
configurationOptions.namespace !== undefined
) {
this.namespace = configurationOptions.namespace;
}

if (this.container.containsConfiguration(this.namespace) && this.namespace !== '') {
if (
this.container.containsConfiguration(this.namespace) &&
this.namespace !== ''
) {
debug(`configuration ${this.namespace} exist than ignore.`);
return;
} else {
Expand All @@ -135,8 +173,10 @@ export class ContainerConfiguration implements IContainerConfiguration {
}
}
} else {

if (this.container.containsConfiguration(this.namespace) && this.namespace !== '') {
if (
this.container.containsConfiguration(this.namespace) &&
this.namespace !== ''
) {
debug(`configuration ${this.namespace} exist than ignore.`);
return;
} else {
Expand All @@ -153,7 +193,10 @@ export class ContainerConfiguration implements IContainerConfiguration {
const clzzName = `${LIFECYCLE_IDENTIFIER_PREFIX}${classNamed(clzz.name)}`;
const id = generateProvideId(clzzName, this.namespace);
saveProviderId(id, clzz, true);
this.container.bind(id, clzz, { namespace: this.namespace, srcPath: filePath });
this.container.bind(id, clzz, {
namespace: this.namespace,
srcPath: filePath,
});
saveModule(CONFIGURATION_KEY, clzz);
}

Expand Down
39 changes: 31 additions & 8 deletions packages/midway-core/src/context/requestContainer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,7 @@ import { parsePrefix } from '../common/util';
import { PIPELINE_IDENTIFIER } from '@midwayjs/decorator';

export class MidwayRequestContainer extends MidwayContainer {

applicationContext: MidwayContainer;
private applicationContext: MidwayContainer;

constructor(ctx, applicationContext) {
super();
Expand All @@ -24,11 +23,19 @@ export class MidwayRequestContainer extends MidwayContainer {
if (this.registry.hasObject(identifier)) {
return this.registry.getObject(identifier);
}
const definition = this.applicationContext.registry.getDefinition(identifier);
const definition = this.applicationContext.registry.getDefinition(
identifier
);
if (definition) {
if (definition.isRequestScope() || definition.id === PIPELINE_IDENTIFIER) {
if (
definition.isRequestScope() ||
definition.id === PIPELINE_IDENTIFIER
) {
// create object from applicationContext definition for requestScope
return this.getManagedResolverFactory().create({ definition, args });
return this.getManagedResolverFactory().create({
definition,
args,
});
}
}

Expand All @@ -48,11 +55,19 @@ export class MidwayRequestContainer extends MidwayContainer {
return this.registry.getObject(identifier);
}

const definition = this.applicationContext.registry.getDefinition(identifier);
const definition = this.applicationContext.registry.getDefinition(
identifier
);
if (definition) {
if (definition.isRequestScope() || definition.id === PIPELINE_IDENTIFIER) {
if (
definition.isRequestScope() ||
definition.id === PIPELINE_IDENTIFIER
) {
// create object from applicationContext definition for requestScope
return this.getManagedResolverFactory().createAsync({ definition, args });
return this.getManagedResolverFactory().createAsync({
definition,
args,
});
}
}

Expand All @@ -69,4 +84,12 @@ export class MidwayRequestContainer extends MidwayContainer {
this.readied = true;
// ignore other things
}

get configService() {
return this.applicationContext.configService;
}

get environmentService() {
return this.applicationContext.environmentService;
}
}
56 changes: 42 additions & 14 deletions packages/midway-core/test/context/requestContainer.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,13 @@
import { expect } from 'chai';
import { MidwayContainer as Container, REQUEST_OBJ_CTX_KEY, MidwayRequestContainer as RequestContainer, ScopeEnum } from '../../src';
import {
MidwayContainer as Container,
REQUEST_OBJ_CTX_KEY,
MidwayRequestContainer as RequestContainer,
ScopeEnum,
} from '../../src';
import { Inject, Provide, Scope } from '@midwayjs/decorator';
import { CircularOne,
import {
CircularOne,
CircularTwo,
CircularThree,
TestOne,
Expand All @@ -18,19 +24,16 @@ import { CircularOne,
TenService,
ScaleManager,
AutoScaleService,
CCController
CCController,
} from '../fixtures/circular_dependency';

class Tracer {

get parentId() {
return '321';
}

}

class DataCollector {

id = Math.random();

getData() {
Expand All @@ -41,7 +44,6 @@ class DataCollector {
@Provide('tracer')
@Scope(ScopeEnum.Request)
class ChildTracer extends Tracer {

id = Math.random();

@Inject('dataCollector')
Expand All @@ -58,20 +60,22 @@ class ChildTracer extends Tracer {
getData() {
return this.collector.getData();
}

}

describe('/test/context/requestContainer.test.ts', () => {

it('should create request container more then once and get same value from parent', async () => {
const appCtx = new Container();
appCtx.bind(DataCollector);
appCtx.bind(ChildTracer);

const reqCtx1 = new RequestContainer({}, appCtx);
const reqCtx2 = new RequestContainer({}, appCtx);
expect(reqCtx1.get<Tracer>(ChildTracer).parentId).to.equal(reqCtx2.get<Tracer>(ChildTracer).parentId);
expect((await reqCtx1.getAsync(ChildTracer)).parentId).to.equal((await reqCtx2.getAsync(ChildTracer)).parentId);
expect(reqCtx1.get<Tracer>(ChildTracer).parentId).to.equal(
reqCtx2.get<Tracer>(ChildTracer).parentId
);
expect((await reqCtx1.getAsync(ChildTracer)).parentId).to.equal(
(await reqCtx2.getAsync(ChildTracer)).parentId
);
});

it('should get same object in same request context', async () => {
Expand Down Expand Up @@ -145,8 +149,8 @@ describe('/test/context/requestContainer.test.ts', () => {
const tracer1 = await reqCtx1.getAsync('tracer');
const tracer2 = await reqCtx2.getAsync('tracer');

expect(tracer1[ REQUEST_OBJ_CTX_KEY ]).to.equal(ctx1);
expect(tracer2[ REQUEST_OBJ_CTX_KEY ]).to.equal(ctx2);
expect(tracer1[REQUEST_OBJ_CTX_KEY]).to.equal(ctx1);
expect(tracer2[REQUEST_OBJ_CTX_KEY]).to.equal(ctx2);
});

it('circular should be ok in requestContainer', async () => {
Expand All @@ -167,7 +171,10 @@ describe('/test/context/requestContainer.test.ts', () => {
const circularTwo: CircularTwo = await container.getAsync(CircularTwo);
expect(circularTwo.test2).eq('this is two');
expect((circularTwo.circularOne as CircularOne).test1).eq('this is one');
expect(((circularTwo.circularOne as CircularOne).circularTwo as CircularTwo).test2).eq('this is two');
expect(
((circularTwo.circularOne as CircularOne).circularTwo as CircularTwo)
.test2
).eq('this is two');

const one = await container.getAsync<TestOne1>(TestOne1);
expect(one).not.null;
Expand Down Expand Up @@ -198,4 +205,25 @@ describe('/test/context/requestContainer.test.ts', () => {
expect(one.autoScaleService.ts).eq('ascale');
expect(one.autoScaleService.scaleManager.ts).eq('scale');
});

it('test getService in requestContainer', () => {
const appCtx = new Container();
// 合并 egg config
const configService = appCtx.getConfigService();
configService.addObject({
name: 'zhangting',
});
appCtx.bind(GatewayManager);
appCtx.ready();
const ctx1 = { a: 1 };
const container = new RequestContainer(ctx1, appCtx);
const defaultConfig = container.getConfigService().getConfiguration();
expect(defaultConfig.name).to.equal('zhangting');
const defaultEnv = container
.getEnvironmentService()
.getCurrentEnvironment();
const currentEnv = container.getCurrentEnv();
expect(defaultEnv).to.equal('test');
expect(currentEnv).to.equal(defaultEnv);
});
});
2 changes: 1 addition & 1 deletion packages/midway-decorator/src/faas/fun.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ export function Func(
) {
if (typeof funHandler !== 'string' && functionOptions === undefined) {
functionOptions = funHandler;
funHandler = functionOptions.funHandler;
funHandler = functionOptions.funHandler || '';
}
return (...args) => {
const [target, key, descriptor] = args as any;
Expand Down

0 comments on commit 586b0be

Please sign in to comment.