ts-repository-pattern
v1.0.8
Published
A reusable repository pattern with TypeScript and Typegoose
Downloads
117
Readme
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
Install the
ts-repository-pattern
package:npm install ts-repository-pattern
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: '[email protected]' });
};
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: '[email protected]' });
// 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: '[email protected]' });
// Delete a user by email
await userRepo.deleteOne({ email: '[email protected]' });
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
inUserRepository
). - 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.