DEV Community

Cover image for Change the DB as you wish | Repository Pattern πŸ“¦
Ivan Zaldivar
Ivan Zaldivar

Posted on β€’ Edited on

23

Change the DB as you wish | Repository Pattern πŸ“¦

πŸ“¦ Repository Pattern

This is a practical and real-life example of how to use the Repository Pattern with Dependency Injection to manipulate with the database like a PRO. 😎

What is a Repository Pattern? πŸ€”

Repositories are classes or components that encapsulate the logic needed to access data sources. They centralize common data access functionality, providing better maintainability and decoupling the infrastructure or technology used to access databases. This allows us to change the Database used at any time, either from a MySQL to a MongoDB without further complexity.

Repository Patteern Diagram UML

As you have to visualize Repository corresponds to the interface, that is, the contract that the specific implementations have to fulfill. In this case MongoRepository, MySQLRepository, PostgreRepository.

Note: Whenever we want to add a new implementation (another database) we must implement this interface.

What is a Dependency Injection? πŸ’‰

Dependency Injection allows objects to be supplied to a class instead of the class itself creating those objects. These objects fulfill contracts (Interfaces) that our classes need in order to function.

Dependencies Injection

Define our interface.

// Define our interfaces/contract
interface Repository<T = any> {
  create(data: T, query?: Query): Promise<T>
  // Other methods...
}
Enter fullscreen mode Exit fullscreen mode

Define our implementations.

class MongoRepository implements Repository {
  async create(data: any, query?: Query): Promise<any> {
    // Do something...
  }
}

class MySQLRepository implements Repository {
  async create(data: any, query?: Query): Promise<any> {
    // Do something...
  }
}
Enter fullscreen mode Exit fullscreen mode

Define our client.

class Controller {
  constructor (repository: Repository) {}
}

// Using MongoDB πŸƒ
new Controller(new MongoRepository())

// Using MySQL 🐬
new Controller(new MySQLRepository())
Enter fullscreen mode Exit fullscreen mode

As you may have noticed, in this way we can change the database quite easily, since our Controller client does not depend on its specific implementations, but on a Repository interface.

Follow me ❀️

Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read more

Top comments (6)

Collapse
 
tempestrock profile image
Tempest Rock β€’

Thanks for the post. I think it is possible to use the repository pattern you suggest. But is it really a good idea to try to switch between relational databases and no-SQL DBs? IMHO, you are forced to reduce your interfaceβ€˜s capabilities to the least common denominator. No chance to use the great freedom of throwing documents at your interface as you could if you just had a no-SQL interface in mind. What about optimization/sharding, clustering, etc.?
Seems to be a more theoretical thing rather than a real-world requirement to switch between all kinds of DBs.

Collapse
 
ivanzm123 profile image
Ivan Zaldivar β€’

Thank you for the comments, bro. πŸ‘

The publication does not intend at any time to suggest such changes. What it intends is to minimize the dependencies that may exist in our projects. That instead of depending on concrete implementations, they depend on an abstraction (interface/contract)

Grettings. πŸ˜‰

Collapse
 
hilleer profile image
Daniel Hillmann β€’ β€’ Edited

thanks for the post! I do miss some example usages of you actually implement this in code.

Collapse
 
ivanzm123 profile image
Ivan Zaldivar β€’

Thanks, bro!

You can take a look at this example: github.com/TheBugWeb/todo-express-...

Collapse
 
erickgonzalez profile image
Erick β€’

We use this pattern at work for a microservice. It makes more sense now! Thanks

Collapse
 
asprazz profile image
Ankush Sudhakar Patil β€’

Thanks! I was always curious about this.

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay