Monorepo

Scaffolding a Nest.js App with REST, GraphQL, Cron, and Message Brokers

Explanation of the idea

In medium and large-scale projects, we often need more than just REST and GraphQL. Frequently, there is a need to run commands on a schedule. Additionally, service applications, such as queue consumers, play a significant role in the architecture.

This gives us a total of four types of applications that may be required:

  1. REST Application: A standard API application that runs a web server, typically listening on port 80.

  2. GraphQL Application: A dedicated server for handling GraphQL queries, implemented using any JavaScript GraphQL library.

  3. Console Application: Used for executing scheduled tasks, such as with cron jobs or systemd-timers.

  4. Service Applications: Applications dedicated to consuming messages from a queue system. While all types of applications can act as message producers, service applications specifically operate as consumers.

The number and types of applications you need will depend on the scale and complexity of your project.

Visually, this can be represented as follows:

Drawing
General scheme of interaction

Preparation

Make sure you have the Nest CLI or just install it.

$ npm i -g @nestjs/cli
$ nest --help
$ nest new --help

Scaffolding new project

Command nest new name - Scaffolds a new standard mode application with all boilerplate files needed to run.

Command nest generate sub-app name Convert this to a monorepo mode.

nest new rest --directory project.com
cd project.com
nest generate sub-app cli
nest generate sub-app gql
nest generate sub-app srv
sed -i '' 's/rest/project.com/' package.json

So great, now we have 4 rest apps 😄. Let's check the result.

$ tree -L 3
.
├── ...
├── apps
│   ├── cli
│   │   ├── src
│   │   ├── test
│   │   └── tsconfig.app.json
│   ├── gql
│   │   ├── src
│   │   ├── test
│   │   └── tsconfig.app.json
│   ├── rest
│   │   ├── src
│   │   ├── test
│   │   └── tsconfig.app.json
│   └── srv
│       ├── src
│       ├── test
│       └── tsconfig.app.json
└── ...

Configure REST App

Configure GraphQL App

yarn add @nestjs/graphql @nestjs/apollo @apollo/server graphql

Configure CLI App

yarn add nest-commander

Configure Service App

https://docs.nestjs.com/microservices/kafka

yarn add @nestjs/config @nestjs/microservices kafkajs

Last updated