DelphiMVCFramework
repository·master·Indexed 23 days ago
https://github.com/danieleteti/delphimvcframeworkAn open-source framework for building RESTful services, JSON-RPC APIs, and web applications using Object Pascal. It features a complete MVC architecture with a built-in ORM, authentication, and middleware support. The repository also includes LoggerPro for asynchronous structured logging and SwagDoc for generating Swagger 2.0 specification files.
What's inside DelphiMVCFramework
- The Firebird programming interface examples are categorized into three main programming styles: Embedded Static SQL, Embedded Dynamic SQL, and the API Interface. These examples demonstrate various database operations ranging from simple table updates to complex asynchronous event trapping.
What is SwagDoc
masterSwagDoc is a Delphi library designed specifically to generate a
swagger.jsonfile following the Swagger Specification version 2.0.Its primary responsibility is the generation of the
swagger.jsonfile, which contains the complete documentation for your REST API. To visualize this documentation as an interactive web page, the generatedswagger.jsonfile must be attached to Swagger UI distribution files.Explore comprehensive streaming mechanisms and guides
masterFor more advanced or different streaming implementations, refer to these resources:
- Comprehensive Showcase: See
samples/streamed_array_writer/for a side-by-side comparison of JSON-array writers, SSE, JSONL, CSV, and the declarativeTMVCStreamedResponsechunked path. - Full Documentation: See
docs/incremental-streaming.mdfor a complete guide on when to use each mechanism, how to activate it, framing, backends, and handling disconnections.
- Comprehensive Showcase: See
Identify key files in the Minimal API WebApp Showcase
masterThe following files contain the core logic and templates for the showcase:
RoutesU.pas: Contains all handlers, annotated with the binding mode they illustrate.ShowcaseModelsU.pas: Defines the records used for data binding (TSignupForm,TContextInfo,TSearchQuery), demonstrating different attribute sources.templates/baselayout.htmlandtemplates/pages/*.html: Bootstrap 5.3 views (defaulting to dark mode viadata-bs-theme).ServicesU.pas: Handles the registration ofIPeopleServiceused by the routes.
Create an automatic installer for Delphi components using InnoSetup
masterThis collection of InnoSetup scripts allows you to build an automated installer for Delphi packages and libraries. The resulting setup can:
- Install the project into a user-selected folder.
- Copy all project files (Sources, resources, Packages, help, etc.).
- Detect installed Delphi versions on the machine.
- Compile packages (
.dcp) to create 32-bit and 64-bit.dcufiles. - Install packages (
.bpl) into the DelphiCommonBplFolder. - Create environment variables and add search paths using those variables.
During updates, the installer can uninstall previous versions (including those from Get-It), remove old sources, and clean up old
.dcpand.bplfiles fromCommonDcpFolderandCommonBplFolderbefore proceeding with the new installation.What is Resource Query Language (RQL)?
masterResource Query Language (RQL) is a query language designed for use in URIs with object-style data structures. It uses a set of nestable named operators with arguments, providing an extensible grammar that is URL-friendly. DelphiMVCFramework supports RQL natively, and theMVCActiveRecordframework implements a large subset of the RQL specifications for database querying.Understand Redis Key Formats for Rate Limiting
masterThe rate limit middleware stores state in Redis using a specific key pattern:
{prefix}:{keytype}:{identifier}. This allows for different types of rate limiting (e.g., by IP, User ID, or API Key) to coexist under the same prefix.Key types include:
rlkIPAddress(Type 0)rlkUserID(Type 1)rlkAPIKey(Type 2)rlkCustomHeader(Type 3)
The key lifecycle follows these steps:
- First Request: Key is created with value
1and a TTL (Time To Live) is set to the window duration. - Subsequent Requests: The key is incremented atomically using the Redis
INCRcommand. - After Window: The key expires automatically via Redis TTL.
- Next Window: A new key is created.
Configure Auto-Validation Attributes
masterThe generator automatically infers validation attributes from the database schema. In version 3.5.0-silicon and later, these are ON by default.
AUTO_REQUIRED: Emits[MVCRequired]on everyNOT NULLcolumn except auto-generated primary keys.AUTO_MAXLENGTH: Emits[MVCMaxLength(N)]on boundedVARCHAR/NVARCHARcolumns.TEXT/CLOBare skipped.
To disable these, set the corresponding key to
falsein your.envfile or use the CLI flags--no-auto-requiredor--no-auto-maxlength.Handle host-incompatible tests in DMVCFramework
masterSome tests exercise behaviors that front-end web servers (like Apache or IIS) might override or filter, such as custom status reason phrases, response compression, or permissive URL parsing. To prevent these from being marked as failures, they are categorized using DUnitX tags.
Test Categories
[Category('NotOnApache')]: Skipped duringtests-apacheruns.[Category('NotOnIIS')]: Skipped duringtests-isapiruns.[Category('NotOnApache,NotOnIIS')]: Skipped during both Apache and ISAPI runs.
The
invoketasks automatically pass the--excludeflag to the DUnitX runner based on these categories so that a successful run reports 0 failed, 0 errored on every host.Configure Fail-Open vs Fail-Closed Behavior
masterBy default, the Redis rate limit middleware is configured to fail-open. This means if the Redis server is unavailable, the middleware allows requests to proceed rather than blocking them. This prevents a Redis outage from causing a complete API outage.
If you require a fail-closed approach (where requests are blocked if Redis cannot be reached), you must customize the
CheckRateLimitmethod to raise an exception on Redis errors.Supported Parameter-Binding Modes in MinimalAPI
masterThe
MVCFramework.MinimalAPIsurface supports several ways to bind incoming request data to handler arguments. The following modes are demonstrated in the showcase:- Dependency Injection (DI): Resolving services (e.g.,
IPeopleService) directly from the service container. - Primitive Binding: Binding simple types (like
Integer) from route segments (e.g.,/people/(id:int)). - Class Body JSON: Binding a JSON request body to a class. This supports auto-validation using
TMVCValidatableand attributes like[MVCRequired],[MVCMinLength], and[MVCEmail]. - Record Binding: Binding query string parameters to a record using the
[MVCFromQueryString]attribute, allowing for per-field default values. - File Upload: Binding multipart form data to a
TMVCFormFileargument, which provides access toFileName,Size, andContentType. - Typed Array from Query: Binding repeated query string keys (e.g.,
?tag=a&tag=b) to aTArray<string>.
- Dependency Injection (DI): Resolving services (e.g.,
Configure dotEnv priority strategies
masterYou can control whether values from
.envfiles or System Environment variables take precedence by usingUseStrategywithTMVCDotEnvPriorityduring thedotEnvbuild process.TMVCDotEnvPriority.FileThenEnv: Values in.envfiles take precedence over System Environment variables.TMVCDotEnvPriority.EnvThenFile: System Environment variables take precedence over values in.envfiles.
// Strategy affects dotEnv.Env() behavior only: var dotEnv := NewDotEnv.UseStrategy(TMVCDotEnvPriority.FileThenEnv).Build(); // If 'PATH' is in both the file and the OS, this returns the file value: var Setting2 := dotEnv.Env('PATH'); // The OS environment remains unchanged: var SystemPath := GetEnvironmentVariable('PATH');