### Install and Start React Frontend Source: https://github.com/synopse/mormot2/blob/master/ex/ThirdPartyDemos/dmvc-ai/51-react/README.md Navigate to the frontend directory, install dependencies using npm, and start the React development server. ```bash cd frontend npm install npm start ``` -------------------------------- ### Instantiating and Starting an HTTP Server Source: https://github.com/synopse/mormot2/blob/master/ex/ThirdPartyDemos/tbo/05-WebMustache/README.md Shows the minimal code required to create and start an HTTP server. This example configures a server on port 8080 with 2 threads and a 0-second keep-alive timeout. ```Pascal FHttpServer := THttpServer.Create( {Port=} ' 8080 ', Nil , Nil , ' ', {ServerThreadPoolCount=} 2, {KeepAliveTimeOut=} 0); FHttpServer.WaitStarted(WAIT_SECONDS); ``` -------------------------------- ### Start Server Source: https://github.com/synopse/mormot2/blob/master/ex/ThirdPartyDemos/dmvc-ai/03-routing/README.md Navigate to the release directory and start the routing sample executable. ```bash cd /mnt/w/mORMot2/ex/dmvc/03-routing/bin/Win32/Release RoutingSample.exe ``` -------------------------------- ### Start mORMot2 Renders Sample Server Source: https://github.com/synopse/mormot2/blob/master/ex/ThirdPartyDemos/dmvc-ai/04-renders/IMPLEMENTATION-NOTES.md Navigate to the sample directory and start the executable. This is the first step for manual testing. ```bash cd /mnt/w/mORMot2/ex/dmvc/04-renders ./RendersSample.exe ``` -------------------------------- ### Start the Custom Authentication Server Source: https://github.com/synopse/mormot2/blob/master/ex/ThirdPartyDemos/dmvc-ai/09-custom_auth/README.md Navigate to the project directory and start the server executable. This command assumes you are in the correct directory. ```bash cd /mnt/w/mORMot2/ex/dmvc/09-custom_auth ./bin/Win64/Debug/CustomAuthSample.exe ``` -------------------------------- ### Start Server Command Source: https://github.com/synopse/mormot2/blob/master/ex/ThirdPartyDemos/dmvc-ai/56-articles_crud_vcl_client/README.md Navigate to the server directory and execute the server application. Ensure the server is running before starting the client. ```bash cd ../06-articles_crud_server ./06-articles_crud_server.exe ``` -------------------------------- ### List mORMot2 Example Directories Source: https://github.com/synopse/mormot2/blob/master/ex/ThirdPartyDemos/dmvc-ai/COMPILATION-ERRORS-REPORT.md Lists the contents of specific mORMot2 example directories to investigate actual working code patterns. These commands help in identifying correct service registration, authentication setup, ORM usage, and event handling. ```bash ls -la /mnt/w/mORMot2/ex/tdd-service/src/ ls -la /mnt/w/mORMot2/ex/mvc-blog/ ls -la /mnt/w/mORMot2/ex/rest-websockets/ ``` -------------------------------- ### Main Program with SSL/HTTPS Setup Source: https://github.com/synopse/mormot2/blob/master/ex/ThirdPartyDemos/dmvc-ai/11-ssl_server/README.md The main program file for the SSL/HTTPS server demo, containing the core setup logic. ```pascal program ssl_server; {$APPTYPE CONSOLE} uses System.SysUtils, System.Classes, System.Generics.Collections, IdGlobal, IdHTTPWebBrokerBridge, IdCustomTCPServer, IdTCPServer, IdHTTPWebResponse, IdHTTPRequest, IdContext, IdYarn, IdSSLOpenSSL, IdSSLIOHandlerSocketOpenSSL, mormot.core.base, mormot.core.log, mormot.core.utils, mormot.core.json, mormot.core.db, mormot.core.db.sqlite, mormot.core.http.server, mormot.core.http.server.ssl, mormot.core.http.server.rest, mormot.core.http.server.api, api.interfaces, api.impl, entities, server; var LServer: TSslDemoServer; LOptions: TTHttpServerOptions; LSSLOptions: TTlsServerOptions; LDB: TSQLDBDatabase; begin ReportMemoryLeaksOnShutdown := True; ReportIdentityLeaksOnShutdown := True; LDB := TSQLDBDatabase.Create(nil); try LDB.DatabaseName := 'memory'; LDB.Open; try // Register ORM model TSQLModel.RegisterEntity(TPerson); // Create tables LDB.Execute( 'CREATE TABLE TPerson(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER)', nil ); // Setup HTTP server options LOptions := TTHttpServerOptions.Create; LSSLOptions := TTlsServerOptions.Create; try LOptions.Port := 8080; LOptions.MaxThreads := 10; LOptions.EnableKeepAlive := True; LOptions.EnableCompression := True; LOptions.EnableLogging := True; // SSL/TLS options LSSLOptions.Enabled := True; LSSLOptions.CertFile := 'server.pem'; // Certificate file LSSLOptions.KeyFile := 'server.key'; // Private key file LSSLOptions.Password := ''; // Password for the private key (if any) LSSLOptions.RootCertFile := ''; // Optional: Root certificate for client authentication LSSLOptions.ClientAuth := TClientAuth.caNone; LSSLOptions.Protocols := [tls12, tls13]; // Supported TLS protocols LSSLOptions.CipherList := ''; // Optional: Custom cipher list // Create and start the SSL/TLS server LServer := TSslDemoServer.Create(LDB, LOptions, LSSLOptions); try Writeln('Starting SSL/HTTPS server on port ', LOptions.Port, '...'); LServer.Start; Writeln('Server started. Press Enter to stop.'); Readln; finally LServer.Free; end; finally LSSLOptions.Free; LOptions.Free; end; except on E: Exception do begin Writeln('Error: ', E.Message); ExitCode := 1; end; end; finally LDB.Close; LDB.Free; end; end. ``` -------------------------------- ### Minimal mORMot2 Project Setup Source: https://github.com/synopse/mormot2/blob/master/docs/mORMot2-SAD-Chapter-01.md A basic Pascal program demonstrating the creation of an ORM model, a REST server with SQLite3 storage, and wrapping it in an HTTP server. This serves as a starting point for mORMot2 applications. ```pascal program MyFirstMormot; {$APPTYPE CONSOLE} uses mormot.core.base, mormot.core.os, mormot.orm.core, mormot.orm.sqlite3, mormot.rest.sqlite3, mormot.rest.http.server; type TOrmSample = class(TOrm) private fName: RawUtf8; fValue: Integer; published property Name: RawUtf8 read fName write fName; property Value: Integer read fValue write fValue; end; var Model: TOrmModel; Server: TRestServerDB; HttpServer: TRestHttpServer; begin // Create ORM model with our class Model := TOrmModel.Create([TOrmSample]); // Create REST server with SQLite3 storage Server := TRestServerDB.Create(Model, 'sample.db3'); Server.Server.CreateMissingTables; // Wrap in HTTP server HttpServer := TRestHttpServer.Create('8080', [Server], '+', useHttpAsync); try WriteLn('Server running on http://localhost:8080'); WriteLn('Press Enter to quit...'); ReadLn; finally HttpServer.Free; Server.Free; Model.Free; end; end. ``` -------------------------------- ### Start the Server Source: https://github.com/synopse/mormot2/blob/master/ex/ThirdPartyDemos/dmvc-ai/41-custom_exception_handling_using_controller/README.md Execute this command to start the mORMot2 server for testing exception handling. ```bash ./41-custom_exception_handling_using_controller ``` -------------------------------- ### Start Backend Server Command Source: https://github.com/synopse/mormot2/blob/master/ex/ThirdPartyDemos/dmvc-ai/50-angular/README.md This bash command navigates to the sample directory and starts the backend server. The server will initialize a database and enable CORS. ```bash cd /mnt/w/mORMot2/ex/dmvc/50-angular ./50-angular ``` -------------------------------- ### Run dmvc-ai Example Executable Source: https://github.com/synopse/mormot2/blob/master/ex/ThirdPartyDemos/dmvc-ai/51-complete_examples_final/README.md Executes the compiled dmvc-ai example application. The server will initialize an in-memory SQLite database, create sample articles, start an HTTP server on port 8080, and log operations. ```bash ./51-complete_examples_final.exe ``` -------------------------------- ### Start Client Command Source: https://github.com/synopse/mormot2/blob/master/ex/ThirdPartyDemos/dmvc-ai/56-articles_crud_vcl_client/README.md Execute the client application after the server has started. The client will automatically connect and load articles. ```bash ./56-articles_crud_vcl_client.exe ``` -------------------------------- ### Start the dmvc-ai Compression Server Source: https://github.com/synopse/mormot2/blob/master/ex/ThirdPartyDemos/dmvc-ai/14-middleware_compression/VERIFICATION.md Navigate to the build directory and start the executable to run the server with compression middleware enabled. ```bash cd /mnt/w/mORMot2/ex/dmvc/14-middleware_compression/Win64/Debug ./14-middleware_compression.exe ``` -------------------------------- ### Start the mORMot2 Server Source: https://github.com/synopse/mormot2/blob/master/ex/ThirdPartyDemos/dmvc-ai/48-jsonwriterrenders/IMPLEMENTATION-NOTES.md Execute this command in the terminal to start the server for the JSON writer demo. Ensure the executable is in your current directory. ```bash ./48-jsonwriterrenders.exe ``` -------------------------------- ### Install and Start Windows Service Source: https://github.com/synopse/mormot2/blob/master/ex/ThirdPartyDemos/dmvc-ai/docs/DEPLOYMENT-QUICK-START.md Use this command to install and start the DMVC AI application as a Windows service. This is recommended for production environments requiring automatic startup. ```bash cd /mnt/w/mORMot2/ex/dmvc/43-windows_service dcc32 43-windows_service.dpr 43-windows_service.exe /install net start "mORMot2 REST Service (DMVC port)" ``` -------------------------------- ### GET Request Format Source: https://github.com/synopse/mormot2/blob/master/docs/mORMot2-SAD-Chapter-17.md Example of a GET request to a mORMot service endpoint for a simple operation. ```http GET /api/Calculator/Add?n1=10&n2=20 HTTP/1.1 Host: server.example.com ``` -------------------------------- ### Start Server Source: https://github.com/synopse/mormot2/blob/master/ex/ThirdPartyDemos/dmvc-ai/49-render_binary_contents/IMPLEMENTATION-NOTES.md Launches the executable that will serve the binary content. Ensure this is run in the correct directory. ```bash ./49-render_binary_contents.exe ``` -------------------------------- ### Start Windows Service Source: https://github.com/synopse/mormot2/blob/master/ex/ThirdPartyDemos/dmvc-ai/docs/DEPLOYMENT-SAMPLES.md Starts the installed mORMot2 REST Service. This command requires administrative privileges. ```bash net start "mORMot2 REST Service (DMVC port)" ``` -------------------------------- ### Get Service Status Endpoint Source: https://github.com/synopse/mormot2/blob/master/ex/ThirdPartyDemos/dmvc-ai/43-windows_service/README.md Example GET request to retrieve the current status of the Windows Service. ```http GET http://localhost:8080/root/ServiceApi.GetStatus ``` -------------------------------- ### Create Test Directory and Files Source: https://github.com/synopse/mormot2/blob/master/ex/ThirdPartyDemos/dmvc-ai/49-render_binary_contents/IMPLEMENTATION-NOTES.md Sets up a directory for test files and creates a sample text file. This is the initial step before running the server. ```bash mkdir -p files_repository cd files_repository # Create test files echo "Hello World" > test.txt # Add test.jpg, test.pdf, etc. ``` -------------------------------- ### Install and Manage Windows Service Source: https://github.com/synopse/mormot2/blob/master/ex/ThirdPartyDemos/dmvc-ai/PHASE-19-DEPLOYMENT-SUMMARY.md Commands to install, start, stop, and uninstall a mORMot2 Windows Service. Ensure the service name matches the executable. ```cmd 43-windows_service.exe /install net start "mORMot2 REST Service (DMVC port)" net stop "mORMot2 REST Service (DMVC port)" 43-windows_service.exe /uninstall ``` -------------------------------- ### Service Status Response Source: https://github.com/synopse/mormot2/blob/master/ex/ThirdPartyDemos/dmvc-ai/43-windows_service/README.md Example JSON response for the Get Service Status endpoint. ```json { "Running": true, "Uptime": 123, "Port": 8080, "Message": "Service running for 123 seconds" } ``` -------------------------------- ### Basic TRestHttpServer Setup Source: https://github.com/synopse/mormot2/blob/master/docs/mORMot2-SAD-Chapter-11.md Initializes a TRestHttpServer to listen on a specified port, host TRestServer instances, and run in asynchronous mode. CORS is enabled. ```pascal uses mormot.rest.http.server; var HttpServer: TRestHttpServer; begin HttpServer := TRestHttpServer.Create( '8080', // Port [Server], // TRestServer instances '+', // Domain ('+' = all) useHttpAsync // Server mode ); try HttpServer.AccessControlAllowOrigin := '*'; // CORS // Server running... ReadLn; finally HttpServer.Free; end; end; ``` -------------------------------- ### Echo Test Endpoint Source: https://github.com/synopse/mormot2/blob/master/ex/ThirdPartyDemos/dmvc-ai/43-windows_service/README.md Example GET request to test the Echo endpoint, sending a message to be returned. ```http GET http://localhost:8080/root/ServiceApi.Echo?aMessage=hello ``` -------------------------------- ### Windows Service Commands Source: https://github.com/synopse/mormot2/blob/master/ex/ThirdPartyDemos/dmvc-ai/docs/DEPLOYMENT-QUICK-START.md Commands to install, start, stop, uninstall, and check the status of a Windows Service deployment. ```cmd # Install 43-windows_service.exe /install # Start net start "mORMot2 REST Service (DMVC port)" # Stop net stop "mORMot2 REST Service (DMVC port)" # Uninstall 43-windows_service.exe /uninstall # Check status sc query "mORMot2RestService" ``` -------------------------------- ### Example: Get User by ID Source: https://github.com/synopse/mormot2/blob/master/ex/ThirdPartyDemos/dmvc-ai/03-routing/INVESTIGATION-SUMMARY.md A complete example demonstrating how to extract an integer path parameter for user ID, handle invalid input, and return a JSON response. Register the route using the extracted parameter syntax. ```pascal function DoGetUser(Ctxt: THttpServerRequestAbstract): cardinal; var userId: Int64; begin // Extract and validate path parameter if not Ctxt.RouteInt64('id', userId) then begin Ctxt.OutContent := '{"error":"Invalid user ID"}'; result := HTTP_BADREQUEST; exit; end; // Process request // ... retrieve user from database ... Ctxt.OutContent := userJson; Ctxt.OutContentType := JSON_CONTENT_TYPE; result := HTTP_SUCCESS; end; // Registration Server.Route.Get('/api/users/', DoGetUser); ``` -------------------------------- ### Basic ORM and REST Server Setup Source: https://github.com/synopse/mormot2/blob/master/docs/mORMot2-SAD-Foreword.md This snippet demonstrates the initial setup for an ORM model and a REST server using SQLite3. It includes defining an ORM class, creating the model, initializing the server, creating tables, and adding a new record. ```Pascal uses mormot.core.base, mormot.orm.core, mormot.rest.sqlite3; type TOrmPerson = class(TOrm) private fName: RawUtf8; fAge: Integer; published property Name: RawUtf8 read fName write fName; property Age: Integer read fAge write fAge; end; var Model: TOrmModel; Server: TRestServerDB; Person: TOrmPerson; begin Model := TOrmModel.Create([TOrmPerson]); Server := TRestServerDB.Create(Model, 'test.db'); try Server.CreateMissingTables; Person := TOrmPerson.Create; try Person.Name := 'John'; Person.Age := 30; Server.Add(Person, true); finally Person.Free; end; finally Server.Free; Model.Free; end; end. ``` -------------------------------- ### Initialize ORM and Database Connection Source: https://github.com/synopse/mormot2/blob/master/ex/ThirdPartyDemos/tbo/01-ORM-DocVariant/README.md Demonstrates the creation of an ORM model and a TRestServerDB instance. Note that smFull is the slowest but ensures ACID behavior; smNormal is a practical compromise. Automatic table creation for authentication is suppressed in this example. ```Pascal type TOrmFile = class (TOrm) ... published property Title: RawUTF8 read FTitle write FTitle; property Comment: RawUtf8 read FComment write FComment; property MetaData: Variant read FMetaData write FMetaData; ... end ; ... FRestServer := TRestServerDB.Create(TOrmModel.Create([TOrmFile, ...]), DBFileName, False, DBPassword); FRestServer.Model.Owner := FRestServer; FRestServer.DB.Synchronous := smFull; FRestServer.DB.LockingMode := lmExclusive; FRestServer.Server.CreateMissingTables(0, [itoNoAutoCreateGroups, itoNoAutoCreateUsers]); ``` -------------------------------- ### Service Endpoints - Get Database Statistics Source: https://github.com/synopse/mormot2/blob/master/ex/ThirdPartyDemos/dmvc-ai/51-complete_examples_final/README.md Example using curl to call the GetStatistics service endpoint to retrieve database statistics. ```bash # Get database statistics curl -X POST http://localhost:8080/root/CompleteApi/GetStatistics ``` -------------------------------- ### Run Log Filter Sample Application Source: https://github.com/synopse/mormot2/blob/master/ex/ThirdPartyDemos/dmvc-ai/39-log_filter/README.md Navigate to the build directory and execute the LogFilterSample.exe to start the server. The server will be accessible at http://localhost:8080. ```bash cd /mnt/w/mORMot2/ex/dmvc/39-log_filter/Win64/Release ./LogFilterSample.exe ``` -------------------------------- ### ORM REST Endpoints - Get Article by ID Source: https://github.com/synopse/mormot2/blob/master/ex/ThirdPartyDemos/dmvc-ai/51-complete_examples_final/README.md Example of how to retrieve a specific article by its ID using the ORM REST API. ```bash # Get article by ID GET /root/Article/1 ``` -------------------------------- ### Premake5 Build Configurations for QuickJS Source: https://github.com/synopse/mormot2/blob/master/res/static/libquickjs/README.md Examples of using Premake5 to configure QuickJS builds for different platforms, compilers, and IDEs. Options include enabling JSX and Persistent Storage support. ```bat premake5 vs2019 --jsx --storage ``` ```bat premake5 codeblocks --cc=gcc --jsx --storage ``` ```bat premake5 gmake2 --cc=gcc --jsx --storage ``` ```bat premake5 gmake2 --cc=clang --jsx --storage ``` ```bat premake5 xcode4 --jsx --storage ``` -------------------------------- ### Windows Service Management Commands Source: https://github.com/synopse/mormot2/blob/master/docs/mORMot2-SAD-Chapter-20.md Batch commands for managing a Windows service created with mORMot2. Covers installation, starting, stopping, and uninstallation. ```batch :: Install service MyServerService.exe /install :: Start service net start MyServer :: Stop service net stop MyServer :: Uninstall service MyServerService.exe /uninstall ``` -------------------------------- ### Configuring In-Memory Storage Server Source: https://github.com/synopse/mormot2/blob/master/docs/mORMot2-SAD-Chapter-05.md Provides examples for creating an in-memory storage server using `TRestServerFullMemory`. It shows how to instantiate it for pure in-memory use or with file persistence. ```Pascal uses mormot.rest.memserver; // Use TRestServerFullMemory for pure in-memory ORM Server := TRestServerFullMemory.Create(Model, '', False, False); // Or with file persistence: Server := TRestServerFullMemory.Create(Model, 'data.json', False, False); ``` -------------------------------- ### Automatic Batching with Client.BatchStart Source: https://github.com/synopse/mormot2/blob/master/docs/mORMot2-SAD-Chapter-12.md Illustrates transparent batching using Client.BatchStart, Client.BatchAdd, and Client.BatchSend. This method simplifies the process of batching operations without explicit TRestBatch management. ```Pascal var Results: TIDDynArray; begin // Start automatic batching Client.BatchStart(TOrmCustomer, 1000); try for i := 1 to 10000 do begin Customer := TOrmCustomer.Create; Customer.Name := FormatUtf8('Customer %', [i]); Client.BatchAdd(Customer, True); // Add to current batch Customer.Free; end; finally Client.BatchSend(Results); // Send remaining batch end; end; ``` -------------------------------- ### Service Endpoints - Get Server Version Source: https://github.com/synopse/mormot2/blob/master/ex/ThirdPartyDemos/dmvc-ai/51-complete_examples_final/README.md Example using curl to call the GetVersion service endpoint. This is a POST request to the /root/CompleteApi/GetVersion path. ```bash # Get server version curl -X POST http://localhost:8080/root/CompleteApi/GetVersion ``` -------------------------------- ### Manual Static File Serving (Before) Source: https://github.com/synopse/mormot2/blob/master/ex/ThirdPartyDemos/dmvc-ai/15-middleware_staticfiles/REFACTOR-SUMMARY.md Illustrates the previous manual approach to serving static files, involving direct assignment of content, content type, and custom headers. ```pascal if FileExists(fileName) then begin // Serve the file Ctxt.OutContent := StringToUtf8(fileName); Ctxt.OutContentType := HTTP_RESP_STATICFILE; // Set custom MIME type Ctxt.OutCustomHeaders := FormatUtf8('Content-Type: %; charset=%'#13#10 + 'Cache-Control: public, max-age=3600', [GetMimeType(fileName, CustomMimeTypes, CustomMimeValues), Charset]); result := HTTP_SUCCESS; TSynLog.Add.Log(sllTrace, 'Served static file: %', [fileName]) end ``` -------------------------------- ### Production CORS Setup in Pascal Source: https://github.com/synopse/mormot2/blob/master/ex/ThirdPartyDemos/dmvc-ai/50-angular/README.md Modify server.pas to restrict allowed origins for production environments. This example shows how to set the Access-Control-Allow-Origin header. ```pascal // Replace in OnBeforeBody: corsHeaders := 'Access-Control-Allow-Origin: https://yourdomain.com'#13#10 + ... ``` -------------------------------- ### ProcessManager Command Line Usage Source: https://github.com/synopse/mormot2/blob/master/docs/mORMot2-SAD-Chapter-20.md Illustrates the command-line arguments for installing, starting, stopping, and running the ProcessManager application in console mode on Windows and Linux. ```bash # Windows ProcessManager.exe /install ProcessManager.exe /start ProcessManager.exe /console # Run in foreground for debugging # Linux ./ProcessManager --run # Run as daemon ./ProcessManager --console # Run in foreground ./ProcessManager --kill # Stop daemon ``` -------------------------------- ### Build QuickJS with Visual Studio Source: https://github.com/synopse/mormot2/blob/master/res/static/libquickjs/README.md Instructions to generate and open a Visual Studio solution for QuickJS using premake5. This allows for compilation and running the interactive JS command line application. ```bat premake5 vs2017.bat premake5 vs2019.bat ``` -------------------------------- ### Initial Welcome Messages Source: https://github.com/synopse/mormot2/blob/master/ex/ThirdPartyDemos/dmvc-ai/17-websocket_primer/www/index.html Displays initial welcome and instructional messages when the page loads. These messages guide the user on how to start using the WebSocket client. ```javascript // Initial message addMessage('👋 Welcome to mORMot2 WebSocket Echo Server Test Client', 'system'); addMessage('📝 Click Connect to start. The server will automatically send periodic heartbeat messages.', 'system'); ``` -------------------------------- ### Run Console Sample Source: https://github.com/synopse/mormot2/blob/master/ex/ThirdPartyDemos/dmvc-ai/02-console_sample/README.md Execute the compiled console sample application. ```bash ./Win32/Debug/ConsoleSample.exe ``` -------------------------------- ### Service Endpoints - Get Articles by Author Source: https://github.com/synopse/mormot2/blob/master/ex/ThirdPartyDemos/dmvc-ai/51-complete_examples_final/README.md Example using curl to call the GetArticlesByAuthor service endpoint. Requires Content-Type and JSON payload specifying the author. ```bash # Get articles by author curl -X POST http://localhost:8080/root/CompleteApi/GetArticlesByAuthor \ -H "Content-Type: application/json" \ -d '{"author":"Author 1"}' ``` -------------------------------- ### Run REST Client Sample Source: https://github.com/synopse/mormot2/blob/master/ex/ThirdPartyDemos/dmvc-ai/21-restclient/README.md Execute the compiled REST client sample application. ```bash ./Win32/Debug/RESTClientSample.exe ``` -------------------------------- ### Aggregation Pipeline Example Source: https://github.com/synopse/mormot2/blob/master/docs/mORMot2-SAD-Chapter-09.md Demonstrates creating and executing an aggregation pipeline with $match, $group, and $sort stages to process documents. ```pascal var Pipeline: variant; Results: variant; i: Integer; begin Pipeline := _Arr([ // Stage 1: Filter _ObjFast(['$match', _ObjFast(['status', 'active'])]), // Stage 2: Group and count _ObjFast(['$group', _ObjFast([ '_id', '$category', 'total', _ObjFast(['$sum', 1]), 'avgPrice', _ObjFast(['$avg', '$price']) ])]), // Stage 3: Sort _ObjFast(['$sort', _ObjFast(['total', -1])]) ]); Results := Coll.AggregateDocFromVariant(Pipeline); with _Safe(Results)^ do for i := 0 to Count - 1 do WriteLn(Values[i]._id, ': ', Values[i].total, ' items, avg $', Values[i].avgPrice); end; ``` -------------------------------- ### URI Routing with Parameter Extraction Source: https://github.com/synopse/mormot2/blob/master/src/net/CLAUDE.md Implement efficient URI routing and parameter extraction using TUriRouter. This example shows rewriting a GET request and handling a POST request. ```pascal Router := TUriRouter.Create(TUriTreeNode); Router.Rewrite(urmGet, '/api/users/', urmGet, '/internal/user?id='); Router.Run(urmPost, '/api/users', @HandleCreateUser); // Router.Process() achieves ~8M parametrized rewrites/sec ``` -------------------------------- ### Main Program to Run REST Services Demo Source: https://github.com/synopse/mormot2/blob/master/docs/mORMot2-SAD-Chapter-14.md Initializes and runs the REST server and client, demonstrating the interaction between them. It sets up the server, configures the client, and executes sample calls. ```Pascal program MethodServicesDemo; uses mormot.core.base, mormot.orm.core, mormot.rest.http.server, RestServerUnit, RestClientUnit; var Model: TOrmModel; Server: TMyRestServer; HttpServer: TRestHttpServer; Client: TMyRestClient; begin Model := TOrmModel.Create([], 'root'); Server := TMyRestServer.Create(Model); try Server.ServiceMethodByPassAuthentication('Time'); HttpServer := TRestHttpServer.Create('8080', [Server], '+', useHttpAsync); try // Client demo Client := TMyRestClient.Create('localhost', '8080', TOrmModel.Create([], 'root')); try WriteLn('Sum(3.5, 2.5) = ', Client.Sum(3.5, 2.5):0:2); WriteLn('Echo: ', Client.Echo('Hello mORMot!')); WriteLn('Server time: ', DateTimeToStr(Client.GetServerTime)); finally Client.Free; end; WriteLn('Press Enter to stop...'); ReadLn; finally HttpServer.Free; end; finally Server.Free; Model.Free; end; end. ``` -------------------------------- ### REST to SQL Translation Examples Source: https://github.com/synopse/mormot2/blob/master/docs/mORMot2-SAD-Chapter-13.md Demonstrates how mORMot2 translates common RESTful HTTP requests (GET, POST, PUT, DELETE) into corresponding SQL statements for CRUD operations. ```text GET /api/Customer → SELECT ID, Name, Email, ... FROM Customer GET /api/Customer/123 → SELECT ID, Name, Email, ... FROM Customer WHERE ID=123 GET /api/Customer?where=Country%3D%27USA%27 → SELECT ID, Name, Email, ... FROM Customer WHERE Country='USA' POST /api/Customer (body: {"Name":"ACME"}) → INSERT INTO Customer (Name) VALUES ('ACME') PUT /api/Customer/123 (body: {"Name":"Updated"}) → UPDATE Customer SET Name='Updated' WHERE ID=123 DELETE /api/Customer/123 → DELETE FROM Customer WHERE ID=123 ``` -------------------------------- ### Example TSynAngelizeService JSON Configuration Source: https://github.com/synopse/mormot2/blob/master/src/app/CLAUDE.md This JSON configuration defines a service named 'WebServer' to be managed by TSynAngelizeService. It specifies the executable path, actions for starting and stopping, a health check URL, and retry/notification settings. ```json { "Name": "WebServer", "Run": "/usr/local/bin/myserver", "Start": [ "start:%run%" ], "Stop": [ "stop:%run%" ], "Watch": [ "http://127.0.0.1:8080/health=200" ], "WatchDelaySec": 60, "RetryStableSec": 120, "Notify": "admin@example.com,%log%alerts.log" } ``` -------------------------------- ### Start Server and Run Tests Source: https://github.com/synopse/mormot2/blob/master/ex/ThirdPartyDemos/dmvc-ai/12-middleware/TESTING.md Initiates the middleware server and then runs a basic test using curl. ```bash # Terminal 1: Start server cd /mnt/w/mORMot2/ex/dmvc/12-middleware 12-middleware.exe # Terminal 2: Run tests curl http://localhost:8080/root/MiddlewareApi/Index ``` -------------------------------- ### DMVC Interface-Based Controller Example Source: https://github.com/synopse/mormot2/blob/master/ex/ThirdPartyDemos/dmvc-ai/CONVERSION-GUIDE.md Defines a DMVC controller for user management with methods for getting all users, a specific user, creating a user, and updating a user. These are mapped to different HTTP methods and paths. ```pascal type [MVCPath('/api/users')] TUserController = class(TMVCController) public [MVCPath('')] [MVCHTTPMethod([httpGET])] procedure GetAllUsers; [MVCPath('/($id)')] [MVCHTTPMethod([httpGET])] procedure GetUser(id: Integer); [MVCPath('')] [MVCHTTPMethod([httpPOST])] procedure CreateUser; [MVCPath('/($id)')] [MVCHTTPMethod([httpPUT])] procedure UpdateUser(id: Integer); end; ``` -------------------------------- ### Test RESTful Endpoints with curl Source: https://github.com/synopse/mormot2/blob/master/ex/ThirdPartyDemos/dmvc-ai/03-routing/REFACTOR-SUMMARY.md Provides examples for testing various RESTful endpoints including GET, POST, PUT, and DELETE requests. Demonstrates parameter passing via URL and JSON body. ```bash curl -X GET http://localhost:8080/api/users/1 curl -X GET "http://localhost:8080/api/users?filter=active&limit=5" curl -X GET http://localhost:8080/api/search/user1 curl -X POST http://localhost:8080/api/users \ -H "Content-Type: application/json" \ -d '{"name":"Jane","email":"jane@example.com"}' curl -X PUT http://localhost:8080/api/users/1 \ -H "Content-Type: application/json" \ -d '{"name":"Jane Updated","email":"jane@example.com"}' curl -X DELETE http://localhost:8080/api/users/1 curl -X GET "http://localhost:8080/api/users/status/active?page=1&pageSize=10" ``` -------------------------------- ### Running Custom Authentication Sample Source: https://github.com/synopse/mormot2/blob/master/ex/ThirdPartyDemos/dmvc-ai/09-custom_auth/VERIFICATION.md Instructions to compile and run the custom authentication sample, followed by executing endpoint tests. ```bash # Start server cd /mnt/w/mORMot2/ex/dmvc/09-custom_auth ./bin/Win64/Debug/CustomAuthSample.exe # In another terminal, run tests ./test-endpoints.sh ``` -------------------------------- ### HTTP Microservice Daemon Setup Source: https://github.com/synopse/mormot2/blob/master/src/app/CLAUDE.md This Pascal code snippet shows how to set up an HTTP microservice within a mormot2 daemon. It covers ORM model creation, database connection, and starting the HTTP server with specific configurations. ```Pascal procedure TMyDaemon.Start; begin // Create ORM model and database Model := TOrmModel.Create([TOrmSample]); DB := TRestServerDB.Create(Model, 'data.db'); DB.CreateMissingTables; // Start HTTP server HttpServer := TRestHttpServer.Create( '8080', // Port [DB], // REST servers '+', // Domain mask useHttpAsync, // HTTP mode 4 // Thread pool ); TSynLog.Add.Log(sllInfo, 'HTTP server started on :8080'); end; procedure TMyDaemon.Stop; begin FreeAndNil(HttpServer); FreeAndNil(DB); FreeAndNil(Model); end; ``` -------------------------------- ### Run JSON-RPC Demo (Default Server) Source: https://github.com/synopse/mormot2/blob/master/ex/ThirdPartyDemos/dmvc-ai/57-jsonrpc/README.md Starts the JSON-RPC demo. By default, it runs in server mode. ```bash JsonRpcDemo ``` -------------------------------- ### Install Windows Service Source: https://github.com/synopse/mormot2/blob/master/ex/ThirdPartyDemos/dmvc-ai/43-windows_service/README.md Command to install the mORMot2 Windows Service. ```cmd 43-windows_service.exe /install ``` -------------------------------- ### mORMot2 Application Initialization Source: https://github.com/synopse/mormot2/blob/master/ex/ThirdPartyDemos/dmvc-ai/37-loggergui/README.md Demonstrates how to initialize a VCL application with mORMot2's TSynLog, configuring logging levels and thread handling. ```pascal program LoggerGUISample; uses Vcl.Forms, mormot.core.log, MainFormU; begin TSynLog.Family.Level := LOG_VERBOSE; TSynLog.Family.PerThreadLog := ptIdentifiedInOneFile; Application.CreateForm(TMainForm, MainForm); end; ``` -------------------------------- ### JSON-RPC 2.0 Example Response Source: https://github.com/synopse/mormot2/blob/master/ex/ThirdPartyDemos/dmvc-ai/57-jsonrpc/README.md An example of a JSON-RPC 2.0 response containing the result of an operation. ```json { "result": 15 } ``` -------------------------------- ### SQLite3 Database Replication Setup Source: https://github.com/synopse/mormot2/blob/master/docs/mORMot2-SAD-Chapter-20.md Demonstrates setting up a master and replica SQLite3 database servers for read-only access on replicas. This is a basic setup for database replication. ```pascal // Master server MasterServer := TRestServerDB.Create(Model, 'master.db3'); // Replica servers (read-only) ReplicaServer := TRestServerDB.Create(Model, 'replica.db3'); ReplicaServer.DB.OpenV2('replica.db3', SQLITE_OPEN_READONLY); ``` -------------------------------- ### Log File Content Example Source: https://github.com/synopse/mormot2/blob/master/ex/ThirdPartyDemos/dmvc-ai/36-logging/README.md An example of the content found within the generated log file. ```text 20251220 14305045 info This is an info log [tag:log1] 20251220 14305045 warn This is a warn log [tag:log1] 20251220 14305045 debug This is a debug log [tag:log2] 20251220 14305045 EXC This is an error log [tag:log2] 20251220 14305045 fail This is a fatal log [tag:log3] ``` -------------------------------- ### Run the Executable Source: https://github.com/synopse/mormot2/blob/master/ex/ThirdPartyDemos/dmvc-ai/44-servercontainer/README.md Execute the compiled application to start the server container. ```cmd 44-servercontainer.exe ``` -------------------------------- ### Build DLL for Server in DLL Sample Source: https://github.com/synopse/mormot2/blob/master/ex/ThirdPartyDemos/dmvc-ai/docs/DEPLOYMENT-SAMPLES.md Compiles the DLL for the 'Server in DLL' sample. Ensure you are in the correct directory. ```bash dcc32 dll\ServerDLL.dpr ``` -------------------------------- ### Console Output Example Source: https://github.com/synopse/mormot2/blob/master/ex/ThirdPartyDemos/dmvc-ai/36-logging/README.md Example of the expected console output when running the mORMot2 logging demo. ```text mORMot2 Basic Logging Sample ============================ This sample demonstrates TSynLog basic usage Port of: DMVCFramework samples/Logger Logs will be written to: W:\...\LoggingSample 20251220_143045.log INFO: This is an info log [tag:log1] WARN: This is a warn log [tag:log1] DEBUG: This is a debug log [tag:log2] ERROR: This is an error log [tag:log2] FATAL: This is a fatal log [tag:log3] All logs written successfully! Check the log file: W:\...\LoggingSample 20251220_143045.log Press [Enter] to exit ``` -------------------------------- ### Test Get All Greetings API Source: https://github.com/synopse/mormot2/blob/master/ex/ThirdPartyDemos/dmvc-ai/02-console_sample/README.md Send a GET request to retrieve all greetings from the REST API. ```bash curl http://localhost:8080/GreetingService/GetAllGreetings ``` -------------------------------- ### Run the Server Source: https://github.com/synopse/mormot2/blob/master/ex/ThirdPartyDemos/dmvc-ai/01-basicdemo_server/README.md Execute the compiled server application. The server will start on http://localhost:8080. ```bash ./01-basicdemo_server.exe ``` -------------------------------- ### Start Windows Service Source: https://github.com/synopse/mormot2/blob/master/ex/ThirdPartyDemos/dmvc-ai/43-windows_service/README.md Command to start the mORMot2 Windows Service using the Windows Service Manager. ```cmd net start "mORMot2 REST Service" ``` -------------------------------- ### Build and Run Server Source: https://github.com/synopse/mormot2/blob/master/ex/ThirdPartyDemos/dmvc-ai/33-jsonwebtoken_roleauth/README.md Steps to compile and launch the JWT role-based authentication server. ```bash cd /mnt/w/mORMot2/ex/dmvc/33-jsonwebtoken_roleauth delphi-compiler.exe JwtRoleAuthServer.dproj --config=Debug --platform=Win32 bin\Win32\Debug\JwtRoleAuthServer.exe ``` -------------------------------- ### Navigate to Basic Demo Server Directory Source: https://github.com/synopse/mormot2/blob/master/ex/ThirdPartyDemos/dmvc-ai/GETTING-STARTED.md Changes the current directory to the '01-basicdemo_server' sample, which is the starting point for mORMot2 DMVC development. ```bash cd /mnt/w/mORMot2/ex/dmvc/01-basicdemo_server ``` -------------------------------- ### JSON-RPC 2.0 Example Request Source: https://github.com/synopse/mormot2/blob/master/ex/ThirdPartyDemos/dmvc-ai/57-jsonrpc/README.md An example of a JSON-RPC 2.0 POST request to a CalculatorService for an Add operation. ```json POST /CalculatorService/Add Content-Type: application/json { "a": 10, "b": 5 } ``` -------------------------------- ### Profiling Log Output Example Source: https://github.com/synopse/mormot2/blob/master/ex/ThirdPartyDemos/dmvc-ai/46-profiling/README.md An example of the detailed timing information captured in the profiling log file. ```log 20231220 10:15:30.123 + Enter TProfilingApi.Index 20231220 10:15:30.123 + Enter TProfilingApi.ProcA 20231220 10:15:30.123 + Enter TProfilingApi.ProcB 20231220 10:15:30.123 + Enter TProfilingApi.ProcA ... 20231220 10:15:30.456 - Leave TProfilingApi.ProcB (333.12ms) 20231220 10:15:30.456 - Leave TProfilingApi.ProcA (333.45ms) 20231220 10:15:30.456 - Leave TProfilingApi.Index (333.89ms) ``` -------------------------------- ### Running a Test Suite in Pascal Source: https://github.com/synopse/mormot2/blob/master/docs/mORMot2-SAD-Chapter-25.md Illustrates the basic structure for creating and running a test suite. This is the entry point for executing a collection of tests. ```pascal var Suite: TMyTestSuite; begin Suite := TMyTestSuite.Create('Test Suite'); try Suite.Run; finally Suite.Free; end; end; ``` -------------------------------- ### Perform GET Request with HTTPie Source: https://github.com/synopse/mormot2/blob/master/ex/ThirdPartyDemos/dmvc-ai/GETTING-STARTED.md Basic usage of HTTPie to send a GET request to a specified URL. ```bash # GET request http localhost:8080/BasicDemoApi/HelloWorld ``` -------------------------------- ### TEcdheProtocol Client and Server Setup Source: https://github.com/synopse/mormot2/blob/master/docs/mORMot2-SAD-Chapter-23.md Demonstrates setting up both server and client instances of TEcdheProtocol for mutual authentication using ECC certificates. Requires certificate files and passwords. ```pascal uses mormot.crypt.ecc; var ServerProtocol, ClientProtocol: IProtocol; ServerCert: TEccCertificateSecret; ClientCert: TEccCertificateSecret; Handshake1, Handshake2, Handshake3: RawUtf8; begin // Server setup (TEcdheProtocolServer) ServerCert := TEccCertificateSecret.CreateFromSecureFile('server.private', 'pwd'); ServerProtocol := TEcdheProtocol.Create(authMutual, nil, ServerCert); // Client setup (TEcdheProtocolClient) with server's public key in PKI ClientCert := TEccCertificateSecret.CreateFromSecureFile('client.private', 'pwd'); ClientProtocol := TEcdheProtocol.Create(authMutual, nil, ClientCert); // Three-way handshake ClientProtocol.ProcessHandshake('', Handshake1); // Client hello ServerProtocol.ProcessHandshake(Handshake1, Handshake2); // Server response ClientProtocol.ProcessHandshake(Handshake2, Handshake3); // Client finish // Now encrypted communication is possible var Plain := 'Secret message'; var Encrypted: RawByteString; ClientProtocol.Encrypt(Plain, Encrypted); ServerProtocol.Decrypt(Encrypted, Plain); end; ```