nest.js + TypeORM + PostgreSQL
Tags: webdev, node, typescript, postgres
Published: 2021-06-08 04:30:53

### __Agenda :__
Building a rest api using Nest.JS .

### __Backend Architecture :__
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/ttobvwwzubdvz8kx8xdh.png)

### __Technologies used:__
1. __Node.js__    --- __Platform__ .
2. __NestJS__     --- __server__ .
3. __TypeORM__    --- __orm__ .
4. __PostgreSQL__ --- __database__ .

### __What is Node.js :__
![Node js](https://dev-to-uploads.s3.amazonaws.com/i/xqmcjh8b48rgdbnottw3.jpg)
NodeJS is a Javascript runtime(contains everything to run javascript) for building server side applications .

### __What is NestJs :__
![Nest](https://images.ctfassets.net/1es3ne0caaid/3XE9gJHMZakYUy0gKAsQ2M/986b5ddd64ea0ff1a344cde15b442a40/nest-logo.png)
Nest is a framework for building efficient and scalable NodeJs server side applications .

### __What is TypeORM :__
TypeORM is an object relational mapper which task is to basically generates objects using object oriented programming which maps to the database virtually .

### __What is PostgreSQL :__  
__PostgreSQL__ is an object relational database management system for building scalable and high availability applications .

* Install @nestjs/cli package .and create a new project
```
$ npm i -g @nestjs/cli
$ nest new project-name 
```  
### __In a common nestJS project :__
* main.ts contains the __bootstraping__ code .
* .spec file contains the testing files .
* nestjs usages module to organize the application structure .
* controller contains the routing rules for the application .
* service contains the business logic for the application .  
```$ npm run start ```
```
curl localhost:3000  
```

### __Set up Database :__
```SQL 
$sudo -U postgres
$psql
$create database conduit
$create user conduit with encrypted password conduit
$grant all privileges on database conduit to conduit
```
* File structure :
```
src
|- app.controller.ts
|- app.controller.spec.ts
|- app.module.ts
|- app.service.ts
|- main.ts
```

### __Create a `connection` to the database__ . 
```$ touch app.dbconfig.ts``` 

```typescript
import {TypeOrmModuleOptions} from "typeorm";

export function createTypeOrmProdConfig(): TypeOrmModuleOptions{
 return({
    type: "postgres",
    username: "conduit",
    password: "conduit",
    database: "conduit"
    entities: [join(__dirname, '**', '*.entity.{ts, js}')],
    synchronize: true,
    logging: true,
    logger: "advanced-console",
});
}
```

* Next we have to create the `entities` for our Database . And the individual entity to the entities array in the `createConnection` function . 
```$ mkdir src/entities```
```$cd entities```
```$nano Article.ts``` 

```typescript
@Entity()
export class Article {
    
    @PrimaryColumn({length: 40})
    slug: string

    @Column({length: 40})
    title?: string

    @Column({length: 100, nullable:true})
    description: string

    @Column({type: 'text'})
    body: string
```
### __Generate module, service, controller for the article route :__
```$
nest g mo article module
nest g co article module
nest g s article module
```
```$ cd module/article```
```$ nano module.article.ts```
`imports : [Typeormmodue.forFeature([Article])]`

* navigate to the article service file .
```
@InjectRepository(Article) private readonly articleRepo: Repository<Article>,

async getAllArticles(): Promise<Article[]> {
        return await this.articleRepo.find();
    }
```
* navigate to the article controller file .
 ```
constructor(private readonly articlesService: ArticlesService) {}
@Get()
    async getAllArticles(): Promise<Article[]> {
        return await this.articlesService.getAllArticles();
    }
```

Then finally in the application root module .
``` imports :[TypeOrmModule.forroot([Article])] ```

```$npm start```

Thank You For Reading 🔥