-
Notifications
You must be signed in to change notification settings - Fork 0
Build/update deps #2
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
6224d4f
chore: remove code coverage data
fulleni 7eb7754
chore(.gitignore): update .gitignore file
fulleni eebcf1e
chore(deps): update dependencies and add version control
fulleni 0008ce4
docs(README): redesign and simplify documentation
fulleni 45993f2
docs: update code coverage shield in README
fulleni a1b9aa0
docs(data_mongodb): add reference link for 'language' field conflict
fulleni File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,7 +1,4 @@ | ||
| # See https://www.dartlang.org/guides/libraries/private-files | ||
|
|
||
| # Files and directories created by pub | ||
| .dart_tool/ | ||
| .packages | ||
| build/ | ||
| pubspec.lock | ||
| coverage/ |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,160 +1,42 @@ | ||
| # data_mongodb | ||
| <div align="center"> | ||
| <img src="https://avatars.githubusercontent.com/u/202675624?s=400&u=dc72a2b53e8158956a3b672f8e52e39394b6b610&v=4" alt="Flutter News App Toolkit Logo" width="220"> | ||
| <h1>Data MongoDB</h1> | ||
| <p><strong>A production-ready MongoDB implementation of the `DataClient` interface for the Flutter News App Toolkit.</strong></p> | ||
| </div> | ||
|
|
||
|  | ||
| [](https://pub.dev/packages/very_good_analysis) | ||
| [](https://polyformproject.org/licenses/free-trial/1.0.0) | ||
| <p align="center"> | ||
| <img src="https://img.shields.io/badge/coverage-89%25-green?style=for-the-badge" alt="coverage"> | ||
| <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> | ||
| <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> | ||
| </p> | ||
|
|
||
| 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). | ||
| 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. | ||
|
|
||
| ## Description | ||
| ## ⭐ Feature Showcase: Powerful MongoDB Integration | ||
|
|
||
| `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. | ||
| This package offers a comprehensive set of features for interacting with MongoDB. | ||
|
|
||
| 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. | ||
| <details> | ||
| <summary><strong>🧱 Core Functionality</strong></summary> | ||
|
|
||
| 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. | ||
| ### 🚀 `DataClient` Implementation | ||
| - **`DataMongodb<T>` Class:** A production-ready MongoDB implementation of the `DataClient<T>` interface, enabling type-safe interactions with various data models. | ||
| - **`MongoDbConnectionManager`:** Includes a robust connection manager for handling MongoDB connection lifecycle, ensuring reliable database access. | ||
|
|
||
| ## Getting Started | ||
| ### 🌐 Advanced Querying & Data Management | ||
| - **Native MongoDB Queries:** Translates `readAll` parameters (rich `filter`, multi-field `sort`, and cursor-based `pagination`) into efficient native MongoDB queries. | ||
| - **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). | ||
| - **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. | ||
| - **Efficient Counting & Aggregation:** Implements `count` for efficient document counting and `aggregate` to execute powerful, server-side aggregation pipelines. | ||
| - **Partial Text Search:** Translates a `q` filter parameter into a case-insensitive (`$regex`) search across designated searchable fields. | ||
|
|
||
| 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. | ||
| ### 🛡️ Standardized Error Handling | ||
| - **`HttpException` Propagation:** Throws standard exceptions from `package:core` for consistent error handling, ensuring predictable error management across the application layers. | ||
|
|
||
| To use this package, add `data_mongodb` and its peer dependencies to your `pubspec.yaml`. | ||
|
|
||
| ```yaml | ||
| dependencies: | ||
| # data_client defines the interface this package implements. | ||
| data_client: | ||
| git: | ||
| url: https://github.com/flutter-news-app-full-source-code/data-client.git | ||
| # ref: <specific_commit_or_tag> | ||
| # core is needed for models and exceptions. | ||
| core: | ||
| git: | ||
| url: https://github.com/flutter-news-app-full-source-code/core.git | ||
| # ref: <specific_commit_or_tag> | ||
| data_mongodb: | ||
| git: | ||
| url: https://github.com/flutter-news-app-full-source-code/data-mongodb.git | ||
| # ref: <specific_commit_or_tag> | ||
| ``` | ||
|
|
||
| Then run `dart pub get` or `flutter pub get`. | ||
|
|
||
| ## Features | ||
|
|
||
| - Implements the `DataClient<T>` interface from `package:data_client`. | ||
| - Includes `MongoDbConnectionManager` for robust connection lifecycle management. | ||
| - Translates `readAll` parameters (`filter`, `sort`, `pagination`) into native MongoDB queries. | ||
| - **Handles ID Management**: Faithfully maps the application-level `id` string to the database `_id`, preserving data integrity for all document types. | ||
| - **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. | ||
| - Throws standard exceptions from `package:core` for consistent error handling. | ||
| - Implements `count` for efficient document counting. | ||
| - Implements `aggregate` to execute powerful, server-side aggregation pipelines. | ||
| - **Partial Text Search**: Translates a `q` filter parameter into a case-insensitive (`$regex`) across designated searchable fields. | ||
|
|
||
| ## Usage | ||
|
|
||
| Here's a basic example of how to use `DataMongodb` with a simple `Product` model. | ||
|
|
||
| ```dart | ||
| import 'package:data_client/data_client.dart'; | ||
| import 'package:data_mongodb/data_mongodb.dart'; | ||
| import 'package:core/core.dart'; | ||
| // 1. Define your model. | ||
| class Product { | ||
| Product({required this.id, required this.name, required this.price}); | ||
| final String id; | ||
| final String name; | ||
| final double price; | ||
| // Your fromJson/toJson factories. | ||
| factory Product.fromJson(Map<String, dynamic> json) { | ||
| return Product( | ||
| id: json['id'] as String, | ||
| name: json['name'] as String, | ||
| price: json['price'] as double, | ||
| ); | ||
| } | ||
| Map<String, dynamic> toJson() => {'id': id, 'name': name, 'price': price}; | ||
| } | ||
| void main() async { | ||
| // 2. Set up the connection manager. | ||
| final connectionManager = MongoDbConnectionManager(); | ||
| const connectionString = 'mongodb://localhost:27017/my_database'; | ||
| try { | ||
| // 3. Initialize the database connection. | ||
| await connectionManager.init(connectionString); | ||
| // 4. Instantiate the client for your model. | ||
| final client = DataMongodb<Product>( | ||
| connectionManager: connectionManager, | ||
| modelName: 'products', // The name of the MongoDB collection. | ||
| fromJson: Product.fromJson, | ||
| toJson: (product) => product.toJson(), | ||
| searchableFields: ['name'], // Designate 'name' for partial-text search. | ||
| ); | ||
| // 5. Use the client to perform operations. | ||
| // Example: Forgiving search for products with "pro" in their name. | ||
| final searchResponse = await client.readAll( | ||
| filter: {'q': 'pro'}, | ||
| pagination: const PaginationOptions(limit: 5), | ||
| ); | ||
| print('\nFound ${searchResponse.data.items.length} products matching "pro":'); | ||
| for (final product in searchResponse.data.items) { | ||
| print('- ${product.name}'); | ||
| } | ||
| final filter = { | ||
| 'price': {r'$gte': 10.0} // Find products with price >= 10.0 | ||
| }; | ||
| final sort = [const SortOption('price', SortOrder.desc)]; | ||
| final pagination = const PaginationOptions(limit: 10); | ||
| final response = await client.readAll( | ||
| filter: filter, | ||
| sort: sort, | ||
| pagination: pagination, | ||
| ); | ||
| print('Found ${response.data.items.length} products.'); | ||
| for (final product in response.data.items) { | ||
| print('- ${product.name} (\$${product.price})'); | ||
| } | ||
| // Example: Counting items | ||
| final countResponse = await client.count( | ||
| filter: {'price': {r'$lt': 15.0}}, | ||
| ); | ||
| print('Found ${countResponse.data} products cheaper than $15.'); | ||
| // Example: Running an aggregation pipeline | ||
| final aggregateResponse = await client.aggregate( | ||
| pipeline: [ | ||
| { | ||
| r'$group': {'_id': null, 'averagePrice': {r'$avg': r'$price'}}, | ||
| }, | ||
| ], | ||
| ); | ||
| if (aggregateResponse.data.isNotEmpty) { | ||
| print( | ||
| 'Average product price: \$${aggregateResponse.data.first['averagePrice']}', | ||
| ); | ||
| } | ||
| } on HttpException catch (e) { | ||
| print('An error occurred: ${e.message}'); | ||
| } finally { | ||
| // 6. Always close the connection. | ||
| await connectionManager.close(); | ||
| } | ||
| } | ||
| ``` | ||
| > **💡 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. | ||
| </details> | ||
|
|
||
| ## 🔑 Licensing | ||
|
|
||
| This package is source-available and licensed under the [PolyForm Free Trial 1.0.0](LICENSE). Please review the terms before use. | ||
|
|
||
| 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. | ||
| 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. | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.