Skip to content

Commit

Permalink
feat(core): add connect: boolean param to MikroORM.init()
Browse files Browse the repository at this point in the history
  • Loading branch information
B4nan committed Aug 9, 2020
1 parent 2302f2b commit 43a9ce9
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 6 deletions.
11 changes: 7 additions & 4 deletions packages/core/src/MikroORM.ts
Expand Up @@ -22,7 +22,7 @@ export class MikroORM<D extends IDatabaseDriver = IDatabaseDriver> {
* Initialize the ORM, load entity metadata, create EntityManager and connect to the database.
* If you omit the `options` parameter, your CLI config will be used.
*/
static async init<D extends IDatabaseDriver = IDatabaseDriver>(options?: Options<D> | Configuration<D>): Promise<MikroORM<D>> {
static async init<D extends IDatabaseDriver = IDatabaseDriver>(options?: Options<D> | Configuration<D>, connect = true): Promise<MikroORM<D>> {
if (!options) {
options = await ConfigurationLoader.getConfiguration<D>();
}
Expand All @@ -34,10 +34,13 @@ export class MikroORM<D extends IDatabaseDriver = IDatabaseDriver> {
orm.em = orm.driver.createEntityManager<D>();
orm.metadata.decorate(orm.em);
orm.driver.setMetadata(orm.metadata);
await orm.connect();

if (orm.config.get('ensureIndexes')) {
await orm.driver.ensureIndexes();
if (connect) {
await orm.connect();

if (orm.config.get('ensureIndexes')) {
await orm.driver.ensureIndexes();
}
}

return orm;
Expand Down
3 changes: 2 additions & 1 deletion packages/mongodb/src/MongoConnection.ts
Expand Up @@ -20,7 +20,8 @@ export class MongoConnection extends Connection {
}

async isConnected(): Promise<boolean> {
return this.client.isConnected();
const ret = this.client?.isConnected();
return !!ret;
}

getCollection(name: EntityName<AnyEntity>): Collection {
Expand Down
5 changes: 4 additions & 1 deletion tests/MikroORM.test.ts
Expand Up @@ -91,11 +91,14 @@ describe('MikroORM', () => {
const pkg = { 'mikro-orm': { useTsNode: true } } as any;
jest.mock('../package.json', () => pkg, { virtual: true });

const orm = await MikroORM.init();
const orm = await MikroORM.init(undefined, false);

expect(orm).toBeInstanceOf(MikroORM);
expect(orm.em).toBeInstanceOf(EntityManager);
expect(Object.keys(orm.getMetadata().getAll()).sort()).toEqual(['Test']);
expect(await orm.isConnected()).toBe(false);

await orm.connect();
expect(await orm.isConnected()).toBe(true);

await orm.close();
Expand Down

0 comments on commit 43a9ce9

Please sign in to comment.