Change the DB as you wish | Repository Pattern 📦

ivanzm123

Ivan Zaldivar

Posted on November 6, 2022

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 ❤️

💖 💪 🙅 🚩
ivanzm123
Ivan Zaldivar

Posted on November 6, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related