If you work with and you have many replicated codes for different data models or create ) at all times, then this post is for you! Node.js /Javascript CRUDs (Create, Read, Update and Delete Generic Repository Pattern Working with applications, we have some problems to share similar code between the application, and in many times we create the same code for different applications. That pattern gives to you a power to write an abstraction of data, when we have one abstract class (or many classes) and reuse the implementations independent of your Data Model, passing only your types to someone classes. Javascript Talking about the , it is a representation where you can keep all operations of your database (like a Create, Read, Update and Delete Operations) in one local per Business Entity, when you need to do operations with Database, don’t call directly database drivers and if you have more one database, or differently databases to one transaction, you application only calls the method of repository and is transparently for who calls. Repository pattern Therefore, the is similar but now you have only one abstraction, one Base Class which have all common operations and your only extends the base class with all implementations of database operations. Following the principles, that pattern follows the , when your is open for extension, but closed for modification. Generic Repository EntityRepository SOLID Open / Closed principle baseClass When to use a Generic Repository ? Depends on your Business Model, and critical level of your applications. My opinion about this pattern it’s about the extensibility and enabling you to create only one class to write all common operations, such , when all of your application should have a or similar operations. CRUDs Entities CRUD When don’t use Generic Repository ? The same way that you have a power, you have dangerous implicit codes, an clean example for that is: You have two Entity Classes: and People Account. Users can remove People. Users can’t update information about (like add more money to account) Account If both classes extends from , that haves and methods_,_ the programmer should remember of that rule and not expose or methods to service, or your business case is wrong and dangerous. BaseClass update() remove() remove update Thinking About Generics with Typescript Components that are capable of working on the data of today as well as the data of tomorrow will give you the most flexible capabilities for building up large software systems — typescriptlang.org/docs/handbook/generics.html Following the Typescript's documentation, generics gives the power to build flexible and generic components (or types). From their docs, we have a better example about how it works: One method that receives one number argument and returns your argument So, we have a , which receives one number and returns the same type. If you want pass one string to this method you need to create another method with the same implementation and repeat your code. concrete method With the Implementation, we have the aleatory word to says what is the generic implementation (for convention, uses to say that is a generic type) Generics T Same method, refactored to Generic implementation Creating a real project with Generic Repository and Node.js Lets go! If you don’t understated yet, with the next section you’ll be able be to get the idea. Requirements: Node.js 8+ Typescript 2.6.2+ + MongoDB 3.6 VSCode Testing your environment After install all environment requirements, test in your terminal if it is all ok. npm --v && node --version Output of commands to view Node.js version and npm versions To verify if your MongoDB is fine, run on another terminal tab, sudo mongod MongoDB Instance Starting Then, in another tab run to enter em your database. mongo Entering em MongoDB database Then, install the global package , to compile your typescript projects. Run typescript npm install -g typescript Output of typescript globally package installed Once you’re done with that, we are ready to move forward :D Now, we need to create one folder and initializate a project. Node.js mkdir warriors-projectcd warriors-pŕojectnpm init -y #to init nodejs app without wizardtsc --init #to init config file to typescript After that, should open the within your project folder. To create our project, you need create some folders for better organization of our application. We are going to use the folder structure bellow: vscode .├── entities├── package.json├── repositories│ ├── base│ └── interfaces└── tsconfig.json Entering in file, in the section of property modify the value to “es2015” , we alter that property of a , to work with modules, like in Typescript. Alter the property to to generate files in a separated folder. tsconfig.json "lib": [] "lib": [ ] json file es2015 Promises outDir “outDir”: “lib” .js About our folders, when folder is about your data models, folder is about our database operations and our operations' contracts. Now, we should create our entities, in folder, create a file with the following code: entities repositories interfaces entities Spartan.ts Entity Classe of a Spartan Now, on folder, we'll create two files, following the these files will have our contracts that the abstract classes must be. Our contracts, should follow the generic pattern, that can be written without a fixed type, but, when anyone implements this interfaces, should pass the type for them. repositories/interfaces single responsability, IWrite Generic Interface with our manipulation methods operations IRead Generic Interface with our read methods operations After creating our interface, we should create the , an abstract class that implements all generic interfaces and has our common implementation for all entities. In folder, create a with following code BaseClass base BaseRepository.ts Creating BaseRepository with Interfaces imported After you importing the interfaces you need to implements the signature of your interfaces, for that, you can press to show options of to show options to fix problems and click in “ to add all implementations. ctrl . vscode Implements Interface IWrite<T> (Fix all in file)” After open options and select fix all in files Now we have a class similar to code bellow Our code after fix all interface errors We should now create the implementations for all methods. Our class, should know how is the database and collection that you can access. At this point, you need to install the for that, return to your terminal on project folder and runs to add driver and typescript definition of package. BaseRepository mongodb driver package, npm i -S mongodb @types/mongodb mongodb In we add two arguments, and . Your class implementation should like a following code constructor, db collectionName Now, we created the file to specific entity in folder_._ Repository repositories Now, to test our repository and all logic event. We need in root of project, create a file, that call all repositories. Index.ts Implementation of main code of our application You need to transpile your to files, running the command from terminal, you have now in folder all and now, you can run your application with Typescript Javascript tsc lib javascript files node lib/Index.js. To you see the power of , we go to create more one repository for with name and one , that represents a . Generic Repositories Heroes HeroesRepository.ts entity class Hero Entity Created to represents a Hero Implementation of HeroRepository without specific operations Now, we just call that repository in our following the complete code below. Index.ts, Complete implementation Conclusion With one class, we have many implementations to use and to work more easily, for me, the feature in is one of most powerful features to work. All the code that you see here is available in the GitHub repo that you can find in the links section below, don’t forget to check it out :D Generics TypeScript If you got up to this point, don’t forget to comment, share with your friends and leave some feedback. Please be mindful that this is my first English post so feel free to correct me with some private notes if you happen to spot any error :D Don’t forget too, to click and claps on post. Links https://github.com/ErickWendel/generic-repository-nodejs-typescript-article https://erickwendel.com.br fb.com/page.erickwendel http://deviq.com/repository-pattern/ http://hannesdorfmann.com/android/evolution-of-the-repository-pattern https://www.pluralsight.com/courses/domain-driven-design-fundamentals https://en.wikipedia.org/wiki/Open/closed_principle https://en.wikipedia.org/wiki/SOLID_(object-oriented_design) https://medium.com/@cramirez92/s-o-l-i-d-the-first-5-priciples-of-object-oriented-design-with-javascript-790f6ac9b9fa https://www.typescriptlang.org/docs/handbook/generics.html See ya 🤘
Share Your Thoughts