ebook img

Nest.js- A Progressive Node.js Framework PDF

313 Pages·2020·2.724 MB·English
Save to my drive
Quick download
Download
Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.

Preview Nest.js- A Progressive Node.js Framework

Table of Contents Preface .............................................................................................................................. 8 What is Nest.js? ................................................................................................................ 8 About the example ........................................................................................................... 9 About the authors .......................................................................................................... 10 Chapter 1. Introduction ................................................................................................. 11 Topics discussed ............................................................................................................. 12 Nest CLI ......................................................................................................................... 12 Dependency Injection ..................................................................................................... 13 Authentication ................................................................................................................ 14 ORM .............................................................................................................................. 15 REST API ...................................................................................................................... 16 WebSockets .................................................................................................................... 16 Microservices ................................................................................................................. 17 GraphQL ....................................................................................................................... 17 Routing ........................................................................................................................... 17 Nest specific tools ........................................................................................................... 18 OpenAPI (Swagger) ....................................................................................................... 19 Command Query Responsibility Segregation (CQRS) .................................................. 19 Testing ............................................................................................................................ 19 Server-side rendering with Angular Universal .............................................................. 20 Summary ........................................................................................................................ 20 Chapter 2. Overview ...................................................................................................... 22 Controllers ..................................................................................................................... 22 Providers ........................................................................................................................ 22 Modules .......................................................................................................................... 23 Bootstrapping ................................................................................................................. 24 Middleware .................................................................................................................... 25 Guards ........................................................................................................................... 27 Summary ........................................................................................................................ 28 Chapter 3. Nest.js authentication .................................................................................... 30 Passport .......................................................................................................................... 30 Manual implementation ................................................................................................. 31 Implementation ..................................................................................................................... 31 AUTHENTICATION MODULE .......................................................................................... 31 USER MODULE ..................................................................................................................... 36 APP MODULE ........................................................................................................................ 42 Authentication middleware ................................................................................................. 44 Managing restrictions with guards ................................................................................... 44 Nest.js passport package ................................................................................................ 45 Summary ........................................................................................................................ 48 Chapter 4. Dependency Injection system of Nest.js ......................................................... 49 Overview of Dependency Injection ................................................................................ 49 Why use Dependency Injection ......................................................................................... 50 How it works without Dependency Injection ................................................................... 50 How it works with a manual Dependency Injection ........................................................ 51 Dependency Injection pattern today ................................................................................. 52 Nest.js Dependency Injection ......................................................................................... 53 The difference between Nest.js and Angular DI ............................................................ 57 Summary ........................................................................................................................ 57 Chapter 5. TypeORM ....................................................................................................... 59 What database to use ..................................................................................................... 59 About MariaDB ..................................................................................................................... 60 Getting started ............................................................................................................... 60 Start the database ................................................................................................................ 61 Connect to the database ..................................................................................................... 62 Initialize TypeORM ............................................................................................................... 63 Modelling our data ......................................................................................................... 63 Our first entity ....................................................................................................................... 63 Using our models ............................................................................................................ 65 The service ............................................................................................................................ 65 The controller ....................................................................................................................... 67 Building a new module ........................................................................................................ 67 Improving our models .................................................................................................... 70 Auto-generated IDs .............................................................................................................. 71 When was the entry created? ............................................................................................. 72 Column types ........................................................................................................................ 74 COLUMN TYPES FOR MYSQL / MARIADB .................................................................. 74 COLUMN TYPES FOR POSTGRES ................................................................................. 75 COLUMN TYPES FOR SQLITE / CORDOVA / REACT-NATIVE ............................ 75 COLUMN TYPES FOR MSSQL ......................................................................................... 75 COLUMN TYPES FOR ORACLE ...................................................................................... 75 NoSQL in SQL ....................................................................................................................... 75 Relationships between data models ................................................................................ 76 How to store related entities .............................................................................................. 80 SAVING RELATED ENTITIES THE EASIER WAY ................................................. 82 Retrieving related entities in bulk ...................................................................................... 84 Lazy relationships ................................................................................................................ 86 Other kinds of relationships ........................................................................................... 88 One-to-one ............................................................................................................................ 88 BI-DIRECTIONAL ONE-TO-ONE RELATIONSHIPS .............................................. 90 Many-to-many ....................................................................................................................... 92 Advanced TypeORM ..................................................................................................... 92 Security first .......................................................................................................................... 92 Other listeners ...................................................................................................................... 93 Composing and extending entities ................................................................................... 93 EMBEDDED ENTITIES ....................................................................................................... 94 ENTITY INHERITANCE ...................................................................................................... 96 Caching .................................................................................................................................. 97 Building a query ................................................................................................................... 99 Building our model from a existing database ............................................................... 100 Summary ...................................................................................................................... 100 Chapter 6. Sequelize ...................................................................................................... 102 Configure Sequelize ..................................................................................................... 102 Create a model ............................................................................................................. 105 @Table ................................................................................................................................. 105 @column ............................................................................................................................. 106 Create the User model ....................................................................................................... 107 LifeCycle hooks .................................................................................................................. 109 Injecting a model into a service .................................................................................... 110 Usage of Sequelize transaction ..................................................................................... 111 Migration ..................................................................................................................... 112 Configuring the migration script ..................................................................................... 113 Create a migration .............................................................................................................. 114 Summary ...................................................................................................................... 114 Chapter 7. Mongoose .................................................................................................... 116 A word about MongoDB .............................................................................................. 116 A word about Mongoose .............................................................................................. 116 Mongoose and Nest.js ....................................................................................................... 117 Getting started ............................................................................................................. 117 Set up the database ........................................................................................................... 117 Start the containers ........................................................................................................... 118 Connect to the database ................................................................................................... 118 THE CONNECTION STRING ......................................................................................... 119 THE RIGHT ARGUMENT FOR THE FORROOT() METHOD ............................... 120 Modelling our data ....................................................................................................... 120 Our first schema ................................................................................................................. 120 INCLUDING THE SCHEMA INTO THE MODULE .................................................. 122 INCLUDE THE NEW MODULE INTO THE MAIN MODULE ............................... 122 Using the schema .......................................................................................................... 123 The interface ....................................................................................................................... 123 The service .......................................................................................................................... 124 The controller ..................................................................................................................... 125 The first requests ......................................................................................................... 126 Relationships ................................................................................................................ 127 Modelling relationships ..................................................................................................... 128 Saving relationships .......................................................................................................... 129 Reading relationships ....................................................................................................... 131 Summary ...................................................................................................................... 133 Chapter 8. Web sockets ................................................................................................ 134 WebSocketGateway ..................................................................................................... 134 Gateways ...................................................................................................................... 135 Authentication .............................................................................................................. 137 Adapter ........................................................................................................................ 138 Client side ..................................................................................................................... 141 Summary ...................................................................................................................... 144 Chapter 9. Microservices ............................................................................................. 145 Server bootstrap ........................................................................................................... 145 Configuration ............................................................................................................... 146 First microservice handler ........................................................................................... 146 Sending data ................................................................................................................. 147 Exception filters ........................................................................................................... 149 Pipes ............................................................................................................................. 151 Guards ......................................................................................................................... 152 Interceptors .................................................................................................................. 154 Built-in transports ........................................................................................................ 155 Redis .................................................................................................................................... 155 MQTT .................................................................................................................................... 157 NATS .................................................................................................................................... 158 gRPC .................................................................................................................................... 160 Custom transport ......................................................................................................... 165 Hybrid application ....................................................................................................... 172 Advanced architecture design ...................................................................................... 173 Summary ...................................................................................................................... 175 Chapter 10. Routing and request handling in Nest.js ..................................................... 177 Request handlers .......................................................................................................... 177 Generating responses ................................................................................................... 178 Standard approach ............................................................................................................ 178 Express approach .............................................................................................................. 179 Route parameters ......................................................................................................... 179 Request body ................................................................................................................ 180 Request object .............................................................................................................. 180 Asynchronous handlers ................................................................................................ 181 Async/await ......................................................................................................................... 181 Promise ................................................................................................................................ 182 Observables ........................................................................................................................ 182 Error responses ............................................................................................................ 183 HttpException ..................................................................................................................... 183 Unrecognized exceptions ................................................................................................. 184 Summary ...................................................................................................................... 184 Chapter 11. OpenAPI (Swagger) Specification ................................................................ 186 Document Settings ....................................................................................................... 187 Documenting authentication ............................................................................................ 188 Swagger UI ................................................................................................................... 190 API input decorators .................................................................................................... 192 @Body ................................................................................................................................. 196 @Param ............................................................................................................................... 200 @Query ................................................................................................................................ 203 @Headers ............................................................................................................................ 206 Authentication .................................................................................................................... 210 API request and response decorators .......................................................................... 213 API metadata decorators ............................................................................................. 219 Saving the swagger document ...................................................................................... 225 Summary ...................................................................................................................... 225 Chapter 12. Command Query Responsibility Separation (CQRS) .................................... 227 Entry module commands ............................................................................................. 228 Command handlers ........................................................................................................... 229 Invoking command handlers ............................................................................................ 234 Linking keywords with events ...................................................................................... 239 Keyword events .................................................................................................................. 249 Invoking event handlers .................................................................................................... 253 Retrieving keywords APIs ........................................................................................... 258 Linking keywords with sagas ....................................................................................... 262 Keyword saga commands ................................................................................................ 262 Keyword saga ..................................................................................................................... 266 Summary ...................................................................................................................... 270 Chapter 13. Architecture ............................................................................................... 272 Style guide of naming conventions ............................................................................... 272 Controller ............................................................................................................................. 272 Service ................................................................................................................................. 272 Module ................................................................................................................................. 273 Middleware .......................................................................................................................... 273 Exception filter ................................................................................................................... 273 Pipe ....................................................................................................................................... 273 Guard ................................................................................................................................... 273 Interceptor ........................................................................................................................... 274 Custom decorator .............................................................................................................. 274 Gateway ............................................................................................................................... 274 Adapter ................................................................................................................................ 274 Unit test ............................................................................................................................... 275 E2E test ................................................................................................................................ 275 Directory structure ...................................................................................................... 275 Server architecture ............................................................................................................ 275 COMPLETE OVERVIEW .................................................................................................. 275 THE SRC DIRECTORY ...................................................................................................... 276 Angular Universal architecture ........................................................................................ 282 THE SRC DIRECTORY ...................................................................................................... 282 Summary ...................................................................................................................... 284 Chapter 14. Testing ....................................................................................................... 285 Unit testing ................................................................................................................... 285 Tooling ................................................................................................................................. 286 Preparation .......................................................................................................................... 286 Writing our first test ........................................................................................................... 288 Testing for equality ............................................................................................................ 294 Covering our code in tests ............................................................................................... 296 FAILING TESTS FOR LOW COVERAGE ................................................................. 298 E2E testing ................................................................................................................... 301 Preparation .......................................................................................................................... 301 Writing end-to-end tests ................................................................................................... 302 Summary ...................................................................................................................... 303 Chapter 15. Server-side Rendering with Angular Universal ....................................... 305 Serving the Angular Universal App with Nest.js ......................................................... 306 Building and running the Universal App ..................................................................... 312 Summary ...................................................................................................................... 313 Preface What is Nest.js? There are so many available web frameworks, and with the advent of Node.js, even more have been released. JavaScript frameworks go in and out of style very quickly as web technologies change and grow. Nest.js is a good starting point for many developers that are looking to use a modern web framework because it uses a language that is very similar to that of the most used language on the web to this day, JavaScript. Many developers were taught programming using languages such as Java or C/C++, which are both strict languages, so using JavaScript can be a little awkward and easy to make mistakes given the lack of type safety. Nest.js uses TypeScript, which is a happy medium. It is a language that provides the simplicity and power of JavaScript with the type safety of other languages you may be used to. The type safety in Nest.js is only available at compile time, because the Nest.js server is compiled to a Node.js Express server that runs JavaScript. This is still a major advantage, however, since it allows you to better design programs error free prior to runtime. Node.js has a rich ecosystem of packages in NPM (Node Package Manager). With over 350,000 packages, it’s the world’s largest package registry. With Nest.js making use of Express, you have access to each and every one of these packages when developing Nest applications. Many even have type definitions for their packages that allow IDE’s to read the package and make suggestions/auto fill in code that may not be possible when crossing JavaScript code with TypeScript code. One of the largest benefits of Node.js is the huge repository of modules that are available to pull from instead of having to write your own. Nest.js includes some of these modules already as part of the Nest platform, like , which uses the NPM library . Prior to @nestjs/mongoose mongoose 2009, JavaScript was mainly a front-end language, but after the release of Node.js in 2009, it spurred the development of many JavaScript and TypeScript projects like: Angular, React, and Vue, among others. Angular was a heavy inspiration for the development of Nest.js because both use a Module/Component system that allows for reusability. If you are not familiar with Angular, it is a TypeScript-based front-end framework that can be used cross-platform to develop responsive web apps and native apps, and it functions a lot like Nest does. The two also pair very well together with Nest providing the ability to run a Universal server to serve pre-rendered Angular web pages to speed up website delivering times using Server-Side Rendering (SSR) mentioned above. About the example This book will reference a working Nest.js project that is hosted on GitHub at (https://github.com/backstopmedia/nest-book-example). Throughout the book, code snippets and chapters will reference parts of the code so that you can see a working example of what you are learning about. The example Git repository can be cloned within your command prompt. git clone https://github.com/backstopmedia/nest-book- example.git This will create a local copy of the project on your computer, which you can run locally by building the project with Docker: docker-compose up Once your Docker container is up and running on port localhost:3000, you will want to run the migration before doing anything else. To do this run: docker ps To get the ID of your running Docker container: docker exec -it [ID] npm run migrate up This will run the database migrations so that your Nest.js app can read and write to the database with the correct schema. If you don’t want to use Docker, or cannot use Docker, you can build the project with your choice of package managers such as or : npm yarn npm install or yarn This installs the dependencies in your folder. Then run: node_modules npm start:dev Or the following to start your Nest.js server: yarn start:dev These will run , which will cause your Nest.js application to restart if nodemon any changes are made, saving you from having to stop, rebuild, and start your application again. About the authors • Greg Magolan is a Senior Architect, Full-Stack Engineer, and Angular Consultant at Rangle.io. He has been developing enterprise software solutions for over 15 years working for companies suchas Agilent Technologies, Electronic Arts, Avigilon, Energy Transfer Partners, FunnelEnvy, Yodel andACM Facility Safety. • Jay Bell is the CTO of Trellis. He is a Senior Angular developer that uses Nest.js in production to develop industry leading software to help non-profits and charities in Canada. He is a serial entrepreneur that has developed software in a large range of industries from helping combat wildfires with drones to building mobile apps. • David Guijarro is a Front-End Developer at Car2go Group GmbH. He has a wide experience working within the JavaScript ecosystem. He has successfully built and led multi-cultural, multi- functional teams. • Adrien de Peretti is a Full-Stack JavaScript Developer. He is passionate about new technologies and is constantly looking for new challenges, and is especially interested in the field of Artificial Intelligence and Robotics. When he is not front of his computer, Adrien is in nature and playing different sports. • Patrick Housley is a Lead Technologist at VML. He is an IT professional with over six years of experience in the technology industry and is capable of analyzing complex issues spanning multiple technologies while providing detailed resolutions and explanations. He has strong front-end development skills with experience leading development teams in maintenance and greenfield projects.

See more

The list of books you might like

Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.