├── .vscode └── settings.json ├── .prettierrc ├── .env ├── tsconfig.build.json ├── src ├── data │ └── constants.ts ├── app.service.ts ├── countries │ ├── entities │ │ └── country.entity.ts │ ├── dto │ │ ├── create-country.dto.ts │ │ └── update-country.dto.ts │ ├── models │ │ └── country.model.ts │ ├── repositories │ │ ├── countries.repository.interface.ts │ │ ├── implementations │ │ │ ├── countries.in-memory.repository.ts │ │ │ └── countries.typeorm.repository.ts │ │ └── countries.repository.provider.ts │ ├── countries.service.spec.ts │ ├── countries.module.ts │ ├── countries.controller.spec.ts │ ├── countries.service.ts │ └── countries.controller.ts ├── main.ts ├── app.controller.ts ├── app.controller.spec.ts └── app.module.ts ├── nest-cli.json ├── test ├── jest-e2e.json └── app.e2e-spec.ts ├── .gitignore ├── tsconfig.json ├── .eslintrc.js ├── README.md └── package.json /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "prettier.printWidth": 120 3 | } 4 | -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "singleQuote": true, 3 | "trailingComma": "all" 4 | } -------------------------------------------------------------------------------- /.env: -------------------------------------------------------------------------------- 1 | # This file should not be committed but we leave it for didactic purposes 2 | COUNTRIES_DATASOURCE=typeorm -------------------------------------------------------------------------------- /tsconfig.build.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./tsconfig.json", 3 | "exclude": ["node_modules", "test", "dist", "**/*spec.ts"] 4 | } 5 | -------------------------------------------------------------------------------- /src/data/constants.ts: -------------------------------------------------------------------------------- 1 | export enum DataSource { 2 | TYPEORM = 'typeorm', 3 | MEMORY = 'memory', 4 | REDIS = 'redis', 5 | POSTGRES = 'postgres', 6 | } 7 | -------------------------------------------------------------------------------- /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/countries/entities/country.entity.ts: -------------------------------------------------------------------------------- 1 | export class Country { 2 | constructor( 3 | public id: string, 4 | public name: string, 5 | public areaInKms: number, 6 | ) {} 7 | } 8 | -------------------------------------------------------------------------------- /src/countries/dto/create-country.dto.ts: -------------------------------------------------------------------------------- 1 | export class CreateCountryDto { 2 | constructor( 3 | public id: string, 4 | public name: string, 5 | public areaInKms: number, 6 | ) {} 7 | } 8 | -------------------------------------------------------------------------------- /nest-cli.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://json.schemastore.org/nest-cli", 3 | "collection": "@nestjs/schematics", 4 | "sourceRoot": "src", 5 | "compilerOptions": { 6 | "deleteOutDir": true 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/countries/dto/update-country.dto.ts: -------------------------------------------------------------------------------- 1 | import { PartialType } from '@nestjs/mapped-types'; 2 | import { CreateCountryDto } from './create-country.dto'; 3 | 4 | export class UpdateCountryDto extends PartialType(CreateCountryDto) {} 5 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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/countries/models/country.model.ts: -------------------------------------------------------------------------------- 1 | import { Column, Entity, PrimaryColumn } from 'typeorm'; 2 | 3 | @Entity() 4 | export class Country { 5 | @PrimaryColumn() 6 | public id: string; 7 | 8 | @Column() 9 | public name: string; 10 | 11 | @Column() 12 | public areaInKms: number; 13 | } 14 | -------------------------------------------------------------------------------- /src/countries/repositories/countries.repository.interface.ts: -------------------------------------------------------------------------------- 1 | import { Country } from '../entities/country.entity'; 2 | 3 | export interface CountriesRepository { 4 | create(country: Country): Promise; 5 | findAll(): Promise; 6 | } 7 | 8 | export const COUNTRIES_REPOSITORY_TOKEN = 'countries-repository-token'; 9 | -------------------------------------------------------------------------------- /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/countries/repositories/implementations/countries.in-memory.repository.ts: -------------------------------------------------------------------------------- 1 | import { Country } from '../../entities/country.entity'; 2 | import { CountriesRepository } from '../countries.repository.interface'; 3 | 4 | export class CountriesInMemoryRepository implements CountriesRepository { 5 | private countries: Country[] = []; 6 | 7 | async create(country: Country) { 8 | this.countries.push(country); 9 | return country; 10 | } 11 | 12 | async findAll() { 13 | return this.countries; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # env variables 2 | # .env 3 | 4 | # compiled output 5 | /dist 6 | /node_modules 7 | 8 | # Logs 9 | logs 10 | *.log 11 | npm-debug.log* 12 | pnpm-debug.log* 13 | yarn-debug.log* 14 | yarn-error.log* 15 | lerna-debug.log* 16 | 17 | # OS 18 | .DS_Store 19 | 20 | # Tests 21 | /coverage 22 | /.nyc_output 23 | 24 | # IDEs and editors 25 | /.idea 26 | .project 27 | .classpath 28 | .c9/ 29 | *.launch 30 | .settings/ 31 | *.sublime-workspace 32 | 33 | # IDE - VSCode 34 | .vscode/* 35 | !.vscode/settings.json 36 | !.vscode/tasks.json 37 | !.vscode/launch.json 38 | !.vscode/extensions.json -------------------------------------------------------------------------------- /src/countries/countries.service.spec.ts: -------------------------------------------------------------------------------- 1 | import { Test, TestingModule } from '@nestjs/testing'; 2 | import { CountriesService } from './countries.service'; 3 | 4 | describe('CountriesService', () => { 5 | let service: CountriesService; 6 | 7 | beforeEach(async () => { 8 | const module: TestingModule = await Test.createTestingModule({ 9 | providers: [CountriesService], 10 | }).compile(); 11 | 12 | service = module.get(CountriesService); 13 | }); 14 | 15 | it('should be defined', () => { 16 | expect(service).toBeDefined(); 17 | }); 18 | }); 19 | -------------------------------------------------------------------------------- /src/countries/countries.module.ts: -------------------------------------------------------------------------------- 1 | import { Module } from '@nestjs/common'; 2 | import { CountriesService } from './countries.service'; 3 | import { CountriesController } from './countries.controller'; 4 | import { TypeOrmModule } from '@nestjs/typeorm'; 5 | import { Country } from './models/country.model'; 6 | import { provideCountriesRepository } from './repositories/countries.repository.provider'; 7 | 8 | @Module({ 9 | imports: [TypeOrmModule.forFeature([Country])], 10 | controllers: [CountriesController], 11 | providers: [CountriesService, ...provideCountriesRepository()], 12 | }) 13 | export class CountriesModule {} 14 | -------------------------------------------------------------------------------- /src/countries/repositories/implementations/countries.typeorm.repository.ts: -------------------------------------------------------------------------------- 1 | import { Country } from '../../models/country.model'; 2 | import { CountriesRepository } from '../countries.repository.interface'; 3 | import { Repository } from 'typeorm'; 4 | 5 | export class CountriesTypeOrmRepository implements CountriesRepository { 6 | constructor(private countriesRepository: Repository) {} 7 | 8 | async create(country: Country) { 9 | await this.countriesRepository.insert(country); 10 | return country; 11 | } 12 | 13 | async findAll() { 14 | return this.countriesRepository.find(); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /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 | "strict": true 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/countries/countries.controller.spec.ts: -------------------------------------------------------------------------------- 1 | import { Test, TestingModule } from '@nestjs/testing'; 2 | import { CountriesController } from './countries.controller'; 3 | import { CountriesService } from './countries.service'; 4 | 5 | describe('CountriesController', () => { 6 | let controller: CountriesController; 7 | 8 | beforeEach(async () => { 9 | const module: TestingModule = await Test.createTestingModule({ 10 | controllers: [CountriesController], 11 | providers: [CountriesService], 12 | }).compile(); 13 | 14 | controller = module.get(CountriesController); 15 | }); 16 | 17 | it('should be defined', () => { 18 | expect(controller).toBeDefined(); 19 | }); 20 | }); 21 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /.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 | -------------------------------------------------------------------------------- /src/app.module.ts: -------------------------------------------------------------------------------- 1 | import { Module } from '@nestjs/common'; 2 | import { ConfigModule } from '@nestjs/config'; 3 | import { TypeOrmModule } from '@nestjs/typeorm'; 4 | import { AppController } from './app.controller'; 5 | import { AppService } from './app.service'; 6 | import { CountriesModule } from './countries/countries.module'; 7 | import { Country } from './countries/models/country.model'; 8 | 9 | @Module({ 10 | imports: [ 11 | CountriesModule, 12 | ConfigModule.forRoot(), 13 | TypeOrmModule.forRoot({ 14 | type: 'postgres', 15 | host: 'localhost', 16 | port: 5432, 17 | username: 'postgres', 18 | password: 'postgres', 19 | database: 'postgres', 20 | entities: [Country], 21 | synchronize: true, 22 | }), 23 | ], 24 | controllers: [AppController], 25 | providers: [AppService], 26 | }) 27 | export class AppModule {} 28 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Example Repo for the Blogpost: Implementing data source agnostic services with NestJS 2 | 3 | 📝 **[Read the full blogpost on the Trilon website](https://trilon.io/blog/implementing-data-source-agnostic-services-with-nestjs)** 4 | 5 | --- 6 | 7 |
8 |

