Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add helper to get EggObject from class #148

Merged
merged 3 commits into from
Aug 28, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
4 changes: 4 additions & 0 deletions core/runtime/test/EggObject.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,10 @@ describe('test/EggObject.test.ts', () => {
'preDestroy',
'destroy',
]);
// get obj from class
const barObj2 = await EggContainerFactory.getOrCreateEggObjectFromClazz(barProto.clazz, barProto.name);
assert.equal(barObj2, barObj);
assert.equal(barObj2.obj, barObj.obj);
});
});
});
Expand Down