abelcastro.dev

Abel Castro 2025 - checkout the source code of this page on GitHub - Privacy Policy

Setting Up a REPL in a NestJS Project with Mikro-ORM: A Django Shell Equivalent

2024-10-21

NestJSMikro-ORMDjango

After spending considerable time working with the Python framework Django, I've recently ventured into the Node.js world with NestJS. One of the features I deeply missed from Django was the Django Shell. It was an incredibly useful tool that allowed me to interact with my application in a Python shell, test out code snippets, and manipulate data directly using the Django ORM.

In the NestJS ecosystem, I was searching for a similar interactive environment and discovered that what I was looking for is called a REPL (Read-Evaluate-Print Loop). A REPL provides an interactive shell where you can execute code in real-time within the context of your application.

In this post, I'll show you how to set up a REPL in a NestJS project that uses Mikro-ORM, drawing from my experience adapting code from this GitHub repository.

Why Use a REPL?

A REPL is invaluable for:

  • Testing code snippets: Quickly try out code without writing tests or modifying your application files.
  • Database manipulation: Interact with your database through your ORM to query or modify data.
  • Debugging: Experiment with different functions and methods to troubleshoot issues.

Setting Up the REPL in NestJS with Mikro-ORM

Here's how you can set up a REPL in your NestJS project:

Step 1: Create a repl.ts File

In the root of your project, create a file named repl.ts with the following content:

import 'tsconfig-paths/register';

import { repl } from '@nestjs/core';
import { AppModule } from './app.module';
import { MikroORM } from '@mikro-orm/core';
import { commonMikroOrmConfig } from './mikro-orm.config';
import { Post } from './posts/post.entities';

async function bootstrap() {
  const replServer = await repl(AppModule);
  const { context } = replServer;

  const orm = await MikroORM.init({
    ...commonMikroOrmConfig,
    allowGlobalContext: true,
    entitiesTs: ['./**/*.entities.ts'],
    entities: ['./dist/**/*.entities.js'],
    discovery: {
      warnWhenNoEntities: false,
    },
  });

  // Add your entities and ORM to the REPL context for easy access
  context.Post = Post;
  context.orm = orm;
  context.em = orm.em;
}
bootstrap();

Explanation:

  • Import Statements: We import necessary modules, including repl from @nestjs/core and MikroORM from @mikro-orm/core.
  • Bootstrap Function: We initialize the REPL server and MikroORM within an asynchronous bootstrap function.
  • Context Enhancement: We add the ORM instance, the entity manager (em), and any entities (like Post) to the REPL context for easy access.

Step 2: Start the REPL

Run the following command in your terminal:

npm run start -- --entryFile repl

This tells NestJS to use repl.ts as the entry file instead of the default main.ts.

Using the REPL

Once the REPL starts, you'll see a prompt like this:

[info] MikroORM successfully connected to database blog_db on postgresql://blog_user:*****@127.0.0.1:5432

>

Now you can interact with your application. Here's an example of querying all Post entities:

> const posts = await em.find(Post, {});
[query] select "p0".* from "post" as "p0" [took 5 ms, 2 results]
> posts
[
  {
    id: 1,
    title: 'First Post',
    content: 'This is the first post.',
    createdAt: 2023-10-21T12:34:56.789Z
  },
  {
    id: 2,
    title: 'Second Post',
    content: 'This is the second post.',
    createdAt: 2023-10-22T08:15:30.123Z
  }
]

Tips for Using the REPL:

  • Access Entities: Use Post, User, or any other entities you've added to the context.
  • Entity Manager: em is available for database operations.
  • Autocomplete: The REPL supports autocomplete for faster coding.

Important Considerations

  • Production Use: While a REPL is powerful, using it in a production environment can be risky. Be cautious when manipulating data directly.
  • Security: Ensure that access to the REPL in production environments is secure and restricted.

Conclusion

Setting up a REPL in your NestJS project with Mikro-ORM bridges the gap between Django's interactive shell and the Node.js world. It enhances productivity by allowing real-time interaction with your application's context and database.

Feel free to explore and extend this setup by adding more entities or custom services to the REPL context. Happy coding!


References:

  • NestJS Documentation - REPL
  • Mikro-ORM Documentation