├── .editorconfig
├── .eslintrc.js
├── .gitignore
├── .prettierrc
├── README.md
├── nest-cli.json
├── package-lock.json
├── package.json
├── src
├── api
│ ├── api.module.ts
│ └── user
│ │ ├── user.controller.ts
│ │ ├── user.dto.ts
│ │ ├── user.entity.ts
│ │ ├── user.module.ts
│ │ └── user.service.ts
├── app.controller.spec.ts
├── app.controller.ts
├── app.module.ts
├── app.service.ts
├── common
│ ├── envs
│ │ ├── .env
│ │ └── development.env
│ └── helper
│ │ └── env.helper.ts
├── main.ts
└── shared
│ └── typeorm
│ └── typeorm.service.ts
├── test
├── app.e2e-spec.ts
└── jest-e2e.json
├── tsconfig.build.json
└── tsconfig.json
/.editorconfig:
--------------------------------------------------------------------------------
1 | [*.{js,jsx,ts,tsx,vue,scss,sass}]
2 | indent_style = space
3 | indent_size = 2
4 | end_of_line = lf
5 | trim_trailing_whitespace = true
6 | insert_final_newline = true
7 | max_line_length = 130
8 |
--------------------------------------------------------------------------------
/.eslintrc.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | parser: '@typescript-eslint/parser',
3 | parserOptions: {
4 | project: 'tsconfig.json',
5 | sourceType: 'module',
6 | },
7 | plugins: ['@typescript-eslint/eslint-plugin'],
8 | extends: [
9 | 'plugin:@typescript-eslint/recommended',
10 | 'plugin:prettier/recommended',
11 | ],
12 | root: true,
13 | env: {
14 | node: true,
15 | jest: true,
16 | },
17 | ignorePatterns: ['.eslintrc.js'],
18 | rules: {
19 | '@typescript-eslint/interface-name-prefix': 'off',
20 | '@typescript-eslint/explicit-function-return-type': 'off',
21 | '@typescript-eslint/explicit-module-boundary-types': 'off',
22 | '@typescript-eslint/no-explicit-any': 'off',
23 | },
24 | };
25 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # compiled output
2 | /dist
3 | /node_modules
4 |
5 | # Logs
6 | logs
7 | *.log
8 | npm-debug.log*
9 | pnpm-debug.log*
10 | yarn-debug.log*
11 | yarn-error.log*
12 | lerna-debug.log*
13 |
14 | # OS
15 | .DS_Store
16 |
17 | # Tests
18 | /coverage
19 | /.nyc_output
20 |
21 | # IDEs and editors
22 | /.idea
23 | .project
24 | .classpath
25 | .c9/
26 | *.launch
27 | .settings/
28 | *.sublime-workspace
29 |
30 | # IDE - VSCode
31 | .vscode/*
32 | !.vscode/settings.json
33 | !.vscode/tasks.json
34 | !.vscode/launch.json
35 | !.vscode/extensions.json
--------------------------------------------------------------------------------
/.prettierrc:
--------------------------------------------------------------------------------
1 | {
2 | "singleQuote": true,
3 | "trailingComma": "all",
4 | "arrowParens": "always",
5 | "tabWidth": 2,
6 | "printWidth": 130
7 | }
8 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | [circleci-image]: https://img.shields.io/circleci/build/github/nestjs/nest/master?token=abc123def456
6 | [circleci-url]: https://circleci.com/gh/nestjs/nest
7 |
8 | A progressive Node.js framework for building efficient and scalable server-side applications.
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
24 |
25 | ## Description
26 |
27 | [Nest](https://github.com/nestjs/nest) framework TypeScript starter repository.
28 |
29 | ## Installation
30 |
31 | ```bash
32 | $ npm install
33 | ```
34 |
35 | ## Running the app
36 |
37 | ```bash
38 | # development
39 | $ npm run start
40 |
41 | # watch mode
42 | $ npm run start:dev
43 |
44 | # production mode
45 | $ npm run start:prod
46 | ```
47 |
48 | ## Test
49 |
50 | ```bash
51 | # unit tests
52 | $ npm run test
53 |
54 | # e2e tests
55 | $ npm run test:e2e
56 |
57 | # test coverage
58 | $ npm run test:cov
59 | ```
60 |
61 | ## Support
62 |
63 | Nest is an MIT-licensed open source project. It can grow thanks to the sponsors and support by the amazing backers. If you'd like to join them, please [read more here](https://docs.nestjs.com/support).
64 |
65 | ## Stay in touch
66 |
67 | - Author - [Kamil Myśliwiec](https://kamilmysliwiec.com)
68 | - Website - [https://nestjs.com](https://nestjs.com/)
69 | - Twitter - [@nestframework](https://twitter.com/nestframework)
70 |
71 | ## License
72 |
73 | Nest is [MIT licensed](LICENSE).
74 |
--------------------------------------------------------------------------------
/nest-cli.json:
--------------------------------------------------------------------------------
1 | {
2 | "collection": "@nestjs/schematics",
3 | "sourceRoot": "src",
4 | "compilerOptions": {
5 | "assets": ["common/envs/*"]
6 | }
7 | }
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "nest-postgres",
3 | "version": "0.0.1",
4 | "description": "",
5 | "author": "",
6 | "private": true,
7 | "license": "UNLICENSED",
8 | "scripts": {
9 | "prebuild": "rimraf dist",
10 | "build": "nest build",
11 | "format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
12 | "start": "nest start",
13 | "start:dev": "npm run prebuild && nest start --watch",
14 | "start:debug": "npm run prebuild && nest start --debug --watch",
15 | "start:prod": "node dist/main",
16 | "lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
17 | "test": "jest",
18 | "test:watch": "jest --watch",
19 | "test:cov": "jest --coverage",
20 | "test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
21 | "test:e2e": "jest --config ./test/jest-e2e.json"
22 | },
23 | "dependencies": {
24 | "@nestjs/common": "^8.0.0",
25 | "@nestjs/config": "^1.2.0",
26 | "@nestjs/core": "^8.0.0",
27 | "@nestjs/platform-express": "^8.0.0",
28 | "@nestjs/typeorm": "^8.0.3",
29 | "class-transformer": "^0.5.1",
30 | "class-validator": "^0.13.2",
31 | "pg": "^8.7.3",
32 | "reflect-metadata": "^0.1.13",
33 | "rimraf": "^3.0.2",
34 | "rxjs": "^7.2.0",
35 | "typeorm": "^0.2.43"
36 | },
37 | "devDependencies": {
38 | "@nestjs/cli": "^8.0.0",
39 | "@nestjs/schematics": "^8.0.0",
40 | "@nestjs/testing": "^8.0.0",
41 | "@types/express": "^4.17.13",
42 | "@types/jest": "^26.0.24",
43 | "@types/node": "^16.11.25",
44 | "@types/supertest": "^2.0.11",
45 | "@typescript-eslint/eslint-plugin": "^4.28.2",
46 | "@typescript-eslint/parser": "^4.28.2",
47 | "eslint": "^7.30.0",
48 | "eslint-config-prettier": "^8.3.0",
49 | "eslint-plugin-prettier": "^3.4.0",
50 | "jest": "27.0.6",
51 | "prettier": "^2.3.2",
52 | "supertest": "^6.1.3",
53 | "ts-jest": "^27.0.3",
54 | "ts-loader": "^9.2.3",
55 | "ts-node": "^10.0.0",
56 | "tsconfig-paths": "^3.10.1",
57 | "typescript": "^4.3.5"
58 | },
59 | "jest": {
60 | "moduleFileExtensions": [
61 | "js",
62 | "json",
63 | "ts"
64 | ],
65 | "rootDir": "src",
66 | "testRegex": ".*\\.spec\\.ts$",
67 | "transform": {
68 | "^.+\\.(t|j)s$": "ts-jest"
69 | },
70 | "collectCoverageFrom": [
71 | "**/*.(t|j)s"
72 | ],
73 | "coverageDirectory": "../coverage",
74 | "testEnvironment": "node"
75 | }
76 | }
77 |
--------------------------------------------------------------------------------
/src/api/api.module.ts:
--------------------------------------------------------------------------------
1 | import { Module } from '@nestjs/common';
2 | import { UserModule } from './user/user.module';
3 |
4 | @Module({
5 | imports: [UserModule],
6 | })
7 | export class ApiModule {}
8 |
--------------------------------------------------------------------------------
/src/api/user/user.controller.ts:
--------------------------------------------------------------------------------
1 | import { Body, Controller, Get, Inject, Param, ParseIntPipe, Post } from '@nestjs/common';
2 | import { CreateUserDto } from './user.dto';
3 | import { User } from './user.entity';
4 | import { UserService } from './user.service';
5 |
6 | @Controller('user')
7 | export class UserController {
8 | @Inject(UserService)
9 | private readonly service: UserService;
10 |
11 | @Get(':id')
12 | public getUser(@Param('id', ParseIntPipe) id: number): Promise {
13 | return this.service.getUser(id);
14 | }
15 |
16 | @Post()
17 | public createUser(@Body() body: CreateUserDto): Promise {
18 | return this.service.createUser(body);
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/src/api/user/user.dto.ts:
--------------------------------------------------------------------------------
1 | import { IsEmail, IsNotEmpty, IsString } from 'class-validator';
2 |
3 | export class CreateUserDto {
4 | @IsString()
5 | @IsNotEmpty()
6 | public name: string;
7 |
8 | @IsEmail()
9 | public email: string;
10 | }
11 |
--------------------------------------------------------------------------------
/src/api/user/user.entity.ts:
--------------------------------------------------------------------------------
1 | import { Entity, PrimaryGeneratedColumn, Column, CreateDateColumn, UpdateDateColumn } from 'typeorm';
2 |
3 | @Entity()
4 | export class User {
5 | @PrimaryGeneratedColumn()
6 | public id!: number;
7 |
8 | @Column({ type: 'varchar', length: 120 })
9 | public name: string;
10 |
11 | @Column({ type: 'varchar', length: 120 })
12 | public email: string;
13 |
14 | @Column({ type: 'boolean', default: false })
15 | public isDeleted: boolean;
16 |
17 | /*
18 | * Create and Update Date Columns
19 | */
20 |
21 | @CreateDateColumn({ type: 'timestamp' })
22 | public createdAt!: Date;
23 |
24 | @UpdateDateColumn({ type: 'timestamp' })
25 | public updatedAt!: Date;
26 | }
27 |
--------------------------------------------------------------------------------
/src/api/user/user.module.ts:
--------------------------------------------------------------------------------
1 | import { Module } from '@nestjs/common';
2 | import { TypeOrmModule } from '@nestjs/typeorm';
3 | import { UserController } from './user.controller';
4 | import { User } from './user.entity';
5 | import { UserService } from './user.service';
6 |
7 | @Module({
8 | imports: [TypeOrmModule.forFeature([User])],
9 | controllers: [UserController],
10 | providers: [UserService],
11 | })
12 | export class UserModule {}
13 |
--------------------------------------------------------------------------------
/src/api/user/user.service.ts:
--------------------------------------------------------------------------------
1 | import { Injectable } from '@nestjs/common';
2 | import { InjectRepository } from '@nestjs/typeorm';
3 | import { Repository } from 'typeorm';
4 | import { CreateUserDto } from './user.dto';
5 | import { User } from './user.entity';
6 |
7 | @Injectable()
8 | export class UserService {
9 | @InjectRepository(User)
10 | private readonly repository: Repository;
11 |
12 | public getUser(id: number): Promise {
13 | return this.repository.findOne(id);
14 | }
15 |
16 | public createUser(body: CreateUserDto): Promise {
17 | const user: User = new User();
18 |
19 | user.name = body.name;
20 | user.email = body.email;
21 |
22 | return this.repository.save(user);
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/src/app.controller.spec.ts:
--------------------------------------------------------------------------------
1 | import { Test, TestingModule } from '@nestjs/testing';
2 | import { AppController } from './app.controller';
3 | import { AppService } from './app.service';
4 |
5 | describe('AppController', () => {
6 | let appController: AppController;
7 |
8 | beforeEach(async () => {
9 | const app: TestingModule = await Test.createTestingModule({
10 | controllers: [AppController],
11 | providers: [AppService],
12 | }).compile();
13 |
14 | appController = app.get(AppController);
15 | });
16 |
17 | describe('root', () => {
18 | it('should return "Hello World!"', () => {
19 | expect(appController.getHello()).toBe('Hello World!');
20 | });
21 | });
22 | });
23 |
--------------------------------------------------------------------------------
/src/app.controller.ts:
--------------------------------------------------------------------------------
1 | import { Controller, Get } from '@nestjs/common';
2 | import { AppService } from './app.service';
3 |
4 | @Controller()
5 | export class AppController {
6 | constructor(private readonly appService: AppService) {}
7 |
8 | @Get()
9 | getHello(): string {
10 | return this.appService.getHello();
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/src/app.module.ts:
--------------------------------------------------------------------------------
1 | import { Module } from '@nestjs/common';
2 | import { ConfigModule } from '@nestjs/config';
3 | import { TypeOrmModule } from '@nestjs/typeorm';
4 | import { ApiModule } from './api/api.module';
5 | import { AppController } from './app.controller';
6 | import { AppService } from './app.service';
7 | import { getEnvPath } from './common/helper/env.helper';
8 | import { TypeOrmConfigService } from './shared/typeorm/typeorm.service';
9 |
10 | const envFilePath: string = getEnvPath(`${__dirname}/common/envs`);
11 |
12 | @Module({
13 | imports: [
14 | ConfigModule.forRoot({ envFilePath, isGlobal: true }),
15 | TypeOrmModule.forRootAsync({ useClass: TypeOrmConfigService }),
16 | ApiModule,
17 | ],
18 | controllers: [AppController],
19 | providers: [AppService],
20 | })
21 | export class AppModule {}
22 |
--------------------------------------------------------------------------------
/src/app.service.ts:
--------------------------------------------------------------------------------
1 | import { Injectable } from '@nestjs/common';
2 |
3 | @Injectable()
4 | export class AppService {
5 | getHello(): string {
6 | return 'Hello World!';
7 | }
8 | }
9 |
--------------------------------------------------------------------------------
/src/common/envs/.env:
--------------------------------------------------------------------------------
1 | PORT=3000
2 | BASE_URL=http://localhost:3000
3 |
4 | DATABASE_HOST=
5 | DATABASE_NAME=
6 | DATABASE_USER=
7 | DATABASE_PASSWORD=
8 | DATABASE_PORT=
--------------------------------------------------------------------------------
/src/common/envs/development.env:
--------------------------------------------------------------------------------
1 | PORT=3000
2 | BASE_URL=http://localhost:3000
3 |
4 | DATABASE_HOST=localhost
5 | DATABASE_NAME=nest_api
6 | DATABASE_USER=kevin
7 | DATABASE_PASSWORD=
8 | DATABASE_PORT=5432
--------------------------------------------------------------------------------
/src/common/helper/env.helper.ts:
--------------------------------------------------------------------------------
1 | import { existsSync } from 'fs';
2 | import { resolve } from 'path';
3 |
4 | export function getEnvPath(dest: string): string {
5 | const env: string | undefined = process.env.NODE_ENV;
6 | const fallback: string = resolve(`${dest}/.env`);
7 | const filename: string = env ? `${env}.env` : 'development.env';
8 | let filePath: string = resolve(`${dest}/${filename}`);
9 |
10 | if (!existsSync(filePath)) {
11 | filePath = fallback;
12 | }
13 |
14 | return filePath;
15 | }
16 |
--------------------------------------------------------------------------------
/src/main.ts:
--------------------------------------------------------------------------------
1 | import { ValidationPipe } from '@nestjs/common';
2 | import { ConfigService } from '@nestjs/config';
3 | import { NestFactory } from '@nestjs/core';
4 | import { NestExpressApplication } from '@nestjs/platform-express';
5 | import { AppModule } from './app.module';
6 |
7 | async function bootstrap() {
8 | const app: NestExpressApplication = await NestFactory.create(AppModule);
9 | const config: ConfigService = app.get(ConfigService);
10 | const port: number = config.get('PORT');
11 |
12 | app.useGlobalPipes(new ValidationPipe({ whitelist: true, transform: true }));
13 |
14 | await app.listen(port, () => {
15 | console.log('[WEB]', config.get('BASE_URL'));
16 | });
17 | }
18 |
19 | bootstrap();
20 |
--------------------------------------------------------------------------------
/src/shared/typeorm/typeorm.service.ts:
--------------------------------------------------------------------------------
1 | import { Injectable, Inject } from '@nestjs/common';
2 | import { ConfigService } from '@nestjs/config';
3 | import { TypeOrmOptionsFactory, TypeOrmModuleOptions } from '@nestjs/typeorm';
4 |
5 | @Injectable()
6 | export class TypeOrmConfigService implements TypeOrmOptionsFactory {
7 | @Inject(ConfigService)
8 | private readonly config: ConfigService;
9 |
10 | public createTypeOrmOptions(): TypeOrmModuleOptions {
11 | return {
12 | type: 'postgres',
13 | host: this.config.get('DATABASE_HOST'),
14 | port: this.config.get('DATABASE_PORT'),
15 | database: this.config.get('DATABASE_NAME'),
16 | username: this.config.get('DATABASE_USER'),
17 | password: this.config.get('DATABASE_PASSWORD'),
18 | entities: ['dist/**/*.entity.{ts,js}'],
19 | migrations: ['dist/migrations/*.{ts,js}'],
20 | migrationsTableName: 'typeorm_migrations',
21 | logger: 'file',
22 | synchronize: true, // never use TRUE in production!
23 | };
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/test/app.e2e-spec.ts:
--------------------------------------------------------------------------------
1 | import { Test, TestingModule } from '@nestjs/testing';
2 | import { INestApplication } from '@nestjs/common';
3 | import * as request from 'supertest';
4 | import { AppModule } from './../src/app.module';
5 |
6 | describe('AppController (e2e)', () => {
7 | let app: INestApplication;
8 |
9 | beforeEach(async () => {
10 | const moduleFixture: TestingModule = await Test.createTestingModule({
11 | imports: [AppModule],
12 | }).compile();
13 |
14 | app = moduleFixture.createNestApplication();
15 | await app.init();
16 | });
17 |
18 | it('/ (GET)', () => {
19 | return request(app.getHttpServer())
20 | .get('/')
21 | .expect(200)
22 | .expect('Hello World!');
23 | });
24 | });
25 |
--------------------------------------------------------------------------------
/test/jest-e2e.json:
--------------------------------------------------------------------------------
1 | {
2 | "moduleFileExtensions": ["js", "json", "ts"],
3 | "rootDir": ".",
4 | "testEnvironment": "node",
5 | "testRegex": ".e2e-spec.ts$",
6 | "transform": {
7 | "^.+\\.(t|j)s$": "ts-jest"
8 | }
9 | }
10 |
--------------------------------------------------------------------------------
/tsconfig.build.json:
--------------------------------------------------------------------------------
1 | {
2 | "extends": "./tsconfig.json",
3 | "exclude": ["node_modules", "test", "dist", "**/*spec.ts"]
4 | }
5 |
--------------------------------------------------------------------------------
/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "module": "commonjs",
4 | "declaration": true,
5 | "removeComments": true,
6 | "emitDecoratorMetadata": true,
7 | "experimentalDecorators": true,
8 | "allowSyntheticDefaultImports": true,
9 | "target": "es2017",
10 | "sourceMap": true,
11 | "outDir": "./dist",
12 | "baseUrl": "./",
13 | "incremental": true,
14 | "skipLibCheck": true
15 | }
16 | }
17 |
--------------------------------------------------------------------------------