How to get dependency tree/graph in NestJS?

Viewed 3453

Nestjs provides out of the box DI container very conveniently but as project gets more complex it is easy to lose the full picture of all dependencies and their order.

Question: Is there a way to get a list of all dependencies (modules, providers, controllers...) possibly in a way that can be put into a tree/graph? I'm sure Nestjs tracks this information internally and I'm wondering what would be the best way to access it.

(I found [nestjs-dependency-graph] but it scans the modules manually for metadata, doesn't find all dependencies and tends to go into infinite loop)

2 Answers

It's not a complete solution yet, but there is the package I've been working on nestjs-spelunker. You can read through the readme and see if it does what you're looking for

I've tried nestjs-splunker like mentioned in @Jay's comment and it's really solid.

You just need to generate the graph text and paste it in the mermaid-live-editor

import { NestFactory } from '@nestjs/core';
import { SpelunkerModule } from 'nestjs-spelunker';

async function bootstrap() {
  const app = await NestFactory.create<NestFastifyApplication>(AppModule);

  // 1. Generate the tree as text
  const tree = SpelunkerModule.explore(app);
  const root = SpelunkerModule.graph(tree);
  const edges = SpelunkerModule.findGraphEdges(root);
  const mermaidEdges = edges
    .filter( // I'm just filtering some extra Modules out
      ({ from, to }) =>
        !(
          from.module.name === 'ConfigHostModule' ||
          from.module.name === 'LoggerModule' ||
          to.module.name === 'ConfigHostModule' ||
          to.module.name === 'LoggerModule'
        ),
    )
    .map(({ from, to }) => `${from.module.name}-->${to.module.name}`);
  console.log(`graph TD\n\t${mermaidEdges.join('\n\t')}`);
  
  // 2. Copy and paste the log content in "https://mermaid.live/"
}

bootstrap();
Related