ts-repository-pattern
TypeScript icon, indicating that this package has built-in type declarations

1.0.8 • Public • Published

How to Use ts-repository-pattern

This guide will walk you through the steps to integrate and use the ts-repository-pattern package with Typegoose and MongoDB in your TypeScript project.

Installation

  1. Install the ts-repository-pattern package:

    npm install ts-repository-pattern
  2. Install the required dependencies (mongoose, @typegoose/typegoose):

    npm install mongoose @typegoose/typegoose

Project Setup

1. Create Your Typegoose Models

First, define your data model using Typegoose. For example, if you are working with a User model, define it as follows:

// src/entities/user.ts
import { prop } from '@typegoose/typegoose';

export class User {
    @prop({ required: true })
    public name!: string;

    @prop({ required: true })
    public email!: string;
}

2. Extend BaseRepository for Your Models

Next, create a repository class for your User model by extending the BaseRepository provided by ts-repository-pattern.

// src/repositories/user-repository.ts
import { getModelForClass } from '@typegoose/typegoose';
import { BaseRepository } from 'ts-repository-pattern';
import { User } from '../entities';

export class UserRepository extends BaseRepository<User> {
  constructor() {
    super(getModelForClass(User));
  }
}

3. Using the Repository

Now, you can use your UserRepository to perform database operations. Here is an example of how to use it in your application:

// src/app.ts
import { UserRepository } from './repositories/user-repository';

const main = async () => {
    // Connect to the database

    // Instantiate the repository
    const userRepo = new UserRepository();

    // Create a new user
    const newUser = await userRepo.create({ name: 'John Doe', email: 'john@example.com' });
};

main().catch((error) => console.error('Error:', error));

4. Available Methods in BaseRepository

Your BaseRepository class includes the following methods for common CRUD operations:

  • countDocument(query?: Partial<T>): Promise<number>: Count documents matching the query.
  • find(query: Partial<T>): Promise<T[]>: Find documents matching the query.
  • findOne(query: Partial<T>): Promise<T>: Find a document matching the query.
  • create(data: T): Promise<T>: Create a new document.
  • updateOne(query: Partial<T>, updateData: Partial<T>): Promise<boolean>: Update a document matching the query.
  • deleteOne(query: Partial<T>): Promise<boolean>: Delete documents matching the query.

Example usage:

// Create a new user
await userRepo.create({ name: 'Alice', email: 'alice@example.com' });

// Find all users with the name "Alice"
const users = await userRepo.find({ name: 'Alice' });

// Find one user with the id "1"
const users = await userRepo.findOne({ id: 1 });

// Count the number of users
const userCount = await userRepo.countDocument();

// Update a user's email
await userRepo.updateOne({ name: 'Alice' }, { email: 'alice@newmail.com' });

// Delete a user by email
await userRepo.deleteOne({ email: 'alice@example.com' });

Conclusion

By following these steps, you can easily implement a repository pattern for your MongoDB models using TypeScript and Typegoose. You can extend BaseRepository to add custom logic and methods for each model, making your codebase clean, reusable, and maintainable.

Additional Tips

  • You can create repositories for multiple models by extending BaseRepository.
  • Add custom methods in your repositories to handle model-specific operations (e.g., findByEmail in UserRepository).
  • Handle MongoDB connection and error handling properly when working with production environments.

License

This package is licensed under the MIT License. You are free to use, modify, and distribute it.

Package Sidebar

Install

npm i ts-repository-pattern

Weekly Downloads

7

Version

1.0.8

License

none

Unpacked Size

11.1 kB

Total Files

12

Last publish

Collaborators

  • kankosal
  • samnangapp