Part 2️⃣ - Product API |๐ Build .NET 8 eCommerce Microservice ๐with API Gateway, Rate Limiting, Caching & more ๐งบ
๐ Build .NET 8 eCommerce Microservice ๐with API Gateway, Rate Limiting, Caching & more ๐งบ - [Part 2️⃣]
Product
Description
This code defines the Product
class within the ProductApi.Domain.Entities
namespace. The Product
class represents a product entity with properties commonly associated with products in an e-commerce application.
Features
Id: Represents the unique identifier for the product. It is an integer property and serves as the primary key for the product entity.
Name: Represents the name of the product. It is a nullable string property, allowing the product name to be optional.
Price: Represents the price of the product. It is a decimal property, ensuring accurate representation of the product's cost, including fractions of currency units.
Quantity: Represents the quantity of the product available in stock. It is an integer property, indicating the number of units of the product that are available.
Usage
Data Representation: The
Product
class is used to represent product data within the application. It encapsulates all the necessary properties that describe a product, making it a central component for handling product-related operations.Entity Framework: This class can be used with Entity Framework or other ORM tools to map product data to a database table. The properties correspond to columns in the database, facilitating CRUD operations on product data.
Data Transfer and Manipulation: The
Product
class is often used in conjunction with data transfer objects (DTOs) to move data between different layers of the application. It provides a consistent structure for managing product information throughout the application's lifecycle.
Example
This Product
class serves as a fundamental building block for e-commerce applications, providing a clear and concise representation of product data. It promotes organized and maintainable code by encapsulating product-related properties and behaviors in a single, cohesive entity.
ProductDTO
Description
This code defines a ProductDTO
record in the ProductApi.Application.DTOs
namespace. The ProductDTO
record is a data transfer object used to encapsulate product information in a structured and validated format.
Features
Id: Represents the unique identifier for the product. It is an integer and does not have any specific validation attributes.
Name: Represents the name of the product. It is a required string field, ensuring that the product name must be provided.
Quantity: Represents the quantity of the product available. It is a required integer field with a validation attribute ensuring the value must be at least 1, preventing invalid or negative quantities.
Price: Represents the price of the product. It is a required decimal field with a data type attribute specifying it as a currency value, ensuring the proper handling and formatting of monetary values.
Usage
Validation: The
ProductDTO
uses data annotations to enforce validation rules, ensuring that all necessary fields are provided and adhere to specified constraints. This helps maintain data integrity and prevents invalid data from being processed.Data Transfer: This record is primarily used for transferring product data between different parts of the application, such as between the client and server or between different layers within the server. Its structure and validation attributes make it ideal for ensuring consistent and reliable data transfer.
Example
This ProductDTO
enhances the application's data handling capabilities by providing a clear and validated structure for product information, promoting robust and reliable data management practices.
ProductConversion
Description
This code defines a static class ProductConversion
within the ProductApi.Application.DTOs.Conversions
namespace. The class provides conversion methods between Product
entities and ProductDTO
objects, facilitating data transfer and manipulation within the application.
Features
ToEntity Method: Converts a
ProductDTO
object into aProduct
entity. This method creates a newProduct
instance, setting its properties (Id
,Name
,Quantity
, andPrice
) from the correspondingProductDTO
.FromEntity Method: Converts a
Product
entity or a collection ofProduct
entities into a tuple containing either a singleProductDTO
or an enumerable ofProductDTO
objects:- Single Product Conversion: When a single
Product
entity is provided, it returns a tuple with aProductDTO
representing that product and anull
for the collection. - Multiple Products Conversion: When a collection of
Product
entities is provided, it returns a tuple with anull
for the single product and an enumerable ofProductDTO
objects representing the collection. - Fallback: If neither a single product nor a collection is provided, it returns a tuple with both elements as
null
.
- Single Product Conversion: When a single
Usage
- The
ToEntity
method is useful when transforming data received from a client or external source into an entity suitable for database operations. - The
FromEntity
method is designed to convert entity data into a format suitable for transfer or display, accommodating both single entity and collection scenarios.
Example
This class enhances the application's ability to manage and manipulate product data efficiently, ensuring a seamless flow between different layers of the application architecture.
IProduct
Description
This code defines the IProduct
interface within the ProductApi.Application.Interfaces
namespace. It extends the IGenericInterface<Product>
from the eCommerce.SharedLibrary.Interface
namespace, facilitating the implementation of generic CRUD operations for Product
entities.
Features
Inheritance from
IGenericInterface<Product>
: TheIProduct
interface inherits fromIGenericInterface<Product>
, which likely defines a set of generic methods for performing CRUD operations (Create, Read, Update, Delete) onProduct
entities. This inheritance allows theIProduct
interface to leverage these generic methods, ensuring a consistent and reusable approach to data operations.Type-Specific Operations: By extending the generic interface with
Product
as the type parameter,IProduct
is tailored specifically for handlingProduct
entities, promoting type safety and reducing the risk of runtime errors.
Usage
Dependency Injection: The
IProduct
interface can be used in conjunction with dependency injection to provide a flexible and decoupled way of accessing and manipulatingProduct
entities within the application. This allows for easier testing and maintenance by adhering to the Dependency Inversion Principle.Implementation: Developers can create a concrete class that implements the
IProduct
interface, providing specific implementations for the generic CRUD operations defined inIGenericInterface<Product>
. This concrete class would handle the actual data operations, potentially interacting with a database or other data storage mechanisms.
Example
This interface promotes a modular and maintainable architecture by defining a clear contract for product-related data operations, leveraging the power of generics to ensure consistency and reusability across the application.
ProductDbContext
Description
This code defines the ProductDbContext
class within the ProductApi.Infrastructure.Data
namespace. The ProductDbContext
class extends DbContext
from the Entity Framework Core library, providing a database context for managing Product
entities.
Features
Inheritance from
DbContext
: TheProductDbContext
class inherits fromDbContext
, a core component of Entity Framework Core. This inheritance allows theProductDbContext
to manage database connections, transactions, and data operations forProduct
entities.Constructor with
DbContextOptions
: The constructor acceptsDbContextOptions<ProductDbContext>
as a parameter and passes it to the baseDbContext
constructor. This setup allows for configuration of the context, such as connection strings and database providers, to be specified externally, enhancing flexibility and ease of configuration.DbSet<Product> Products
: TheProducts
property is of typeDbSet<Product>
, representing a collection ofProduct
entities. This property enables CRUD operations onProduct
entities within the database. Entity Framework Core usesDbSet<T>
to query and save instances ofProduct
.
Usage
Entity Framework Core Integration: The
ProductDbContext
class integrates with Entity Framework Core, facilitating the use of LINQ queries, change tracking, and migrations for managingProduct
entities. It acts as a bridge between the domain entities and the database, enabling efficient data access and manipulation.Dependency Injection: The
ProductDbContext
can be registered with the dependency injection (DI) container in an ASP.NET Core application, allowing it to be injected into services and controllers. This promotes a decoupled and testable architecture.Configuration and Migrations: Developers can configure the
ProductDbContext
in the application'sStartup
class or equivalent, specifying the database provider (e.g., SQL Server, SQLite) and connection string. Migrations can be used to create and update the database schema based on changes to theProduct
entity model.
Example
The ProductDbContext
class is a crucial component of the application's data access layer, providing a structured and efficient way to manage Product
entities and their interactions with the database. It enhances the application's maintainability and scalability by leveraging the features and capabilities of Entity Framework Core.
ServiceContainer
Description
This code defines the ServiceContainer
static class within the ProductApi.Infrastructure.DependencyInjection
namespace. The class provides methods for setting up dependency injection and configuring middleware policies for the ProductApi
infrastructure.
Features
AddInfrastructureService Method: This method extends the
IServiceCollection
to add necessary services for the application infrastructure.- Database Connectivity: Integrates the database context (
ProductDbContext
) with the application's service collection, utilizing a shared service container fromeCommerce.SharedLibrary.DependencyInjection
. The configuration includes setting up Serilog for logging. - Dependency Injection: Registers the
IProduct
interface with its implementationProductRepository
, using scoped lifetime, ensuring a new instance is created per request. - Authentication Scheme: While the details are not explicitly provided, the method can be used to configure authentication schemes if needed.
- Database Connectivity: Integrates the database context (
UseInfrastructurePolicy Method: This method extends the
IApplicationBuilder
to configure middleware policies for the application.- Global Exception Handling: Integrates middleware for handling global exceptions, providing a centralized mechanism for error handling.
- API Gateway Request Listening: Configures the application to listen only to calls from the API Gateway, blocking external requests to enhance security.
- Shared Policies: Utilizes the shared service container to apply common middleware policies across the application.
Usage
Service Registration: The
AddInfrastructureService
method is called in theStartup
class or equivalent during the application's service registration phase. This ensures that all necessary infrastructure services are configured and available through dependency injection.Middleware Configuration: The
UseInfrastructurePolicy
method is invoked in the middleware configuration phase of the application, typically in theConfigure
method of theStartup
class. This ensures that the necessary middleware for handling exceptions and enforcing security policies is registered and active.
Example
The ServiceContainer
class enhances the modularity and maintainability of the application by encapsulating infrastructure service registration and middleware configuration within dedicated methods. It leverages shared services and policies, promoting consistency and reuse across the application's infrastructure.
ProductRepository
Description
The ProductRepository
class in the ProductApi.Infrastructure.Repositories
namespace implements the IProduct
interface and provides CRUD (Create, Read, Update, Delete) operations for Product
entities. It utilizes Entity Framework Core for data access and incorporates shared libraries for logging and response handling.
Features
CreateAsync: Adds a new
Product
entity to the database.- Checks for duplicate products by name before adding.
- Logs exceptions and returns user-friendly error messages.
DeleteAsync: Deletes an existing
Product
entity from the database.- Finds the product by its ID before deletion.
- Logs exceptions and returns user-friendly error messages.
FindByIdAsync: Retrieves a
Product
entity by its ID.- Returns the product if found; otherwise, returns null.
- Logs exceptions and throws user-friendly error messages.
GetAllAsync: Retrieves all
Product
entities from the database.- Returns a list of products.
- Logs exceptions and throws user-friendly error messages.
GetByAsync: Retrieves a
Product
entity that matches a specified predicate.- Uses LINQ expressions for querying.
- Logs exceptions and throws user-friendly error messages.
UpdateAsync: Updates an existing
Product
entity in the database.- Detaches the existing entity to prevent tracking issues.
- Logs exceptions and returns user-friendly error messages.
Usage
Dependency Injection: The
ProductRepository
is registered as a scoped service in the dependency injection container, allowing it to be injected into services or controllers that require product data operations.Error Handling and Logging: Utilizes
LogException
from theeCommerce.SharedLibrary.Logs
namespace to log exceptions. Provides clear, non-technical error messages to users while preserving detailed logs for developers.Response Handling: Returns
Response
objects from theeCommerce.SharedLibrary.Responses
namespace to standardize the format of API responses, indicating success or failure along with appropriate messages.
Example
The ProductRepository
class serves as a robust and maintainable data access layer for product-related operations in the application. By leveraging Entity Framework Core, shared logging, and response handling libraries, it ensures efficient and reliable data management while promoting clean code practices and error handling.
ProductsController
Description
The ProductsController
class within the ProductApi.Presentation.Controllers
namespace is an ASP.NET Core Web API controller that handles HTTP requests related to Product
entities. It leverages dependency injection to interact with the IProduct
interface, facilitating CRUD operations and conversions between Product
entities and ProductDTO
data transfer objects.
Features
GetProducts: Handles GET requests to retrieve all products.
- Retrieves all products from the repository.
- Converts entities to DTOs using the
ProductConversion
utility. - Returns a list of products or a 404 Not Found response if no products are available.
GetProduct: Handles GET requests to retrieve a single product by ID.
- Retrieves a product from the repository by its ID.
- Converts the entity to a DTO using the
ProductConversion
utility. - Returns the product or a 404 Not Found response if the product is not found.
CreateProduct: Handles POST requests to create a new product.
- Validates the model state to ensure data annotations are respected.
- Converts the DTO to an entity using the
ProductConversion
utility. - Calls the repository to add the new product and returns the response.
- Returns a success response or a 400 Bad Request response based on the operation result.
UpdateProduct: Handles PUT requests to update an existing product.
- Validates the model state to ensure data annotations are respected.
- Converts the DTO to an entity using the
ProductConversion
utility. - Calls the repository to update the product and returns the response.
- Returns a success response or a 400 Bad Request response based on the operation result.
DeleteProduct: Handles DELETE requests to remove a product.
- Converts the DTO to an entity using the
ProductConversion
utility. - Calls the repository to delete the product and returns the response.
- Returns a success response or a 400 Bad Request response based on the operation result.
- Converts the DTO to an entity using the
Usage
Dependency Injection: The
ProductsController
uses dependency injection to obtain an instance ofIProduct
, implemented byProductRepository
. This promotes separation of concerns and decouples the controller from the data access logic.DTO Conversion: Utilizes the
ProductConversion
static class to convert betweenProduct
entities andProductDTO
data transfer objects, ensuring a clean and consistent API data model.Standardized Responses: Returns standardized
Response
objects from theeCommerce.SharedLibrary.Responses
namespace, indicating success or failure of operations along with appropriate messages.
Example
The ProductsController
class is a key component of the ProductApi
, managing HTTP requests related to product management. By using DTOs, it maintains a consistent data format for API responses. It also fosters clean code practices by separating data access logic through dependency injection and handling CRUD operations efficiently.
Configuration
Description
This configuration snippet defines settings for an ASP.NET Core application, including logging, connection strings, Serilog configuration, and authentication. The settings are structured in JSON format, suitable for inclusion in the appsettings.json
file.
Features
Logging:
- LogLevel:
Default
: Sets the default logging level to "Information", meaning logs of "Information" level and above will be recorded.Microsoft.AspNetCore
: Sets the logging level for ASP.NET Core-specific logs to "Warning", so only warnings and errors will be logged for ASP.NET Core components.
- LogLevel:
AllowedHosts:
- Allows all hosts by setting it to "*". This configuration is useful during development but should be restricted in production environments for security reasons.
ConnectionStrings:
- eCommerceConnection: Defines the connection string for connecting to the SQL Server database.
Server
: Specifies the local server.Database
: Names the database asYoutubeECommerceDb
.Trusted_Connection=true
: Uses Windows Authentication.TrustServerCertificate=true
: Trusts the server's SSL certificate without validation, useful in development environments.
- eCommerceConnection: Defines the connection string for connecting to the SQL Server database.
MySerilog:
- FileName: Specifies the filename for Serilog logging. Logs will be written to files named
ProductApi
.
- FileName: Specifies the filename for Serilog logging. Logs will be written to files named
Authentication:
- Key: Provides a secret key used for generating and validating JWT tokens.
- Issuer: Defines the token issuer URL, set to
http://localhost:5000
for local development. - Audience: Defines the token audience URL, also set to
http://localhost:5000
for local development.
Usage
Logging: Configures the logging levels for different parts of the application, allowing for controlled verbosity of log output. This helps in filtering logs based on their importance.
Connection Strings: Provides the necessary details for the application to connect to the database, which is essential for data access and storage.
Serilog Configuration: Sets up Serilog for logging application events to files. This helps in maintaining log files for monitoring and troubleshooting.
Authentication: Configures JWT authentication with a secret key, issuer, and audience, allowing the application to securely handle user authentication and token validation.
Example
This configuration ensures that logging is appropriately managed, database connections are correctly established, and authentication is securely handled, making it suitable for both development and initial deployment scenarios. Adjustments may be required for production environments, such as restricting allowed hosts and enhancing security settings.
Program Registration
Description
This configuration snippet defines settings for an ASP.NET Core application, including logging, connection strings, Serilog configuration, and authentication. The settings are structured in JSON format, suitable for inclusion in the appsettings.json
file.
Features
Logging:
- LogLevel:
Default
: Sets the default logging level to "Information", meaning logs at the "Information" level and above will be recorded.Microsoft.AspNetCore
: Sets the logging level specifically for ASP.NET Core to "Warning", ensuring that only warnings and errors are logged for ASP.NET Core components.
- LogLevel:
AllowedHosts:
- Allows all hosts by setting it to "*". This is useful for development but should be restricted in production environments to enhance security.
ConnectionStrings:
- eCommerceConnection: Specifies the connection string for the SQL Server database.
Server
: Defines the local server.Database
: Names the database asYoutubeECommerceDb
.Trusted_Connection=true
: Uses Windows Authentication.TrustServerCertificate=true
: Trusts the server's SSL certificate without validation, which is helpful for development.
- eCommerceConnection: Specifies the connection string for the SQL Server database.
MySerilog:
- FileName: Specifies the filename for Serilog logs. Log entries will be written to files named
ProductApi
.
- FileName: Specifies the filename for Serilog logs. Log entries will be written to files named
Authentication:
- Key: Provides a secret key used for generating and validating JWT tokens.
- Issuer: Defines the URL of the token issuer, set to
http://localhost:5000
for local development. - Audience: Defines the URL of the token audience, also set to
http://localhost:5000
for local development.
Usage
Logging: Configures logging levels to control verbosity and ensure important log information is captured. This setup allows for filtering logs based on their severity.
Connection Strings: Provides essential details for connecting to the SQL Server database, crucial for data access and storage operations.
Serilog Configuration: Sets up Serilog for file-based logging of application events, aiding in maintaining logs for monitoring and troubleshooting purposes.
Authentication: Configures JWT authentication with the necessary details such as the secret key, issuer, and audience, ensuring secure handling of user authentication and token validation.
Example
This configuration ensures that logging is effective, database connections are properly established, and authentication is securely managed. It is suitable for development and initial deployment scenarios but should be reviewed and adjusted for production environments, particularly with regard to security and host restrictions.
# Here's a follow-up section to encourage engagement and support for Netcode-Hub:
๐ Get in touch with Netcode-Hub! ๐ซ
1. GitHub: [Explore Repositories] ๐
2. Twitter: [Stay Updated] ๐ฆ
3. Facebook: [Connect Here]๐
4. LinkedIn: [Professional Network]๐
5. Email: [business.netcodehub@gmail.com] ๐ง
# ☕️ If you've found value in Netcode-Hub's work, consider supporting the channel with a coffee!
Comments
Post a Comment