├── .eslintrc.js ├── .gitignore ├── .prettierrc ├── Nest.js - Arquitetura da aplicação@1.25x.png ├── README.md ├── api.http ├── bank-accounts.sqlite ├── nest-cli.json ├── package-lock.json ├── package.json ├── src ├── @core │ ├── domain │ │ ├── bank-account.repository.ts │ │ ├── bank-account.service.spec.ts │ │ ├── bank-account.service.ts │ │ ├── bank-account.spec.ts │ │ ├── bank-account.ts │ │ └── transfer.service.ts │ └── infra │ │ └── db │ │ ├── bank-account-typeorm.repository.spec.ts │ │ ├── bank-account-typeorm.repository.ts │ │ └── bank-account.schema.ts ├── app.controller.spec.ts ├── app.controller.ts ├── app.module.ts ├── app.service.ts ├── bank-accounts │ ├── bank-accounts.controller.spec.ts │ ├── bank-accounts.controller.ts │ ├── bank-accounts.module.ts │ ├── bank-accounts.service.spec.ts │ ├── bank-accounts.service.ts │ └── dto │ │ ├── create-bank-account.dto.ts │ │ └── transfer-bank-account.dto.ts ├── main.ts └── repl.ts ├── test ├── app.e2e-spec.ts └── jest-e2e.json ├── tsconfig.build.json └── tsconfig.json /.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | parser: '@typescript-eslint/parser', 3 | parserOptions: { 4 | project: 'tsconfig.json', 5 | tsconfigRootDir : __dirname, 6 | sourceType: 'module', 7 | }, 8 | plugins: ['@typescript-eslint/eslint-plugin'], 9 | extends: [ 10 | 'plugin:@typescript-eslint/recommended', 11 | 'plugin:prettier/recommended', 12 | ], 13 | root: true, 14 | env: { 15 | node: true, 16 | jest: true, 17 | }, 18 | ignorePatterns: ['.eslintrc.js'], 19 | rules: { 20 | '@typescript-eslint/interface-name-prefix': 'off', 21 | '@typescript-eslint/explicit-function-return-type': 'off', 22 | '@typescript-eslint/explicit-module-boundary-types': 'off', 23 | '@typescript-eslint/no-explicit-any': 'off', 24 | }, 25 | }; 26 | -------------------------------------------------------------------------------- /.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 36 | 37 | .history/ -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "singleQuote": true, 3 | "trailingComma": "all" 4 | } -------------------------------------------------------------------------------- /Nest.js - Arquitetura da aplicação@1.25x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codeedu/live-imersao-fullcycle9-nestjs-ddd/04816ef9a27afd197b3179bc66866adedd3306b1/Nest.js - Arquitetura da aplicação@1.25x.png -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ![Imersão Full Stack && Full Cycle](https://events-fullcycle.s3.amazonaws.com/events-fullcycle/static/site/img/grupo_4417.png) 2 | 3 | Participe gratuitamente: https://imersao.fullcycle.com.br/ 4 | 5 | ## Sobre o repositório 6 | Esse repositório contém o código-fonte ministrado na aula Nest.js com Domain Driven Design (DDD): [https://www.youtube.com/watch?v=XTmvAj5OSQI](https://www.youtube.com/watch?v=XTmvAj5OSQI) 7 | 8 | ## Rodar a aplicação 9 | 10 | Execute os comandos: 11 | 12 | ```bash 13 | npm install 14 | npm run start:dev 15 | ``` 16 | 17 | Acesse http://localhost:3000/bank-accounts ou use o arquivo `api.http` para testar a API usando a extensão Rest Client do VSCode ou outra ferramenta para brincar com o HTTP. -------------------------------------------------------------------------------- /api.http: -------------------------------------------------------------------------------- 1 | GET http://localhost:3000/bank-accounts 2 | 3 | ### 4 | GET http://localhost:3000/bank-accounts/ce669d21-4fa4-47bb-8918-e657b809910a 5 | 6 | ### 7 | POST http://localhost:3000/bank-accounts 8 | Content-Type: application/json 9 | 10 | { 11 | "account_number": "5555-55" 12 | } 13 | 14 | ### 15 | PATCH http://localhost:3000/bank-accounts/123 16 | Content-Type: application/json 17 | 18 | { 19 | "account_number": 1234 20 | } 21 | 22 | ### 23 | DELETE http://localhost:3000/bank-accounts/123 24 | 25 | ### 26 | POST http://localhost:3000/bank-accounts/transfer 27 | Content-Type: application/json 28 | 29 | { 30 | "from": "4444-44", 31 | "to": "5555-55", 32 | "amount": 100 33 | } -------------------------------------------------------------------------------- /bank-accounts.sqlite: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codeedu/live-imersao-fullcycle9-nestjs-ddd/04816ef9a27afd197b3179bc66866adedd3306b1/bank-accounts.sqlite -------------------------------------------------------------------------------- /nest-cli.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://json.schemastore.org/nest-cli", 3 | "collection": "@nestjs/schematics", 4 | "sourceRoot": "src" 5 | } 6 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "iniciando-nestjs-9", 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": "nest start --watch", 14 | "start:debug": "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 | "repl": "npm run start -- --entryFile repl" 23 | }, 24 | "dependencies": { 25 | "@nestjs/common": "^9.0.0", 26 | "@nestjs/core": "^9.0.0", 27 | "@nestjs/mapped-types": "*", 28 | "@nestjs/platform-express": "^9.0.0", 29 | "@nestjs/typeorm": "^9.0.0", 30 | "reflect-metadata": "^0.1.13", 31 | "rimraf": "^3.0.2", 32 | "rxjs": "^7.2.0", 33 | "sqlite3": "^5.0.11", 34 | "typeorm": "^0.3.7", 35 | "uuid": "^8.3.2" 36 | }, 37 | "devDependencies": { 38 | "@nestjs/cli": "^9.0.0", 39 | "@nestjs/schematics": "^9.0.0", 40 | "@nestjs/testing": "^9.0.0", 41 | "@types/express": "^4.17.13", 42 | "@types/jest": "28.1.4", 43 | "@types/node": "^16.0.0", 44 | "@types/supertest": "^2.0.11", 45 | "@typescript-eslint/eslint-plugin": "^5.0.0", 46 | "@typescript-eslint/parser": "^5.0.0", 47 | "eslint": "^8.0.1", 48 | "eslint-config-prettier": "^8.3.0", 49 | "eslint-plugin-prettier": "^4.0.0", 50 | "jest": "28.1.2", 51 | "prettier": "^2.3.2", 52 | "source-map-support": "^0.5.20", 53 | "supertest": "^6.1.3", 54 | "ts-jest": "28.0.5", 55 | "ts-loader": "^9.2.3", 56 | "ts-node": "^10.0.0", 57 | "tsconfig-paths": "4.0.0", 58 | "typescript": "^4.3.5" 59 | }, 60 | "jest": { 61 | "moduleFileExtensions": [ 62 | "js", 63 | "json", 64 | "ts" 65 | ], 66 | "rootDir": "src", 67 | "testRegex": ".*\\.spec\\.ts$", 68 | "transform": { 69 | "^.+\\.(t|j)s$": "ts-jest" 70 | }, 71 | "collectCoverageFrom": [ 72 | "**/*.(t|j)s" 73 | ], 74 | "coverageDirectory": "../coverage", 75 | "testEnvironment": "node" 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /src/@core/domain/bank-account.repository.ts: -------------------------------------------------------------------------------- 1 | import { BankAccount } from './bank-account'; 2 | 3 | export interface BankAccountRepository { 4 | insert(bankAccount: BankAccount): Promise; 5 | update(bankAccount: BankAccount): Promise; 6 | findByAccountNumber(accountNumber: string): Promise; 7 | } 8 | -------------------------------------------------------------------------------- /src/@core/domain/bank-account.service.spec.ts: -------------------------------------------------------------------------------- 1 | import { DataSource, Repository } from 'typeorm'; 2 | import { BankAccountTypeOrmRepository } from '../infra/db/bank-account-typeorm.repository'; 3 | import { BankAccountSchema } from '../infra/db/bank-account.schema'; 4 | import { BankAccountService } from './bank-account.service'; 5 | 6 | describe('BankAccountService Test', () => { 7 | let dataSource: DataSource; 8 | let ormRepo: Repository; 9 | let repository: BankAccountTypeOrmRepository; 10 | let bankAccountService: BankAccountService; 11 | 12 | beforeEach(async () => { 13 | dataSource = new DataSource({ 14 | type: 'sqlite', 15 | database: ':memory:', 16 | synchronize: true, 17 | logging: true, 18 | entities: [BankAccountSchema], 19 | }); 20 | await dataSource.initialize(); 21 | ormRepo = dataSource.getRepository(BankAccountSchema); 22 | repository = new BankAccountTypeOrmRepository(ormRepo); 23 | bankAccountService = new BankAccountService(repository); 24 | }); 25 | 26 | it('should create a new bank account', async () => { 27 | await bankAccountService.create('1111-11'); 28 | const model = await ormRepo.findOneBy({ account_number: '1111-11' }); 29 | expect(model.id).toBe('123'); 30 | expect(model.balance).toBe(0); 31 | expect(model.account_number).toBe('1111-11'); 32 | }); 33 | }); 34 | -------------------------------------------------------------------------------- /src/@core/domain/bank-account.service.ts: -------------------------------------------------------------------------------- 1 | import { BankAccount } from './bank-account'; 2 | import { BankAccountRepository } from './bank-account.repository'; 3 | import { TransferService } from './transfer.service'; 4 | 5 | export class BankAccountService { 6 | //Application Service 7 | constructor(private bankAccountRepo: BankAccountRepository) {} 8 | 9 | async create(account_number: string) { 10 | const bankAccount = new BankAccount(0, account_number); 11 | await this.bankAccountRepo.insert(bankAccount); 12 | return bankAccount; 13 | } 14 | 15 | async transfer( 16 | account_number_src: string, 17 | account_number_dest: string, 18 | amount: number, 19 | ) { 20 | const bankAccountSrc = await this.bankAccountRepo.findByAccountNumber( 21 | account_number_src, 22 | ); 23 | const bankAccountDest = await this.bankAccountRepo.findByAccountNumber( 24 | account_number_dest, 25 | ); 26 | 27 | const transferService = new TransferService(); 28 | transferService.transfer(bankAccountSrc, bankAccountDest, amount); 29 | 30 | await this.bankAccountRepo.update(bankAccountSrc); 31 | await this.bankAccountRepo.update(bankAccountDest); 32 | } 33 | } 34 | 35 | //DDD - ID auto incrementado 36 | -------------------------------------------------------------------------------- /src/@core/domain/bank-account.spec.ts: -------------------------------------------------------------------------------- 1 | import { BankAccount } from './bank-account'; 2 | 3 | describe('BankAccount Unit Tests', () => { 4 | it('should create a bank account', () => { 5 | const bankAccount = new BankAccount('123', 100, '12345'); 6 | expect(bankAccount.id).toBe('123'); 7 | expect(bankAccount.balance).toBe(100); 8 | expect(bankAccount.account_number).toBe('12345'); 9 | }); 10 | 11 | it('should debit an account', () => { 12 | const bankAccount = new BankAccount('123', 100, '12345'); 13 | bankAccount.debit(50); 14 | expect(bankAccount.balance).toBe(50); 15 | }); 16 | 17 | it('should credit an account', () => { 18 | const bankAccount = new BankAccount('123', 100, '12345'); 19 | bankAccount.credit(50); 20 | expect(bankAccount.balance).toBe(150); 21 | }); 22 | }); 23 | -------------------------------------------------------------------------------- /src/@core/domain/bank-account.ts: -------------------------------------------------------------------------------- 1 | import { v4 as uuid } from 'uuid'; 2 | 3 | export class BankAccount { 4 | //typeorm 5 | id: string; 6 | 7 | balance: number; 8 | 9 | account_number: string; 10 | 11 | constructor(balance: number, account_number: string, id?: string) { 12 | //regras de negócio 13 | this.id = id ?? uuid(); 14 | this.balance = balance; 15 | this.account_number = account_number; 16 | } 17 | 18 | debit(amount: number): void { 19 | //regras de negócio 20 | this.balance -= amount; 21 | } 22 | 23 | credit(amount: number): void { 24 | //regras de negócio 25 | this.balance += amount; 26 | } 27 | } 28 | 29 | // type BankAccountProps = { 30 | // balance: number; 31 | // account_number: string; 32 | // } 33 | 34 | // export class BankAccount { 35 | // //typeorm 36 | // id: string; 37 | 38 | // constructor(public readonly props: BankAccountProps, id?: string) { 39 | // //regras de negócio 40 | // this.id = id ?? uuid(); 41 | // } 42 | 43 | // debit(amount: number): void { 44 | // //regras de negócio 45 | // this.balance -= amount; 46 | // } 47 | 48 | // credit(amount: number): void { 49 | // //regras de negócio 50 | // this.balance += amount; 51 | // } 52 | 53 | // get balance(): number { 54 | // return this.props.balance; 55 | // } 56 | 57 | // private set balance(value: number){ 58 | // this.props.balance = value; 59 | // } 60 | 61 | // get account_number(): string { 62 | // return this.props.account_number; 63 | // } 64 | 65 | // private set account_number(value: string){ 66 | // this.props.account_number = value; 67 | // } 68 | // } 69 | //criar 70 | //depositar 71 | //creditar 72 | 73 | // 74 | 75 | //prisma linguagem schema eficiente 76 | //serviços externos ao ORM 77 | 78 | // 79 | 80 | //risca 81 | 82 | //ddd - solucionar/ajudar a complexidade do coração do sistema 83 | //linguagem ubiqua 84 | //arquitetura em camadas 85 | -------------------------------------------------------------------------------- /src/@core/domain/transfer.service.ts: -------------------------------------------------------------------------------- 1 | import { BankAccount } from './bank-account'; 2 | 3 | export class TransferService { 4 | async transfer( 5 | bankAccountSrc: BankAccount, 6 | bankAccountDest: BankAccount, 7 | amount: number, 8 | ) { 9 | bankAccountSrc.debit(amount); 10 | bankAccountDest.credit(amount); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/@core/infra/db/bank-account-typeorm.repository.spec.ts: -------------------------------------------------------------------------------- 1 | import { DataSource, Repository } from 'typeorm'; 2 | import { BankAccount } from '../../domain/bank-account'; 3 | import { BankAccountTypeOrmRepository } from './bank-account-typeorm.repository'; 4 | import { BankAccountSchema } from './bank-account.schema'; 5 | 6 | describe('BankAccountTypeOrmRepository Test', () => { 7 | let dataSource: DataSource; 8 | let ormRepo: Repository; 9 | let repository: BankAccountTypeOrmRepository; 10 | 11 | beforeEach(async () => { 12 | dataSource = new DataSource({ 13 | type: 'sqlite', 14 | database: ':memory:', 15 | synchronize: true, 16 | logging: true, 17 | entities: [BankAccountSchema], 18 | }); 19 | await dataSource.initialize(); 20 | ormRepo = dataSource.getRepository(BankAccountSchema); 21 | repository = new BankAccountTypeOrmRepository(ormRepo); 22 | }); 23 | 24 | it('should insert a new bank account', async () => { 25 | const bankAccount = new BankAccount('123', 100, '1111-11'); 26 | await repository.insert(bankAccount); 27 | const model = await ormRepo.findOneBy({ account_number: '1111-11' }); 28 | expect(model.id).toBe('123'); 29 | expect(model.balance).toBe(100); 30 | expect(model.account_number).toBe('1111-11'); 31 | }); 32 | }); 33 | -------------------------------------------------------------------------------- /src/@core/infra/db/bank-account-typeorm.repository.ts: -------------------------------------------------------------------------------- 1 | import { Repository } from 'typeorm'; 2 | import { BankAccountSchema } from './bank-account.schema'; 3 | import { BankAccount } from '../../domain/bank-account'; 4 | import { BankAccountRepository } from '../../domain/bank-account.repository'; 5 | 6 | export class BankAccountTypeOrmRepository implements BankAccountRepository { 7 | constructor(private ormRepo: Repository) {} 8 | 9 | async insert(bankAccount: BankAccount): Promise { 10 | const model = this.ormRepo.create(bankAccount); 11 | await this.ormRepo.insert(model); 12 | } 13 | 14 | async update(bankAccount: BankAccount): Promise { 15 | await this.ormRepo.update(bankAccount.id, { 16 | balance: bankAccount.balance, 17 | }); 18 | } 19 | 20 | async findByAccountNumber(account_number: string): Promise { 21 | const model = await this.ormRepo.findOneBy({ 22 | account_number: account_number, 23 | }); 24 | return new BankAccount(model.balance, model.account_number, model.id); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/@core/infra/db/bank-account.schema.ts: -------------------------------------------------------------------------------- 1 | import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm'; 2 | 3 | @Entity() 4 | export class BankAccountSchema { 5 | //typeorm 6 | @PrimaryGeneratedColumn('uuid') 7 | id: string; 8 | 9 | @Column({ type: 'decimal', scale: 2 }) 10 | balance: number; 11 | 12 | @Column({ length: 255 }) 13 | account_number: string; 14 | } 15 | 16 | //modelo anemico | entidade anemica Martin Fowler 17 | -------------------------------------------------------------------------------- /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('prefixo') 5 | export class AppController { 6 | constructor(private readonly appService: AppService) {} 7 | 8 | @Get('test') 9 | getHello(): string { 10 | return this.appService.getHello(); 11 | } 12 | 13 | @Get('test2') 14 | test2(){ 15 | return 'test2'; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/app.module.ts: -------------------------------------------------------------------------------- 1 | import { Module } from '@nestjs/common'; 2 | import { AppController } from './app.controller'; 3 | import { AppService } from './app.service'; 4 | import { BankAccountsModule } from './bank-accounts/bank-accounts.module'; 5 | import { TypeOrmModule } from '@nestjs/typeorm'; 6 | import { BankAccountSchema } from './@core/infra/db/bank-account.schema'; 7 | @Module({ 8 | imports: [ 9 | TypeOrmModule.forRoot({ 10 | type: 'sqlite', 11 | database: __dirname + '/db.sqlite', 12 | synchronize: true, 13 | logging: true, 14 | entities: [BankAccountSchema], 15 | }), 16 | BankAccountsModule, 17 | ], 18 | controllers: [AppController], 19 | providers: [AppService], 20 | }) 21 | export class AppModule {} 22 | 23 | //modular - Angular 24 | -------------------------------------------------------------------------------- /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/bank-accounts/bank-accounts.controller.spec.ts: -------------------------------------------------------------------------------- 1 | import { Test, TestingModule } from '@nestjs/testing'; 2 | import { BankAccountsController } from './bank-accounts.controller'; 3 | import { BankAccountsService } from './bank-accounts.service'; 4 | 5 | describe('BankAccountsController', () => { 6 | let controller: BankAccountsController; 7 | 8 | beforeEach(async () => { 9 | const module: TestingModule = await Test.createTestingModule({ 10 | controllers: [BankAccountsController], 11 | providers: [BankAccountsService], 12 | }).compile(); 13 | 14 | controller = module.get(BankAccountsController); 15 | }); 16 | 17 | it('should be defined', () => { 18 | expect(controller).toBeDefined(); 19 | }); 20 | }); 21 | -------------------------------------------------------------------------------- /src/bank-accounts/bank-accounts.controller.ts: -------------------------------------------------------------------------------- 1 | import { Controller, Get, Post, Body, Param, HttpCode } from '@nestjs/common'; 2 | import { BankAccountService } from '../@core/domain/bank-account.service'; 3 | import { BankAccountsService } from './bank-accounts.service'; 4 | import { CreateBankAccountDto } from './dto/create-bank-account.dto'; 5 | import { TransferBankAccountDto } from './dto/transfer-bank-account.dto'; 6 | 7 | @Controller('bank-accounts') 8 | export class BankAccountsController { 9 | constructor( 10 | private readonly bankAccountsService: BankAccountsService, 11 | private bankAccountService: BankAccountService, 12 | ) {} 13 | 14 | @Post() 15 | create(@Body() createBankAccountDto: CreateBankAccountDto) { 16 | return this.bankAccountService.create(createBankAccountDto.account_number); 17 | } 18 | 19 | @Get() 20 | findAll() { 21 | return this.bankAccountsService.findAll(); 22 | } 23 | 24 | @Get(':id') 25 | findOne(@Param('id') id: string) { 26 | return this.bankAccountsService.findOne(id); 27 | } 28 | 29 | @HttpCode(204) 30 | @Post('transfer') 31 | transfer(@Body() transferDto: TransferBankAccountDto) { 32 | return this.bankAccountService.transfer( 33 | transferDto.from, 34 | transferDto.to, 35 | transferDto.amount, 36 | ); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/bank-accounts/bank-accounts.module.ts: -------------------------------------------------------------------------------- 1 | import { Module } from '@nestjs/common'; 2 | import { BankAccountsService } from './bank-accounts.service'; 3 | import { BankAccountsController } from './bank-accounts.controller'; 4 | import { getDataSourceToken, TypeOrmModule } from '@nestjs/typeorm'; 5 | import { BankAccountSchema } from '../@core/infra/db/bank-account.schema'; 6 | import { BankAccountService } from '../@core/domain/bank-account.service'; 7 | import { DataSource } from 'typeorm'; 8 | import { BankAccountTypeOrmRepository } from '../@core/infra/db/bank-account-typeorm.repository'; 9 | import { BankAccountRepository } from '../@core/domain/bank-account.repository'; 10 | 11 | @Module({ 12 | imports: [TypeOrmModule.forFeature([BankAccountSchema])], 13 | controllers: [BankAccountsController], 14 | providers: [ 15 | BankAccountsService, 16 | { 17 | provide: BankAccountTypeOrmRepository, 18 | useFactory: (dataSource: DataSource) => { 19 | return new BankAccountTypeOrmRepository( 20 | dataSource.getRepository(BankAccountSchema), 21 | ); 22 | }, 23 | inject: [getDataSourceToken()], 24 | }, 25 | { 26 | provide: BankAccountService, 27 | useFactory: (repo: BankAccountRepository) => { 28 | return new BankAccountService(repo); 29 | }, 30 | inject: [BankAccountTypeOrmRepository], 31 | }, 32 | ], 33 | }) 34 | export class BankAccountsModule {} 35 | -------------------------------------------------------------------------------- /src/bank-accounts/bank-accounts.service.spec.ts: -------------------------------------------------------------------------------- 1 | import { Test, TestingModule } from '@nestjs/testing'; 2 | import { BankAccountsService } from './bank-accounts.service'; 3 | 4 | describe('BankAccountsService', () => { 5 | let service: BankAccountsService; 6 | 7 | beforeEach(async () => { 8 | const module: TestingModule = await Test.createTestingModule({ 9 | providers: [BankAccountsService], 10 | }).compile(); 11 | 12 | service = module.get(BankAccountsService); 13 | }); 14 | 15 | it('should be defined', () => { 16 | expect(service).toBeDefined(); 17 | }); 18 | }); 19 | -------------------------------------------------------------------------------- /src/bank-accounts/bank-accounts.service.ts: -------------------------------------------------------------------------------- 1 | import { Inject, Injectable, Scope } from '@nestjs/common'; 2 | import { CreateBankAccountDto } from './dto/create-bank-account.dto'; 3 | import { Repository, DataSource } from 'typeorm'; 4 | import { BankAccountSchema } from '../@core/infra/db/bank-account.schema'; 5 | import { InjectRepository, getDataSourceToken } from '@nestjs/typeorm'; 6 | // Real Eval Print Loop 7 | @Injectable({ 8 | // scope: Scope.REQUEST, 9 | // durable: true, 10 | }) 11 | export class BankAccountsService { 12 | constructor( 13 | @InjectRepository(BankAccountSchema) 14 | private repo: Repository, 15 | @Inject(getDataSourceToken()) 16 | private dataSource: DataSource, 17 | ) {} 18 | 19 | async create(createBankAccountDto: CreateBankAccountDto) { 20 | const bankAccount = this.repo.create({ 21 | account_number: createBankAccountDto.account_number, 22 | balance: 0, 23 | }); 24 | 25 | await this.repo.insert(bankAccount); 26 | return bankAccount; 27 | } 28 | 29 | findAll() { 30 | return this.repo.find(); 31 | } 32 | 33 | findOne(id: string) { 34 | return this.repo.findOneBy({ id }); 35 | } 36 | 37 | async transfer(from: string, to: string, amount: number) { 38 | //modo transação 39 | const queryRunner = this.dataSource.createQueryRunner(); 40 | try { 41 | await queryRunner.startTransaction(); 42 | const fromAccount = await this.repo.findOneBy({ account_number: from }); 43 | const toAccount = await this.repo.findOneBy({ account_number: to }); 44 | 45 | fromAccount.balance -= amount; 46 | toAccount.balance += amount; 47 | 48 | this.repo.save(fromAccount); 49 | this.repo.save(toAccount); 50 | await queryRunner.commitTransaction(); 51 | } catch (e) { 52 | await queryRunner.rollbackTransaction(); 53 | console.error(e); 54 | throw e; 55 | } 56 | } 57 | } 58 | 59 | // repl 60 | // ### durable providers - nested container 61 | // facilitar a criação de módulos personalizados 62 | 63 | //scope request -> request -> motivo ID do mini container 64 | 65 | // tenant - inquilino 66 | 67 | // conta azul - tenant - empresa 68 | 69 | //SaaS -------------------------------------------------------------------------------- /src/bank-accounts/dto/create-bank-account.dto.ts: -------------------------------------------------------------------------------- 1 | export class CreateBankAccountDto { 2 | account_number: string; 3 | } 4 | -------------------------------------------------------------------------------- /src/bank-accounts/dto/transfer-bank-account.dto.ts: -------------------------------------------------------------------------------- 1 | export class TransferBankAccountDto { 2 | from: string; 3 | to: string; 4 | amount: number; 5 | } 6 | -------------------------------------------------------------------------------- /src/main.ts: -------------------------------------------------------------------------------- 1 | import { NestFactory } from '@nestjs/core'; 2 | import { AppModule } from './app.module'; 3 | 4 | async function bootstrap() { 5 | const app = await NestFactory.create(AppModule); 6 | await app.listen(3000); 7 | } 8 | bootstrap(); 9 | -------------------------------------------------------------------------------- /src/repl.ts: -------------------------------------------------------------------------------- 1 | import { repl } from '@nestjs/core'; 2 | import { AppModule } from './app.module'; 3 | 4 | async function bootstrap() { 5 | await repl(AppModule); 6 | } 7 | bootstrap(); 8 | -------------------------------------------------------------------------------- /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 | "strictNullChecks": false, 16 | "noImplicitAny": false, 17 | "strictBindCallApply": false, 18 | "forceConsistentCasingInFileNames": false, 19 | "noFallthroughCasesInSwitch": false 20 | }, 21 | "include": [ 22 | "src" 23 | ] 24 | } 25 | --------------------------------------------------------------------------------