├── .env ├── .eslintrc.js ├── .gitignore ├── .nvmrc ├── .prettierrc ├── README.md ├── docker-compose.yml ├── nest-cli.json ├── package-lock.json ├── package.json ├── prisma ├── migrations │ ├── 20220918204951_redirects │ │ └── migration.sql │ └── migration_lock.toml └── schema.prisma ├── src ├── app.module.ts ├── main.ts └── modules │ ├── prisma │ └── prisma.service.ts │ └── redirects │ ├── adapters │ ├── api │ │ ├── dto │ │ │ ├── create-redirect.dto.ts │ │ │ └── redirect.dto.ts │ │ ├── links.controller.ts │ │ └── redirects.controller.ts │ └── repositories │ │ └── redirects.prisma-repository.ts │ ├── core │ ├── application │ │ ├── helpers │ │ │ └── generate-key.ts │ │ └── redirects.service.ts │ ├── model │ │ └── Redirect.entity.ts │ └── ports │ │ ├── redirects-repository.port.ts │ │ └── redirects.port.ts │ └── redirects.module.ts ├── test ├── app.e2e-spec.ts └── jest-e2e.json ├── tsconfig.build.json └── tsconfig.json /.env: -------------------------------------------------------------------------------- 1 | DATABASE_URL=postgresql://postgres:password@localhost:5432/link-shortener?schema=public&connect_timeout=300 -------------------------------------------------------------------------------- /.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 36 | 37 | redirects-database -------------------------------------------------------------------------------- /.nvmrc: -------------------------------------------------------------------------------- 1 | 16.17.0 -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "singleQuote": true, 3 | "trailingComma": "all" 4 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Example of implementation of Hexagonal Architecture in NestJS 2 | 3 | ## Requirements 4 | 5 | Before starting the project, please make sure that you have installed: 6 | 7 | - [Docker](https://www.docker.com) 8 | - [NVM](https://github.com/nvm-sh/nvm) 9 | 10 | ## Running the project 11 | 12 | 1. Open terminal and navigate to the project directory: 13 | 14 | ``` 15 | cd meetjs-nestjs-hexagonal 16 | ``` 17 | 18 | 2. Start the database (PostgreSQL): 19 | 20 | ``` 21 | docker-compose up 22 | ``` 23 | 24 | The database is listening on port 5432. 25 | 26 | 3. Use Node.js defined by NVM: 27 | 28 | ``` 29 | nvm use 30 | ``` 31 | 32 | It may happen that you don't have the required Node.js version. NVM will guide you to install it. 33 | 34 | 4. Install NPM packages: 35 | 36 | ``` 37 | npm install 38 | ``` 39 | 40 | 5. Run Prisma migrations: 41 | 42 | ``` 43 | npm run db:migrate 44 | ``` 45 | 46 | Having executed this command there should be `redirects` table in the database. 47 | 48 | 6. Start NestJS project: 49 | 50 | ``` 51 | npm run start 52 | ``` 53 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: '3.8' 2 | services: 3 | db: 4 | image: postgres:14.5-alpine 5 | ports: 6 | - '5432:5432' 7 | environment: 8 | # username: postgres 9 | POSTGRES_PASSWORD: password 10 | POSTGRES_DB: link-shortener 11 | volumes: 12 | - postgresql_data:/var/lib/postgresql/data 13 | 14 | volumes: 15 | postgresql_data: 16 | -------------------------------------------------------------------------------- /nest-cli.json: -------------------------------------------------------------------------------- 1 | { 2 | "collection": "@nestjs/schematics", 3 | "sourceRoot": "src" 4 | } 5 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "meetjs-nestjs-hexagonal", 3 | "version": "0.0.1", 4 | "description": "", 5 | "author": "Marcin Kwiatkowski ", 6 | "private": true, 7 | "license": "UNLICENSED", 8 | "scripts": { 9 | "db:migrate": "prisma migrate deploy", 10 | "db:migrate:create": "prisma migrate dev", 11 | "prebuild": "rimraf dist", 12 | "build": "nest build", 13 | "format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"", 14 | "start": "nest start", 15 | "start:dev": "nest start --watch", 16 | "start:debug": "nest start --debug --watch", 17 | "start:prod": "node dist/main", 18 | "lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix", 19 | "test": "jest", 20 | "test:watch": "jest --watch", 21 | "test:cov": "jest --coverage", 22 | "test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand", 23 | "test:e2e": "jest --config ./test/jest-e2e.json" 24 | }, 25 | "dependencies": { 26 | "@nestjs/common": "8.0.0", 27 | "@nestjs/core": "8.0.0", 28 | "@nestjs/platform-express": "8.0.0", 29 | "@prisma/client": "4.3.1", 30 | "nanoid": "3.3.4", 31 | "prisma": "4.3.1", 32 | "reflect-metadata": "0.1.13", 33 | "rimraf": "3.0.2", 34 | "rxjs": "7.2.0", 35 | "uuid": "9.0.0" 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": "27.4.1", 43 | "@types/node": "18.7.18", 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": "27.2.5", 51 | "prettier": "2.3.2", 52 | "source-map-support": "0.5.20", 53 | "supertest": "6.1.3", 54 | "ts-jest": "27.0.3", 55 | "ts-loader": "9.2.3", 56 | "ts-node": "10.9.1", 57 | "tsconfig-paths": "3.10.1", 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 | -------------------------------------------------------------------------------- /prisma/migrations/20220918204951_redirects/migration.sql: -------------------------------------------------------------------------------- 1 | -- CreateTable 2 | CREATE TABLE "redirects" ( 3 | "id" TEXT NOT NULL, 4 | "original_url" TEXT NOT NULL, 5 | "key" TEXT NOT NULL, 6 | "created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, 7 | 8 | CONSTRAINT "redirects_pkey" PRIMARY KEY ("id") 9 | ); 10 | 11 | -- CreateIndex 12 | CREATE UNIQUE INDEX "redirects_original_url_key" ON "redirects"("original_url"); 13 | 14 | -- CreateIndex 15 | CREATE UNIQUE INDEX "redirects_key_key" ON "redirects"("key"); 16 | -------------------------------------------------------------------------------- /prisma/migrations/migration_lock.toml: -------------------------------------------------------------------------------- 1 | # Please do not edit this file manually 2 | # It should be added in your version-control system (i.e. Git) 3 | provider = "postgresql" -------------------------------------------------------------------------------- /prisma/schema.prisma: -------------------------------------------------------------------------------- 1 | // This is your Prisma schema file, 2 | // learn more about it in the docs: https://pris.ly/d/prisma-schema 3 | 4 | generator client { 5 | provider = "prisma-client-js" 6 | } 7 | 8 | datasource db { 9 | provider = "postgresql" 10 | url = env("DATABASE_URL") 11 | } 12 | 13 | model Redirect { 14 | id String @id @default(cuid()) 15 | originalUrl String @map("original_url") @unique 16 | key String @unique 17 | createdAt DateTime @map("created_at") @db.Timestamptz @default(now()) 18 | 19 | @@map("redirects") 20 | } 21 | -------------------------------------------------------------------------------- /src/app.module.ts: -------------------------------------------------------------------------------- 1 | import { Module } from '@nestjs/common'; 2 | import { RedirectsModule } from './modules/redirects/redirects.module'; 3 | 4 | @Module({ 5 | imports: [RedirectsModule], 6 | }) 7 | export class AppModule {} 8 | -------------------------------------------------------------------------------- /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/modules/prisma/prisma.service.ts: -------------------------------------------------------------------------------- 1 | import { INestApplication, Injectable, OnModuleInit } from '@nestjs/common'; 2 | import { PrismaClient } from '@prisma/client'; 3 | 4 | @Injectable() 5 | export class PrismaService extends PrismaClient implements OnModuleInit { 6 | async onModuleInit(): Promise { 7 | await this.$connect(); 8 | } 9 | 10 | async enableShutdownHooks(app: INestApplication): Promise { 11 | this.$on('beforeExit', async () => { 12 | await app.close(); 13 | }); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/modules/redirects/adapters/api/dto/create-redirect.dto.ts: -------------------------------------------------------------------------------- 1 | export class CreateRedirectDto { 2 | readonly url!: string; 3 | } 4 | -------------------------------------------------------------------------------- /src/modules/redirects/adapters/api/dto/redirect.dto.ts: -------------------------------------------------------------------------------- 1 | import { RedirectEntity } from '../../../core/model/Redirect.entity'; 2 | 3 | export class RedirectDto { 4 | readonly shortUrl: string; 5 | 6 | constructor(shortUrl: string) { 7 | this.shortUrl = shortUrl; 8 | } 9 | 10 | static fromBusinessObject(redirect: RedirectEntity): RedirectDto { 11 | return new RedirectDto(redirect.shortUrl); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/modules/redirects/adapters/api/links.controller.ts: -------------------------------------------------------------------------------- 1 | import { Controller, Get, NotFoundException, Param, Res } from '@nestjs/common'; 2 | import { RedirectsPort } from '../../core/ports/redirects.port'; 3 | 4 | @Controller('/links') 5 | export class LinksController { 6 | constructor(private readonly redirectsService: RedirectsPort) {} 7 | 8 | @Get(':key') 9 | public async redirect( 10 | @Param('key') key: string, 11 | @Res() 12 | response: { redirect: (code: number, url: string) => Response }, 13 | ) { 14 | const existingRedirect = await this.redirectsService.findByKey(key); 15 | 16 | if (!existingRedirect) { 17 | throw new NotFoundException(); 18 | } 19 | 20 | return response.redirect(301, existingRedirect.originalUrl); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/modules/redirects/adapters/api/redirects.controller.ts: -------------------------------------------------------------------------------- 1 | import { Body, Controller, Post } from '@nestjs/common'; 2 | import { RedirectsPort } from '../../core/ports/redirects.port'; 3 | import { CreateRedirectDto } from './dto/create-redirect.dto'; 4 | import { RedirectDto } from './dto/redirect.dto'; 5 | 6 | @Controller('/redirects') 7 | export class RedirectsController { 8 | constructor(private readonly redirectsService: RedirectsPort) {} 9 | 10 | @Post() 11 | public async createRedirect( 12 | @Body() payload: CreateRedirectDto, 13 | ): Promise { 14 | const redirect = await this.redirectsService.findOrCreate(payload.url); 15 | return RedirectDto.fromBusinessObject(redirect); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/modules/redirects/adapters/repositories/redirects.prisma-repository.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@nestjs/common'; 2 | import { RedirectEntity } from '../../core/model/redirect.entity'; 3 | import { RedirectsRepositoryPort } from '../../core/ports/redirects-repository.port'; 4 | import { PrismaService } from '../../../prisma/prisma.service'; 5 | import { v4 as uuidv4 } from 'uuid'; 6 | 7 | @Injectable() 8 | export class RedirectsPrismaRepository extends RedirectsRepositoryPort { 9 | constructor(private readonly prisma: PrismaService) { 10 | super(); 11 | } 12 | 13 | async create(url: string, key: string): Promise { 14 | const dbRedirect = await this.prisma.redirect.create({ 15 | data: { 16 | id: uuidv4(), 17 | key: key, 18 | originalUrl: url, 19 | createdAt: new Date(), 20 | }, 21 | }); 22 | 23 | return new RedirectEntity( 24 | dbRedirect.id, 25 | dbRedirect.originalUrl, 26 | dbRedirect.key, 27 | this.buildShortLink(dbRedirect.key), 28 | dbRedirect.createdAt, 29 | ); 30 | } 31 | 32 | async findByOriginalUrl(url: string): Promise { 33 | const redirect = await this.prisma.redirect.findFirst({ 34 | where: { 35 | originalUrl: url, 36 | }, 37 | }); 38 | 39 | if (redirect === null) { 40 | return undefined; 41 | } 42 | 43 | return new RedirectEntity( 44 | redirect.id, 45 | redirect.originalUrl, 46 | this.buildShortLink(redirect.key), 47 | redirect.key, 48 | redirect.createdAt, 49 | ); 50 | } 51 | 52 | async findByKey(key: string): Promise { 53 | const redirect = await this.prisma.redirect.findFirst({ 54 | where: { 55 | key, 56 | }, 57 | }); 58 | 59 | if (redirect === null) { 60 | return undefined; 61 | } 62 | 63 | return new RedirectEntity( 64 | redirect.id, 65 | redirect.originalUrl, 66 | redirect.key, 67 | this.buildShortLink(redirect.key), 68 | redirect.createdAt, 69 | ); 70 | } 71 | 72 | private buildShortLink(key: string): string { 73 | return `http://localhost:3000/links/${key}`; 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /src/modules/redirects/core/application/helpers/generate-key.ts: -------------------------------------------------------------------------------- 1 | import { customAlphabet } from 'nanoid'; 2 | 3 | const alphabet = 4 | '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'; 5 | 6 | const nanoid = customAlphabet(alphabet, 10); 7 | 8 | export const generateKey = (): string => nanoid(); 9 | -------------------------------------------------------------------------------- /src/modules/redirects/core/application/redirects.service.ts: -------------------------------------------------------------------------------- 1 | import { RedirectsPort } from '../ports/redirects.port'; 2 | import { RedirectEntity } from '../model/Redirect.entity'; 3 | import { RedirectsRepositoryPort } from '../ports/redirects-repository.port'; 4 | import { generateKey } from './helpers/generate-key'; 5 | import { Injectable } from '@nestjs/common'; 6 | 7 | @Injectable() 8 | export class RedirectsService extends RedirectsPort { 9 | constructor(private readonly redirectRepository: RedirectsRepositoryPort) { 10 | super(); 11 | } 12 | 13 | async findOrCreate(url: string): Promise { 14 | const existingRedirect = await this.redirectRepository.findByOriginalUrl( 15 | url, 16 | ); 17 | 18 | if (existingRedirect !== undefined) { 19 | return existingRedirect; 20 | } 21 | 22 | // Generate a new key 23 | const key = generateKey(); 24 | 25 | return this.redirectRepository.create(url, key); 26 | } 27 | 28 | async findByKey(key: string): Promise { 29 | return this.redirectRepository.findByKey(key); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/modules/redirects/core/model/Redirect.entity.ts: -------------------------------------------------------------------------------- 1 | export class RedirectEntity { 2 | constructor( 3 | readonly id: string, 4 | readonly originalUrl: string, 5 | readonly key: string, 6 | readonly shortUrl: string, 7 | readonly createdAt: Date, 8 | ) {} 9 | } 10 | -------------------------------------------------------------------------------- /src/modules/redirects/core/ports/redirects-repository.port.ts: -------------------------------------------------------------------------------- 1 | import { RedirectEntity } from '../model/Redirect.entity'; 2 | 3 | export abstract class RedirectsRepositoryPort { 4 | public abstract create(url: string, key: string): Promise; 5 | public abstract findByOriginalUrl( 6 | url: string, 7 | ): Promise; 8 | public abstract findByKey(key: string): Promise; 9 | } 10 | -------------------------------------------------------------------------------- /src/modules/redirects/core/ports/redirects.port.ts: -------------------------------------------------------------------------------- 1 | import { RedirectEntity } from '../model/redirect.entity'; 2 | 3 | export abstract class RedirectsPort { 4 | public abstract findOrCreate(url: string): Promise; 5 | public abstract findByKey(url: string): Promise; 6 | } 7 | -------------------------------------------------------------------------------- /src/modules/redirects/redirects.module.ts: -------------------------------------------------------------------------------- 1 | import { Module } from '@nestjs/common'; 2 | import { RedirectsController } from './adapters/api/redirects.controller'; 3 | import { RedirectsPort } from './core/ports/redirects.port'; 4 | import { RedirectsService } from './core/application/redirects.service'; 5 | import { PrismaService } from '../prisma/prisma.service'; 6 | import { RedirectsRepositoryPort } from './core/ports/redirects-repository.port'; 7 | import { RedirectsPrismaRepository } from './adapters/repositories/redirects.prisma-repository'; 8 | import { LinksController } from './adapters/api/links.controller'; 9 | 10 | @Module({ 11 | controllers: [RedirectsController, LinksController], 12 | providers: [ 13 | { 14 | provide: RedirectsRepositoryPort, 15 | useClass: RedirectsPrismaRepository, 16 | }, 17 | { 18 | provide: RedirectsPort, 19 | useClass: RedirectsService, 20 | }, 21 | PrismaService, 22 | ], 23 | }) 24 | export class RedirectsModule {} 25 | -------------------------------------------------------------------------------- /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 | } 22 | --------------------------------------------------------------------------------