9 | 10 | Trilon.io - Angular Universal, NestJS, JavaScript Application Consulting Development and Training 11 | 12 |

13 | 14 |

Made with :heart: by Trilon.io

15 | 16 | --- 17 | 18 | ## Trilon - Fullstack Consulting | Training | Development 19 | 20 | Official NestJS consulting & support 🐈 21 | 22 | - Check out **[Trilon.io](https://Trilon.io)** for more info! 23 | - Contact us at , and let's talk about your projects needs. 24 | - Twitter: [@Trilon_io](http://twitter.com/Trilon_io) 25 | -------------------------------------------------------------------------------- /src/countries/countries.service.ts: -------------------------------------------------------------------------------- 1 | import { Inject, Injectable } from '@nestjs/common'; 2 | import { CreateCountryDto } from './dto/create-country.dto'; 3 | import { UpdateCountryDto } from './dto/update-country.dto'; 4 | import { 5 | CountriesRepository, 6 | COUNTRIES_REPOSITORY_TOKEN, 7 | } from './repositories/countries.repository.interface'; 8 | 9 | @Injectable() 10 | export class CountriesService { 11 | constructor( 12 | @Inject(COUNTRIES_REPOSITORY_TOKEN) 13 | private countriesRepository: CountriesRepository, 14 | ) {} 15 | 16 | create(countryDto: CreateCountryDto) { 17 | return this.countriesRepository.create(countryDto); 18 | } 19 | 20 | findAll() { 21 | return this.countriesRepository.findAll(); 22 | } 23 | 24 | findOne(id: string) { 25 | return `This action returns a #${id} country`; 26 | } 27 | 28 | update(id: string, updateCountryDto: UpdateCountryDto) { 29 | return `This action updates a #${id} country`; 30 | } 31 | 32 | remove(id: string) { 33 | return `This action removes a #${id} country`; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/countries/countries.controller.ts: -------------------------------------------------------------------------------- 1 | import { 2 | Controller, 3 | Get, 4 | Post, 5 | Body, 6 | Patch, 7 | Param, 8 | Delete, 9 | } from '@nestjs/common'; 10 | import { CountriesService } from './countries.service'; 11 | import { CreateCountryDto } from './dto/create-country.dto'; 12 | import { UpdateCountryDto } from './dto/update-country.dto'; 13 | 14 | @Controller('countries') 15 | export class CountriesController { 16 | constructor(private readonly countriesService: CountriesService) {} 17 | 18 | @Post() 19 | create(@Body() createCountryDto: CreateCountryDto) { 20 | return this.countriesService.create(createCountryDto); 21 | } 22 | 23 | @Get() 24 | findAll() { 25 | return this.countriesService.findAll(); 26 | } 27 | 28 | @Get(':id') 29 | findOne(@Param('id') id: string) { 30 | return this.countriesService.findOne(id); 31 | } 32 | 33 | @Patch(':id') 34 | update(@Param('id') id: string, @Body() updateCountryDto: UpdateCountryDto) { 35 | return this.countriesService.update(id, updateCountryDto); 36 | } 37 | 38 | @Delete(':id') 39 | remove(@Param('id') id: string) { 40 | return this.countriesService.remove(id); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/countries/repositories/countries.repository.provider.ts: -------------------------------------------------------------------------------- 1 | import { Injectable, Provider } from '@nestjs/common'; 2 | import { ConfigModule } from '@nestjs/config'; 3 | import { InjectRepository } from '@nestjs/typeorm'; 4 | import { DataSource } from '../../data/constants'; 5 | import { Repository } from 'typeorm'; 6 | import { Country } from '../models/country.model'; 7 | import { COUNTRIES_REPOSITORY_TOKEN } from './countries.repository.interface'; 8 | import { CountriesInMemoryRepository } from './implementations/countries.in-memory.repository'; 9 | import { CountriesTypeOrmRepository } from './implementations/countries.typeorm.repository'; 10 | 11 | export function provideCountriesRepository(): Provider[] { 12 | return [ 13 | { 14 | provide: COUNTRIES_REPOSITORY_TOKEN, 15 | useFactory: async ( 16 | dependenciesProvider: CountriesRepoDependenciesProvider, 17 | ) => provideCountriesRepositoryFactory(dependenciesProvider), 18 | inject: [CountriesRepoDependenciesProvider], 19 | }, 20 | CountriesRepoDependenciesProvider, 21 | ]; 22 | } 23 | 24 | async function provideCountriesRepositoryFactory( 25 | dependenciesProvider: CountriesRepoDependenciesProvider, 26 | ) { 27 | await ConfigModule.envVariablesLoaded; 28 | 29 | switch (process.env.COUNTRIES_DATASOURCE) { 30 | case DataSource.TYPEORM: 31 | return new CountriesTypeOrmRepository( 32 | dependenciesProvider.typeOrmRepository, 33 | ); 34 | case DataSource.MEMORY: 35 | default: 36 | return new CountriesInMemoryRepository(); 37 | } 38 | } 39 | 40 | @Injectable() 41 | export class CountriesRepoDependenciesProvider { 42 | constructor( 43 | @InjectRepository(Country) 44 | public typeOrmRepository: Repository, 45 | ) {} 46 | } 47 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "nest-db-agnostic", 3 | "version": "0.0.1", 4 | "description": "", 5 | "author": "", 6 | "private": true, 7 | "license": "UNLICENSED", 8 | "scripts": { 9 | "build": "nest build", 10 | "format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"", 11 | "start": "nest start", 12 | "start:dev": "nest start --watch", 13 | "start:debug": "nest start --debug --watch", 14 | "start:prod": "node dist/main", 15 | "lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix", 16 | "test": "jest", 17 | "test:watch": "jest --watch", 18 | "test:cov": "jest --coverage", 19 | "test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand", 20 | "test:e2e": "jest --config ./test/jest-e2e.json" 21 | }, 22 | "dependencies": { 23 | "@nestjs/common": "^9.0.0", 24 | "@nestjs/config": "^2.3.1", 25 | "@nestjs/core": "^9.0.0", 26 | "@nestjs/mapped-types": "*", 27 | "@nestjs/platform-express": "^9.0.0", 28 | "@nestjs/typeorm": "^9.0.1", 29 | "pg": "^8.10.0", 30 | "reflect-metadata": "^0.1.13", 31 | "rxjs": "^7.2.0", 32 | "typeorm": "^0.3.12" 33 | }, 34 | "devDependencies": { 35 | "@nestjs/cli": "^9.0.0", 36 | "@nestjs/schematics": "^9.0.0", 37 | "@nestjs/testing": "^9.0.0", 38 | "@types/express": "^4.17.13", 39 | "@types/jest": "29.2.4", 40 | "@types/node": "18.11.18", 41 | "@types/supertest": "^2.0.11", 42 | "@typescript-eslint/eslint-plugin": "^5.0.0", 43 | "@typescript-eslint/parser": "^5.0.0", 44 | "eslint": "^8.0.1", 45 | "eslint-config-prettier": "^8.3.0", 46 | "eslint-plugin-prettier": "^4.0.0", 47 | "jest": "29.3.1", 48 | "prettier": "^2.3.2", 49 | "source-map-support": "^0.5.20", 50 | "supertest": "^6.1.3", 51 | "ts-jest": "29.0.3", 52 | "ts-loader": "^9.2.3", 53 | "ts-node": "^10.0.0", 54 | "tsconfig-paths": "4.1.1", 55 | "typescript": "^4.7.4" 56 | }, 57 | "jest": { 58 | "moduleFileExtensions": [ 59 | "js", 60 | "json", 61 | "ts" 62 | ], 63 | "rootDir": "src", 64 | "testRegex": ".*\\.spec\\.ts$", 65 | "transform": { 66 | "^.+\\.(t|j)s$": "ts-jest" 67 | }, 68 | "collectCoverageFrom": [ 69 | "**/*.(t|j)s" 70 | ], 71 | "coverageDirectory": "../coverage", 72 | "testEnvironment": "node" 73 | } 74 | } 75 | --------------------------------------------------------------------------------