Notes about Nest.js
- it surrounds your route handler body with try..catch blocks
- it makes every route handler async
- it creates a global express router
- it creates a separated router for each controller
- it binds error-handling middleware
- it binds body-parser middleware (both json and extended urlencoded)
- Keep all files as close to their domain (i.e. module folder) as possible
- Follow this template when in doubt about anything
Schnowa | Jawab |
---|---|
TypeORM models | modelName.entity.ts |
nest generate module <name>
nest generate controller <name>
nest generate service <name>
- Declaration controls routing
// users.controller.ts
import { Controller, Get } from '@nestjs/common';
@Controller('users')
export class UsersController {
@Get()
async getBooks() { return [{book1}, {book2}] }
@Get(':bookID')
async getBook(@Param('bookID') bookID) {}
@Post()
async addBook(@Body() createBookDTO: CreateBookDTO) {}
@Delete()
async deleteBook(@Query() query){ ...query.bookID... }
}
- Just needs a
@Injectable()
decorator at top
// users.service.ts
import { Injectable } from '@nestjs/common';
import { User } from './interfaces/user.interface';
@Injectable()
export class UsersService {
private readonly users: User[] = [];
create(user: User) {
this.users.push(user); }
findAll(): User[] {
return this.users;
}
}
... are TS files decorated with
@Module
decorator
- Every Nest.js application has a root module
- Plus normally submodules
constructor(private readonly usersService: UsersService){}
...
}
- TypeORM module thinks options provided are for a mongodb database when it is actually for postgres. Mindfuck is to write ...
'postgres' as 'postgres'
. Check this answer.
Resources: