Skip to content

[Documentation Request] Using MikroOrm within a dynamic NestJS module #92

@conspireagency

Description

@conspireagency

In the interest of code reuse I'd like to create a NestJS module that I can put on NPM and import into future projects. Within the module I'd like to have things like entity definitions, as well as services that interact with the database.

While I use NestJS + MikroOrm quite a bit, definitely sure part of this is due to a lack of lower level understanding here and there... but regardless would be cool to get more information on how to reuse entities and business logic that interacts with the database via MikroOrm!

So for examples sake we have:
-A newly scaffolded NestJS project
-The custom module that we'd like to reuse as a dependency hosted on NPM like this one https://github.com/conspireagency/nestm-shopify that's a dependency of the newly scaffolded project.

So if you were to look into the project's AppModule, it might look something like this:
`
import {MikroOrmModule } from '@mikro-orm/nestjs';
import { ShopifyModule } from '@conspireagency/nestm-shopify';

@module({
imports: [
MikroOrmModule.forRoot(),
ShopifyModule
],
controllers: [],
providers: [AppService],
})
export class AppModule {}`

In attempting to do this, I ran into a couple roadblocks so far:

  1. How to have the MikroOrm instance in the main project properly work with entities imported from the Custom Module

It looks like by importing the entities from the node module in the mikro-orm.config.ts that it sees the two entities (Product, Variant), but in trying to do something common like create a new migration after adding these entities it fails to detect that changes are required (assuming it is missing the entities).

Screen Shot 2022-12-01 at 12 35 27 AM
Screen Shot 2022-12-01 at 12 48 00 AM
Screen Shot 2022-12-01 at 12 39 04 AM

  1. How to share / inject the MikroOrm instance from the main project into the Custom Module so the services have access to em/orm instance?

I tried importing + injecting it like so in the main project to no avail:

AppModule.ts
MikroOrmModule.forRoot(), ShopifyModule.registerAsync({ imports: [MikroOrmModule], inject: [MikroOrmModule], })

If I change it back to below

AppModule.ts
MikroOrmModule.forRoot(), ShopifyModule

and then in the npm imported module initialize MikroOrm again the errors go away (assuming no version mismatches of the mikro orm packages in the main project and imported module), but guessing this doesn't actually work since both the main app and custom module have separate instances of MikroOrm.

Screen Shot 2022-12-01 at 12 42 07 AM

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions