|
1 | | -# data_mongodb |
| 1 | +<div align="center"> |
| 2 | + <img src="https://avatars.githubusercontent.com/u/202675624?s=400&u=dc72a2b53e8158956a3b672f8e52e39394b6b610&v=4" alt="Flutter News App Toolkit Logo" width="220"> |
| 3 | + <h1>Data MongoDB</h1> |
| 4 | + <p><strong>A production-ready MongoDB implementation of the `DataClient` interface for the Flutter News App Toolkit.</strong></p> |
| 5 | +</div> |
2 | 6 |
|
3 | | - |
4 | | -[](https://pub.dev/packages/very_good_analysis) |
5 | | -[](https://polyformproject.org/licenses/free-trial/1.0.0) |
| 7 | +<p align="center"> |
| 8 | + <img src="https://img.shields.io/badge/coverage-89%25-green?style=for-the-badge" alt="coverage"> |
| 9 | + <a href="https://flutter-news-app-full-source-code.github.io/docs/"><img src="https://img.shields.io/badge/LIVE_DOCS-VIEW-slategray?style=for-the-badge" alt="Live Docs: View"></a> |
| 10 | + <a href="https://github.com/flutter-news-app-full-source-code"><img src="https://img.shields.io/badge/MAIN_PROJECT-BROWSE-purple?style=for-the-badge" alt="Main Project: Browse"></a> |
| 11 | +</p> |
6 | 12 |
|
7 | | -A production-ready MongoDB implementation of the `DataClient` interface, designed to connect Dart and Flutter applications to a MongoDB backend. This package is part of the [**Flutter News App - Full Source Code Toolkit**](https://github.com/flutter-news-app-full-source-code). |
| 13 | +This `data_mongodb` package provides a robust, concrete implementation of the `DataClient` interface within the [**Flutter News App Full Source Code Toolkit**](https://github.com/flutter-news-app-full-source-code). It acts as the bridge between your application's repositories and a MongoDB database, translating abstract data requests into native, efficient MongoDB queries. This package is designed for backend services (like a Dart Frog API) or applications that connect directly to MongoDB, ensuring consistent and scalable data persistence. |
8 | 14 |
|
9 | | -## Description |
| 15 | +## ⭐ Feature Showcase: Powerful MongoDB Integration |
10 | 16 |
|
11 | | -`DataMongodb` provides a robust, concrete implementation of the `DataClient` interface using the `mongo_dart` package. It acts as the bridge between your application's repositories and a MongoDB database. |
| 17 | +This package offers a comprehensive set of features for interacting with MongoDB. |
12 | 18 |
|
13 | | -It translates the abstract, high-level data requests from the `DataClient` interface—including rich filters, multi-field sorting, and cursor-based pagination—into native, efficient MongoDB queries. |
| 19 | +<details> |
| 20 | +<summary><strong>🧱 Core Functionality</strong></summary> |
14 | 21 |
|
15 | | -A key feature of this implementation is its **ID management strategy**. It ensures that the application layer remains the source of truth for a document's ID by mapping the model's `id` string to the database's `_id` field. This is crucial for correctly handling both global documents (like headlines) and user-owned documents (like settings), where the document's `_id` must match the user's ID. For a deeper explanation, see the documentation within the `DataMongodb` class. |
| 22 | +### 🚀 `DataClient` Implementation |
| 23 | +- **`DataMongodb<T>` Class:** A production-ready MongoDB implementation of the `DataClient<T>` interface, enabling type-safe interactions with various data models. |
| 24 | +- **`MongoDbConnectionManager`:** Includes a robust connection manager for handling MongoDB connection lifecycle, ensuring reliable database access. |
16 | 25 |
|
17 | | -## Getting Started |
| 26 | +### 🌐 Advanced Querying & Data Management |
| 27 | +- **Native MongoDB Queries:** Translates `readAll` parameters (rich `filter`, multi-field `sort`, and cursor-based `pagination`) into efficient native MongoDB queries. |
| 28 | +- **ID Management Strategy:** Faithfully maps the application-level `id` string to the database `_id` field, crucial for correctly handling both global documents (like headlines) and user-owned documents (like settings). |
| 29 | +- **Support for Multiple Data Models:** Correctly handles various document types, including global entities and user-owned documents where the `_id` serves as a foreign key to the user. |
| 30 | +- **Efficient Counting & Aggregation:** Implements `count` for efficient document counting and `aggregate` to execute powerful, server-side aggregation pipelines. |
| 31 | +- **Partial Text Search:** Translates a `q` filter parameter into a case-insensitive (`$regex`) search across designated searchable fields. |
18 | 32 |
|
19 | | -This package is intended to be used as a dependency in backend services (like a Dart Frog API) or applications that connect directly to MongoDB. |
| 33 | +### 🛡️ Standardized Error Handling |
| 34 | +- **`HttpException` Propagation:** Throws standard exceptions from `package:core` for consistent error handling, ensuring predictable error management across the application layers. |
20 | 35 |
|
21 | | -To use this package, add `data_mongodb` and its peer dependencies to your `pubspec.yaml`. |
22 | | - |
23 | | -```yaml |
24 | | -dependencies: |
25 | | - # data_client defines the interface this package implements. |
26 | | - data_client: |
27 | | - git: |
28 | | - url: https://github.com/flutter-news-app-full-source-code/data-client.git |
29 | | - # ref: <specific_commit_or_tag> |
30 | | - # core is needed for models and exceptions. |
31 | | - core: |
32 | | - git: |
33 | | - url: https://github.com/flutter-news-app-full-source-code/core.git |
34 | | - # ref: <specific_commit_or_tag> |
35 | | - data_mongodb: |
36 | | - git: |
37 | | - url: https://github.com/flutter-news-app-full-source-code/data-mongodb.git |
38 | | - # ref: <specific_commit_or_tag> |
39 | | -``` |
40 | | - |
41 | | -Then run `dart pub get` or `flutter pub get`. |
42 | | - |
43 | | -## Features |
44 | | - |
45 | | -- Implements the `DataClient<T>` interface from `package:data_client`. |
46 | | -- Includes `MongoDbConnectionManager` for robust connection lifecycle management. |
47 | | -- Translates `readAll` parameters (`filter`, `sort`, `pagination`) into native MongoDB queries. |
48 | | -- **Handles ID Management**: Faithfully maps the application-level `id` string to the database `_id`, preserving data integrity for all document types. |
49 | | -- **Supports Multiple Data Models**: Correctly handles both global documents (e.g., `Headline`) and user-owned documents (e.g., `UserAppSettings`) where the document `_id` serves as the foreign key to the user. |
50 | | -- Throws standard exceptions from `package:core` for consistent error handling. |
51 | | -- Implements `count` for efficient document counting. |
52 | | -- Implements `aggregate` to execute powerful, server-side aggregation pipelines. |
53 | | -- **Partial Text Search**: Translates a `q` filter parameter into a case-insensitive (`$regex`) across designated searchable fields. |
54 | | - |
55 | | -## Usage |
56 | | - |
57 | | -Here's a basic example of how to use `DataMongodb` with a simple `Product` model. |
58 | | - |
59 | | -```dart |
60 | | -import 'package:data_client/data_client.dart'; |
61 | | -import 'package:data_mongodb/data_mongodb.dart'; |
62 | | -import 'package:core/core.dart'; |
63 | | -
|
64 | | -// 1. Define your model. |
65 | | -class Product { |
66 | | - Product({required this.id, required this.name, required this.price}); |
67 | | - final String id; |
68 | | - final String name; |
69 | | - final double price; |
70 | | -
|
71 | | - // Your fromJson/toJson factories. |
72 | | - factory Product.fromJson(Map<String, dynamic> json) { |
73 | | - return Product( |
74 | | - id: json['id'] as String, |
75 | | - name: json['name'] as String, |
76 | | - price: json['price'] as double, |
77 | | - ); |
78 | | - } |
79 | | - Map<String, dynamic> toJson() => {'id': id, 'name': name, 'price': price}; |
80 | | -} |
81 | | -
|
82 | | -void main() async { |
83 | | - // 2. Set up the connection manager. |
84 | | - final connectionManager = MongoDbConnectionManager(); |
85 | | - const connectionString = 'mongodb://localhost:27017/my_database'; |
86 | | -
|
87 | | - try { |
88 | | - // 3. Initialize the database connection. |
89 | | - await connectionManager.init(connectionString); |
90 | | -
|
91 | | - // 4. Instantiate the client for your model. |
92 | | - final client = DataMongodb<Product>( |
93 | | - connectionManager: connectionManager, |
94 | | - modelName: 'products', // The name of the MongoDB collection. |
95 | | - fromJson: Product.fromJson, |
96 | | - toJson: (product) => product.toJson(), |
97 | | - searchableFields: ['name'], // Designate 'name' for partial-text search. |
98 | | - ); |
99 | | -
|
100 | | - // 5. Use the client to perform operations. |
101 | | - // Example: Forgiving search for products with "pro" in their name. |
102 | | - final searchResponse = await client.readAll( |
103 | | - filter: {'q': 'pro'}, |
104 | | - pagination: const PaginationOptions(limit: 5), |
105 | | - ); |
106 | | - print('\nFound ${searchResponse.data.items.length} products matching "pro":'); |
107 | | - for (final product in searchResponse.data.items) { |
108 | | - print('- ${product.name}'); |
109 | | - } |
110 | | - final filter = { |
111 | | - 'price': {r'$gte': 10.0} // Find products with price >= 10.0 |
112 | | - }; |
113 | | - final sort = [const SortOption('price', SortOrder.desc)]; |
114 | | - final pagination = const PaginationOptions(limit: 10); |
115 | | -
|
116 | | - final response = await client.readAll( |
117 | | - filter: filter, |
118 | | - sort: sort, |
119 | | - pagination: pagination, |
120 | | - ); |
121 | | -
|
122 | | - print('Found ${response.data.items.length} products.'); |
123 | | - for (final product in response.data.items) { |
124 | | - print('- ${product.name} (\$${product.price})'); |
125 | | - } |
126 | | -
|
127 | | - // Example: Counting items |
128 | | - final countResponse = await client.count( |
129 | | - filter: {'price': {r'$lt': 15.0}}, |
130 | | - ); |
131 | | - print('Found ${countResponse.data} products cheaper than $15.'); |
132 | | -
|
133 | | - // Example: Running an aggregation pipeline |
134 | | - final aggregateResponse = await client.aggregate( |
135 | | - pipeline: [ |
136 | | - { |
137 | | - r'$group': {'_id': null, 'averagePrice': {r'$avg': r'$price'}}, |
138 | | - }, |
139 | | - ], |
140 | | - ); |
141 | | - if (aggregateResponse.data.isNotEmpty) { |
142 | | - print( |
143 | | - 'Average product price: \$${aggregateResponse.data.first['averagePrice']}', |
144 | | - ); |
145 | | - } |
146 | | - } on HttpException catch (e) { |
147 | | - print('An error occurred: ${e.message}'); |
148 | | - } finally { |
149 | | - // 6. Always close the connection. |
150 | | - await connectionManager.close(); |
151 | | - } |
152 | | -} |
153 | | -``` |
| 36 | +> **💡 Your Advantage:** You get a meticulously designed, production-quality MongoDB client that simplifies database interactions, ensures data integrity, provides robust error handling, and supports advanced querying capabilities. This package accelerates development by providing a solid foundation for data persistence. |
154 | 37 |
|
| 38 | +</details> |
155 | 39 |
|
156 | 40 | ## 🔑 Licensing |
157 | 41 |
|
158 | | -This package is source-available and licensed under the [PolyForm Free Trial 1.0.0](LICENSE). Please review the terms before use. |
159 | | - |
160 | | -For commercial licensing options that grant the right to build and distribute unlimited applications, please visit the main [**Flutter News App - Full Source Code Toolkit**](https://github.com/flutter-news-app-full-source-code) organization. |
| 42 | +This `data_mongodb` package is an integral part of the [**Flutter News App Full Source Code Toolkit**](https://github.com/flutter-news-app-full-source-code). For comprehensive details regarding licensing, including trial and commercial options for the entire toolkit, please refer to the main toolkit organization page. |
0 commit comments