DEV Community

Cover image for 🚄Node On Rails: Finding the backend server: exploring NestJS Part 2!
Michael "lampe" Lazarski
Michael "lampe" Lazarski

Posted on

🚄Node On Rails: Finding the backend server: exploring NestJS Part 2!

In the first part, we installed nestjs and run our first app!
If you have missed it check it out here Click

We now need to take a look at the folder structure that was created for us in the last part.

Alt Text

The first look can be a little bit much, but we have a lot of configuration files.

We see a lot of configuration files like: tsconfig.json, .eslintrc.js.

For us, the folder we want to take a look at is the src folder.

In the folder we can find the following files:

main.ts

That is the entry point for our app. This code gets executed when we run the npm script start or start:dev. The file should look like that:

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  await app.listen(3000);
}
bootstrap();

We are importing two things. The NestFactory that will create a new App and the
AppModule, which is our main module. What a module is in nestjs will be discussed later. For now, you can think that it helps us to organize our app.

app.controller.ts

This is our app controller. Let's first discuss what a controller is.

A controller will receive a request. For example, if you enter http://localhost:3000/users you will have a controller that will listen to the users route. Depending on the HTTP request method like GET or POST.

Let us look at the code

import { Controller, Get } from '@nestjs/common';
import { AppService } from './app.service';

@Controller()
export class AppController {
  constructor(private readonly appService: AppService) {}

  @Get()
  getHello(): string {
    return this.appService.getHello();
  }
}

So you needed to decorate the class with the @Controller() decorator. This tells nestjs that the following class is a Controller. You don't need to name it somethingController but it is good practice to do so. The next new important line is the @Get() decorate with no parameters! This means that this controller will be called when someone makes a GET request on the root path aka /. This is exactly what the browsers do when you enter localhost:3000. The getHello() function then calls the appService's getHello() function. We will discuss next what a service is.

app.service.ts

A service can be a piece of code that retrieves and/or stores data. It can call other services or calculate something. Let check our app.service.ts file.

import { Injectable } from '@nestjs/common';

@Injectable()
export class AppService {
  getHello(): string {
    return 'Hello World!';
  }
}

The @Injectable() decorator tells nextjs that this class can be used in other classes like controllers. Besides that, we see nothing special. We are just implementing the getHello() function that will return 'Hello 'World!'.

app.module.ts

Modules are the glue that puts everything together. Every nestjs application must have one Root Module.

import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';

@Module({
  imports: [],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

As you can see, we are just putting everything together here. One thing we need to talk about is the providers key in the module object. A provider can be a service as we can see in our example, but it can also be a repository, a factory, a helper and more.

Let's add a /users route.

/
So to code a little bit for this post, we add an /users route. Where we will return a static array with user names.

Users service

First, create a users.service.ts file in the source folder.

With the following code:

import { Injectable } from '@nestjs/common';

@Injectable()
export class UsersService {
  getUsers(): string[] {
    return ['michael', 'john'];
  }
}

We are returning an array with Michael and John. We also need to remember to tell TypeScript that we are now sending back an array of strings. So we need to change the return type to string[]. That's it/

Users Controller

import { Controller, Get } from '@nestjs/common';
import { UsersService } from './users.service';

@Controller()
export class UsersController {
  constructor(private readonly usersService: UsersService) {}

  @Get('users')
  getHello(): string[] {
    return this.usersService.getUsers();
  }
}

The most significant change here is that the @get() decorator now takes a string with the value users. This means that this controller is listening to the /users route.

Adding it to the App module.

Now we need to add it to the app.module.ts file.

import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { UsersController } from './users.controller';
import { UsersService } from './users.service';

@Module({
  imports: [],
  controllers: [AppController, UsersController],
  providers: [AppService, UsersService],
})
export class AppModule {}

Now save all the files and open your browser and go to the following URL http://localhost:3000/users.

You should see the following:
Alt Text

I hope you liked that post! If you want a follow-up, please comment, like and share. So I can know that you are interested in content like that!

👋Say Hello! Instagram | Twitter | LinkedIn | Medium | Twitch | YouTube

Top comments (2)

Collapse
 
squigglybob profile image
squigglybob

Thanks for the intro to nest. It looks nice. I haven't yet looked into alternative frameworks to express. Would you say Nest is one of the better ones?

Collapse
 
lampewebdev profile image
Michael "lampe" Lazarski

Actually nestjs builds on top of expressjs or fastify.

I would say that right now nestjs is the one I like the best.