├── .dockerignore ├── .eslintignore ├── .eslintrc.js ├── .gitignore ├── .prettierrc.json ├── .vscode └── settings.json ├── Dockerfile ├── LICENSE ├── README.md ├── docker-compose.dev.yaml ├── docker-compose.yaml ├── jest.config.js ├── package-lock.json ├── package.json ├── src ├── @types │ └── superagent.d.ts ├── configuration │ └── index.ts ├── data │ ├── database │ │ ├── entities │ │ │ └── user.ts │ │ └── index.ts │ └── users │ │ └── userRepository.ts ├── domain │ └── users │ │ ├── user.ts │ │ ├── userRepository.ts │ │ └── usersService.ts ├── http │ ├── app.ts │ ├── routes │ │ ├── error.ts │ │ ├── user.test.ts │ │ └── user.ts │ └── utils │ │ └── asyncWrapper.ts ├── libs │ └── logger │ │ └── index.ts ├── server.ts └── signals │ └── index.ts └── tsconfig.json /.dockerignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | 5 | # Runtime data 6 | pids 7 | *.pid 8 | *.seed 9 | 10 | # Coverage directory used by tools like istanbul 11 | coverage/ 12 | 13 | # Compiled binary addons (http://nodejs.org/api/addons.html) 14 | dist/ 15 | 16 | # Dependency directory 17 | node_modules/ 18 | 19 | # Source Control 20 | .git/ 21 | .gitignore 22 | 23 | # Docker 24 | .dockerignore 25 | Dockerfile 26 | 27 | # Environment 28 | .env 29 | 30 | # Linter config 31 | .eslintrc 32 | 33 | # Editor config 34 | vscode/ -------------------------------------------------------------------------------- /.eslintignore: -------------------------------------------------------------------------------- 1 | node_modules/** 2 | dist/** 3 | -------------------------------------------------------------------------------- /.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | parser: '@typescript-eslint/parser', 3 | extends: [ 4 | 'airbnb-base', 5 | 'plugin:@typescript-eslint/recommended', 6 | 'plugin:jest/recommended', 7 | 'plugin:prettier/recommended', 8 | ], 9 | parserOptions: { 10 | ecmaVersion: 2018, 11 | sourceType: 'module', 12 | tsconfigRootDir: './', 13 | }, 14 | rules: { 15 | '@typescript-eslint/no-empty-interface': 'off', 16 | '@typescript-eslint/interface-name-prefix': 'off', 17 | '@typescript-eslint/explicit-function-return-type': 'off', 18 | '@typescript-eslint/no-explicit-any': 'off', 19 | 'import/prefer-default-export': 'off', 20 | 'no-useless-constructor': 'off', 21 | 'no-underscore-dangle': 'off', 22 | 'import/extensions': 'off', 23 | }, 24 | settings: { 25 | 'import/resolver': { 26 | node: { 27 | extensions: ['.js', '.jsx', '.ts', '.tsx'], 28 | }, 29 | }, 30 | }, 31 | }; 32 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | 8 | # dist folder 9 | dist/ 10 | 11 | # Runtime data 12 | pids 13 | *.pid 14 | *.seed 15 | *.pid.lock 16 | 17 | # Directory for instrumented libs generated by jscoverage/JSCover 18 | lib-cov 19 | 20 | # Coverage directory used by tools like istanbul 21 | coverage 22 | 23 | # nyc test coverage 24 | .nyc_output 25 | 26 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 27 | .grunt 28 | 29 | # Bower dependency directory (https://bower.io/) 30 | bower_components 31 | 32 | # node-waf configuration 33 | .lock-wscript 34 | 35 | # Compiled binary addons (https://nodejs.org/api/addons.html) 36 | build/Release 37 | 38 | # Dependency directories 39 | node_modules/ 40 | jspm_packages/ 41 | 42 | # Typescript v1 declaration files 43 | typings/ 44 | 45 | # Optional npm cache directory 46 | .npm 47 | 48 | # Optional eslint cache 49 | .eslintcache 50 | 51 | # Optional REPL history 52 | .node_repl_history 53 | 54 | # Output of 'npm pack' 55 | *.tgz 56 | 57 | # Yarn Integrity file 58 | .yarn-integrity 59 | 60 | # dotenv environment variables file 61 | .env -------------------------------------------------------------------------------- /.prettierrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "singleQuote": true, 3 | "trailingComma": "all" 4 | } 5 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "javascript.validate.enable": false 3 | } -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM node:carbon-alpine as builder 2 | 3 | RUN mkdir -p /build 4 | 5 | COPY ./package.json ./package-lock.json /build/ 6 | WORKDIR /build 7 | RUN npm ci 8 | 9 | # Bundle app source 10 | COPY . /build 11 | 12 | # Build app for production 13 | RUN npm run build 14 | 15 | FROM node:carbon-alpine 16 | # user with username node is provided from the official node image 17 | ENV user node 18 | # Run the image as a non-root user 19 | USER $user 20 | 21 | # Create app directory 22 | RUN mkdir -p /home/$user/src 23 | WORKDIR /home/$user/src 24 | 25 | COPY --from=builder /build ./ 26 | 27 | EXPOSE 3000 28 | 29 | ENV NODE_ENV production 30 | 31 | CMD ["node", "./dist/server.js"] -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # What is this repository for? 2 | 3 | Node.js app architecture showcase in Typescript. You can start your Node.js projects building on this boilerplate. 4 | 5 | For the old js version look at the branch [javascript](https://github.com/akoufatzis/nodejs-app-architecture/tree/javascript) 6 | 7 | # Architecture Overview 8 | 9 | The app is designed to use a layered architecture. The architecture is heavily influenced by the Clean Architecture. The code style being used is based on the [airbnb js style guide](https://github.com/airbnb/javascript) 10 | 11 | ## Data Layer 12 | 13 | The data layer is implemented using repositories, that hide the underlying data sources (database, network, cache, etc), and provides an abstraction over them so other parts of the application that make use of the repositories, don't care about the origin of the data and are decoupled from the specific implementations used, like Mongoose ORM (MongoDb) that is used by this app. 14 | Furthermore, the repositories are responsible to map the entities they fetch from the data sources to the models used in the applications. This is important to enable the decoupling. 15 | 16 | ## Domain Layer 17 | 18 | The domain layer is implemented using services. They depend on the repository interfaces to get the app models and apply the business rules on them. They are not coupled to a specific database implementation and can be reused if we add more data sources to the app or even if we change the database for example from Postgres to MongoDB. 19 | 20 | ## Routes/Controller Layer 21 | 22 | This layer is being used in the express app and depends on the domain layer (services). Here we define the routes that can be called from outside. The services are always used as the last middleware on the routes and we must not rely on res.locals from express to get data from previous middlewares. That means that the middlewares registered before should not alter data being passed to the domain layer. They are only allowed to act upon the data without modification, like for example validating the data and skipping calling `next()`. 23 | 24 | ## Entry point 25 | 26 | The entry point for the applications is the [server.ts](./src/server.ts) file. It does **not** depend on express.js or other node.js frameworks. It is responsible for instantiating the application layers, connecting to the db, mounting the http server to the specified port and handling the signals for graceful shutdown. 27 | 28 | # Quick start 29 | 30 | #### Use Docker: 31 | 32 | You can use Docker to start the app locally. The [Dockerfile](./Dockerfile) and the [docker-compose.yaml](./docker-compose.yaml) are already provided for you. 33 | 34 | 35 | Run the following command: 36 | 37 | - `docker-compose up` 38 | 39 | #### Use the npm scripts: 40 | 41 | 42 | Setup development environment with docker: 43 | 44 | - `npm run start:dev.env` to start the development environment (mongo database). 45 | 46 | Run the service 47 | 48 | - `npm run dev` for starting the service using ts-node-dev to auto restart the server on changes. 49 | 50 | # Build app 51 | 52 | - `npm run build` to build the project. 53 | - `npm start` to start the server. 54 | 55 | ## Packages and Tools 56 | 57 | - [Node v10+](http://nodejs.org/) 58 | - [TypeScript](https://github.com/Microsoft/TypeScript) 59 | - [Express](https://npmjs.com/package/express) 60 | - [ts-node](https://github.com/TypeStrong/ts-node) 61 | - [Prettier](https://github.com/prettier/prettier) 62 | - [Jest](https://github.com/facebook/jest) 63 | - [ESLint](https://github.com/eslint/eslint) 64 | - [Supertest](https://github.com/visionmedia/supertest) 65 | 66 | ## License 67 | 68 | ``` 69 | Copyright 2020 Alexandros Koufatzis. 70 | 71 | Licensed under the Apache License, Version 2.0 (the "License"); 72 | you may not use this file except in compliance with the License. 73 | You may obtain a copy of the License at 74 | 75 | http://www.apache.org/licenses/LICENSE-2.0 76 | 77 | Unless required by applicable law or agreed to in writing, software 78 | distributed under the License is distributed on an "AS IS" BASIS, 79 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 80 | See the License for the specific language governing permissions and 81 | limitations under the License. 82 | ``` 83 | -------------------------------------------------------------------------------- /docker-compose.dev.yaml: -------------------------------------------------------------------------------- 1 | version: '3.3' 2 | services: 3 | db: 4 | image: mongo:latest 5 | ports: 6 | - '27017:27017' 7 | env_file: .env 8 | -------------------------------------------------------------------------------- /docker-compose.yaml: -------------------------------------------------------------------------------- 1 | version: '3.3' 2 | services: 3 | web: 4 | build: . 5 | ports: 6 | - '3000:3000' 7 | env_file: .env 8 | environment: 9 | - DATABASE_CONNECTION_STRING=mongodb://db:27017/nodejsapparch 10 | depends_on: 11 | - db 12 | volumes: 13 | - .:/home/nodejs/src 14 | db: 15 | image: mongo:latest 16 | ports: 17 | - '27017:27017' 18 | env_file: .env 19 | -------------------------------------------------------------------------------- /jest.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | roots: ['./'], 3 | transform: { 4 | '^.+\\.tsx?$': 'ts-jest', 5 | }, 6 | testRegex: 'test\\.tsx?$', 7 | moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'], 8 | globals: { 9 | 'ts-jest': { 10 | // 'enableTsDiagnostics': true 11 | }, 12 | }, 13 | testURL: 'http://localhost', 14 | }; 15 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "node-architecture-boilerplate", 3 | "version": "0.3.0", 4 | "description": "A node boilerplate project showcasing an architecture approach", 5 | "main": "./src/server.ts", 6 | "scripts": { 7 | "dev": "ts-node-dev --no-notify --respawn --transpileOnly src/server.ts", 8 | "start:dev-env": "docker-compose -f docker-compose.dev.yaml up -d", 9 | "stop:dev-env": "docker-compose -f docker-compose.dev.yaml down", 10 | "start": "NODE_ENV=production node dist/server.js", 11 | "build": "tsc", 12 | "tsc": "tsc", 13 | "prettier": "prettier --list-different './src/**/*.ts'", 14 | "clean": "rimraf dist", 15 | "test": "jest", 16 | "lint": "eslint src --ext .ts" 17 | }, 18 | "lint-staged": { 19 | "src/**/*.js": [ 20 | "npm run lint", 21 | "prettier --write", 22 | "git add" 23 | ] 24 | }, 25 | "husky": { 26 | "hooks": { 27 | "pre-commit": "npm run build && lint-staged", 28 | "pre-push": "npm t" 29 | } 30 | }, 31 | "author": "Alex Koufatzis", 32 | "license": "Apache-2.0", 33 | "dependencies": { 34 | "body-parser": "^1.19.0", 35 | "dotenv": "^8.2.0", 36 | "express": "4.17.1", 37 | "mongoose": "^5.8.9" 38 | }, 39 | "devDependencies": { 40 | "@types/body-parser": "^1.17.0", 41 | "@types/dotenv": "^8.2.0", 42 | "@types/express": "^4.17.2", 43 | "@types/jest": "^24.9.1", 44 | "@types/mongoose": "^5.5.43", 45 | "@types/node": "^10.11.4", 46 | "@types/supertest": "^2.0.8", 47 | "@typescript-eslint/eslint-plugin": "^2.17.0", 48 | "@typescript-eslint/parser": "^2.17.0", 49 | "eslint": "^6.1.0", 50 | "eslint-config-airbnb-base": "^14.0.0", 51 | "eslint-config-prettier": "^6.9.0", 52 | "eslint-plugin-import": "^2.20.0", 53 | "eslint-plugin-jest": "^23.6.0", 54 | "eslint-plugin-prettier": "^3.1.1", 55 | "husky": "4.2.1", 56 | "jest": "^25.1.0", 57 | "lint-staged": "^10.0.2", 58 | "prettier": "^1.19.1", 59 | "rimraf": "^3.0.0", 60 | "supertest": "^4.0.2", 61 | "ts-jest": "^25.0.0", 62 | "ts-node-dev": "^1.0.0-pre.44", 63 | "typescript": "^3.7.5" 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /src/@types/superagent.d.ts: -------------------------------------------------------------------------------- 1 | // error TS2304: Cannot find name 'XMLHttpRequest' 2 | declare interface XMLHttpRequest {} 3 | // error TS2304: Cannot find name 'Blob' 4 | declare interface Blob {} 5 | -------------------------------------------------------------------------------- /src/configuration/index.ts: -------------------------------------------------------------------------------- 1 | import dotenv from 'dotenv'; 2 | 3 | dotenv.config(); 4 | 5 | /** 6 | * This module is used to collect all the configuration variables, 7 | * like the environment vars, in one place so they are not scattered all over the whole codebase 8 | */ 9 | export const config = { 10 | connectionString: process.env.DATABASE_CONNECTION_STRING, 11 | port: process.env.PORT || 3000, 12 | }; 13 | -------------------------------------------------------------------------------- /src/data/database/entities/user.ts: -------------------------------------------------------------------------------- 1 | import mongoose from 'mongoose'; 2 | import { User } from '../../../domain/users/user'; 3 | 4 | export interface IDocumentUser extends mongoose.Document { 5 | firstName: string; 6 | lastName: string; 7 | age: number; 8 | } 9 | export interface UserEntity extends IDocumentUser { 10 | toUser(): User; 11 | } 12 | 13 | export const UserSchema = new mongoose.Schema({ 14 | firstName: { type: String, required: true }, 15 | lastName: { type: String, required: true }, 16 | age: Number, 17 | }); 18 | 19 | UserSchema.methods.toUser = function toUser(): User { 20 | const name = `${this.firstName} ${this.lastName}`; 21 | return { 22 | name, 23 | age: this.age, 24 | id: this._id, 25 | }; 26 | }; 27 | 28 | export const UserDao = mongoose.model('User', UserSchema); 29 | -------------------------------------------------------------------------------- /src/data/database/index.ts: -------------------------------------------------------------------------------- 1 | import mongoose from 'mongoose'; 2 | 3 | export class Database { 4 | mongo?: mongoose.Mongoose; 5 | 6 | constructor(private readonly connectionString: string) {} 7 | 8 | async connect() { 9 | this.mongo = await mongoose.connect(this.connectionString, { 10 | useNewUrlParser: true, 11 | useUnifiedTopology: true, 12 | }); 13 | } 14 | 15 | async disconnect() { 16 | if (this.mongo) { 17 | await this.mongo.disconnect(); 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/data/users/userRepository.ts: -------------------------------------------------------------------------------- 1 | import { UserEntity, UserDao } from '../database/entities/user'; 2 | import { User } from '../../domain/users/user'; 3 | import { UserRepository } from '../../domain/users/userRepository'; 4 | 5 | // DATA LAYER 6 | // UserRepository: 7 | // is used to provide an abstraction on top of the database ( and possible other data sources) 8 | // so other parts of the application are decoupled from the specific database implementation. 9 | // Furthermore it can hide the origin of the data from it's consumers. 10 | // It is possible to fetch the entities from different sources like inmemory cache, 11 | // network or the db without the need to alter the consumers code. 12 | 13 | export function createUserRepository(): UserRepository { 14 | async function getAll(): Promise { 15 | const users: UserEntity[] = await UserDao.find(); 16 | return users.map((userEntity: UserEntity) => userEntity.toUser()); 17 | } 18 | 19 | async function add( 20 | firstName: string, 21 | lastName: string, 22 | age: number, 23 | ): Promise { 24 | let userModel = new UserDao({ firstName, lastName, age }); 25 | userModel = await userModel.save(); 26 | return userModel.toUser(); 27 | } 28 | 29 | return { 30 | getAll, 31 | add, 32 | }; 33 | } 34 | -------------------------------------------------------------------------------- /src/domain/users/user.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This is the app Model it is decoupled from 3 | * the Entities used for the databse 4 | */ 5 | export interface User { 6 | id: string; 7 | name: string; 8 | age: number; 9 | } 10 | -------------------------------------------------------------------------------- /src/domain/users/userRepository.ts: -------------------------------------------------------------------------------- 1 | import { User } from './user'; 2 | 3 | export interface UserRepository { 4 | getAll(): Promise; 5 | add(firstName: string, lastName: string, age: number): Promise; 6 | } 7 | -------------------------------------------------------------------------------- /src/domain/users/usersService.ts: -------------------------------------------------------------------------------- 1 | import { User } from './user'; 2 | import { UserRepository } from './userRepository'; 3 | 4 | // DOMAIN LAYER 5 | // Has the userRepository as a dependency. The UserService does not know 6 | // nor does it care where the user models came from. This is abstracted away 7 | // by the implementation of the repositories. It just calls the needed repositories 8 | // gets the results and usually applies some business logic on them. 9 | 10 | export class UsersService { 11 | constructor(private readonly userRepository: UserRepository) {} 12 | 13 | async getAllUsers() { 14 | const users = await this.userRepository.getAll(); 15 | return users; 16 | } 17 | 18 | async createUser( 19 | firstName: string, 20 | lastName: string, 21 | age: number, 22 | ): Promise { 23 | // TODO: catch possible errors here and rethrow a custom error you defined instead 24 | return this.userRepository.add(firstName, lastName, age); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/http/app.ts: -------------------------------------------------------------------------------- 1 | import express from 'express'; 2 | import bodyParser from 'body-parser'; 3 | import { UsersService } from '../domain/users/usersService'; 4 | import { errorHandler } from './routes/error'; 5 | import { userRoute } from './routes/user'; 6 | 7 | const app = express(); 8 | app.use(bodyParser.json()); 9 | 10 | export const appFactory = (userService: UsersService) => { 11 | const user = userRoute(userService); 12 | app.use('/users', user); 13 | app.use(errorHandler); 14 | return app; 15 | }; 16 | -------------------------------------------------------------------------------- /src/http/routes/error.ts: -------------------------------------------------------------------------------- 1 | import { Request, Response, NextFunction } from 'express'; 2 | 3 | // TODO: Implement error handling here returning the right status code and message for the errors 4 | // TODO: Error details for errors with status code 500 should not be shared 5 | // with the callers of the app as this could be a security risk 6 | 7 | // TODO: Log the errors 8 | 9 | export function errorHandler( 10 | err: Error, 11 | _req: Request, 12 | res: Response, 13 | // eslint-disable-next-line @typescript-eslint/no-unused-vars 14 | _next: NextFunction, 15 | ) { 16 | res.status(500); 17 | res.json({ error: err.message, status: 500 }); 18 | } 19 | -------------------------------------------------------------------------------- /src/http/routes/user.test.ts: -------------------------------------------------------------------------------- 1 | // eslint-disable-next-line import/no-extraneous-dependencies 2 | import request from 'supertest'; 3 | import { appFactory } from '../app'; 4 | import { UsersService } from '../../domain/users/usersService'; 5 | 6 | const userData = [ 7 | { name: 'Alex', age: 30 }, 8 | { name: 'Aris', age: 29 }, 9 | { name: 'Pantelis', age: 40 }, 10 | ]; 11 | 12 | const mockUserRepository = { 13 | getAll: jest.fn(), 14 | add: jest.fn(), 15 | }; 16 | 17 | const userService = new UsersService(mockUserRepository); 18 | 19 | const app = appFactory(userService); 20 | 21 | describe('user route test', () => { 22 | describe('GET /users test', () => { 23 | beforeEach(() => { 24 | mockUserRepository.getAll.mockClear(); 25 | mockUserRepository.add.mockClear(); 26 | }); 27 | 28 | it('should return 200 an array of users', async () => { 29 | mockUserRepository.getAll.mockResolvedValue(userData); 30 | 31 | const { body: users } = await request(app) 32 | .get('/users') 33 | .expect(200); 34 | 35 | expect(users).toEqual(userData); 36 | }); 37 | 38 | it('should return 500 when the service rejects with an error', () => { 39 | const dbError = new Error('Database error'); 40 | mockUserRepository.getAll.mockRejectedValue(dbError); 41 | return request(app) 42 | .get('/users') 43 | .expect(500) 44 | .catch(error => { 45 | expect(error).toEqual(dbError); 46 | }); 47 | }); 48 | }); 49 | }); 50 | -------------------------------------------------------------------------------- /src/http/routes/user.ts: -------------------------------------------------------------------------------- 1 | import express, { Request, Response } from 'express'; 2 | import { asyncWrapper } from '../utils/asyncWrapper'; 3 | import { UsersService } from '../../domain/users/usersService'; 4 | 5 | const router = express.Router(); 6 | 7 | export function userRoute(userService: UsersService) { 8 | router.get( 9 | '/', 10 | asyncWrapper(async (_: Request, res: Response) => { 11 | const users = await userService.getAllUsers(); 12 | res.json(users); 13 | }), 14 | ); 15 | 16 | // TODO: Install middleware to validate the input 17 | router.post( 18 | '/', 19 | asyncWrapper(async (req: Request, res: Response) => { 20 | const { firstName, lastName, age } = req.body; 21 | const user = await userService.createUser(firstName, lastName, age); 22 | res.json(user); 23 | }), 24 | ); 25 | 26 | return router; 27 | } 28 | -------------------------------------------------------------------------------- /src/http/utils/asyncWrapper.ts: -------------------------------------------------------------------------------- 1 | import { Request, Response, NextFunction } from 'express'; 2 | /** 3 | * 4 | * @param {function} fn 5 | */ 6 | export function asyncWrapper(fn: (req: Request, res: Response) => any) { 7 | return async ( 8 | req: Request, 9 | res: Response, 10 | next: NextFunction, 11 | ): Promise => { 12 | try { 13 | await fn(req, res); 14 | return; 15 | } catch (err) { 16 | next(err); 17 | } 18 | }; 19 | } 20 | -------------------------------------------------------------------------------- /src/libs/logger/index.ts: -------------------------------------------------------------------------------- 1 | // TODO: Replace console with a more complete logger library like bunyan, winston 2 | // TODO: return an interface and not the logger directly 3 | export const logger = { 4 | log(...args: any[]): void { 5 | // eslint-disable-next-line no-console 6 | console.log(...args); 7 | }, 8 | error(...args: any[]): void { 9 | // eslint-disable-next-line no-console 10 | console.error(...args); 11 | }, 12 | info(...args: any[]): void { 13 | // eslint-disable-next-line no-console 14 | console.info(...args); 15 | }, 16 | }; 17 | -------------------------------------------------------------------------------- /src/server.ts: -------------------------------------------------------------------------------- 1 | import { config } from './configuration'; 2 | import { appFactory } from './http/app'; 3 | import { logger } from './libs/logger'; 4 | import { createUserRepository } from './data/users/userRepository'; 5 | import { UsersService } from './domain/users/usersService'; 6 | import { init } from './signals'; 7 | import { Database } from './data/database'; 8 | 9 | const database = new Database(config.connectionString as string); 10 | database.connect(); 11 | const userRepository = createUserRepository(); 12 | const userService = new UsersService(userRepository); 13 | 14 | const app = appFactory(userService); 15 | 16 | const server = app.listen(config.port, () => { 17 | logger.info(`Listening on *:${config.port}`); 18 | }); 19 | 20 | const shutdown = init(() => { 21 | server.close(async () => { 22 | await database.disconnect(); 23 | }); 24 | }); 25 | 26 | process.on('SIGINT', shutdown); 27 | process.on('SIGTERM', shutdown); 28 | -------------------------------------------------------------------------------- /src/signals/index.ts: -------------------------------------------------------------------------------- 1 | import process from 'process'; 2 | 3 | export const init = (closeFunc: () => any) => async () => { 4 | try { 5 | await closeFunc(); 6 | process.exit(0); 7 | } catch (err) { 8 | process.exit(1); 9 | } 10 | }; 11 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "es2017", 4 | "module": "commonjs", 5 | "strict": true, 6 | "declaration": true, 7 | "noUnusedLocals": true, 8 | "noUnusedParameters": true, 9 | "moduleResolution": "node", 10 | "sourceMap": true, 11 | "outDir": "./dist", 12 | "types": ["node", "jest"], 13 | "lib": ["es2017"], 14 | "esModuleInterop": true 15 | }, 16 | "include": ["./src/**/*.ts"], 17 | "exclude": ["node_modules", "dist"] 18 | } 19 | --------------------------------------------------------------------------------