Skip to content

Commit

Permalink
feat: add helper to get EggObject from class (#148)
Browse files Browse the repository at this point in the history
  • Loading branch information
fengmk2 authored Aug 28, 2023
1 parent f049412 commit 77eaf38
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
15 changes: 14 additions & 1 deletion core/runtime/src/factory/EggContainerFactory.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { EggPrototype } from '@eggjs/tegg-metadata';
import { EggContainer } from '../model/EggContainer';
import { LifecycleContext } from '@eggjs/tegg-lifecycle';
import { EggObjectName, ObjectInitTypeLike } from '@eggjs/core-decorator';
import { EggObjectName, ObjectInitTypeLike, PrototypeUtil, EggProtoImplClass } from '@eggjs/core-decorator';
import { EggObject } from '../model/EggObject';
import { ContextHandler } from '../model/ContextHandler';
import { ContextInitiator } from '../impl/ContextInitiator';
Expand Down Expand Up @@ -40,6 +40,19 @@ export class EggContainerFactory {
return obj;
}

/**
* get or create egg object from the Class
* If get singleton egg object in context,
* will create context egg object for it.
*/
static async getOrCreateEggObjectFromClazz(clazz: EggProtoImplClass, name?: EggObjectName): Promise<EggObject> {
const proto = PrototypeUtil.getClazzProto(clazz) as EggPrototype;
if (!proto) {
throw new Error(`can not get proto for clazz ${clazz.name}`);
}
return await this.getOrCreateEggObject(proto, name);
}

static getEggObject(proto: EggPrototype, name?: EggObjectName): EggObject {
const container = this.getContainer(proto);
name = name || proto.name;
Expand Down
5 changes: 5 additions & 0 deletions core/runtime/test/EggObject.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,11 @@ describe('test/EggObject.test.ts', () => {
const barProto = EggPrototypeFactory.instance.getPrototype('bar');
const barObj = await EggContainerFactory.getOrCreateEggObject(barProto, barProto.name);
const bar = barObj.obj as Bar;
// get obj from class
const barObj2 = await EggContainerFactory.getOrCreateEggObjectFromClazz((barProto as any).clazz, barProto.name);
assert.equal(barObj2, barObj);
assert.equal(barObj2.obj, barObj.obj);

await TestUtil.destroyLoadUnitInstance(instance);
const called = bar.getLifecycleCalled();
assert.deepStrictEqual(called, [
Expand Down

0 comments on commit 77eaf38

Please sign in to comment.