### Initialize Total.js, Register Route, and Launch Server Source: https://docs.totaljs.com/total5/IbGpBV2Mx61f This JavaScript code snippet demonstrates the initialization of the Total.js framework, registers a simple GET route for the root path that returns a JSON message, and sets up a WebSocket route. Finally, it launches the web server. Ensure Total.js is installed via npm. ```javascript // Initializes Total.js framework 5 require('total5'); // Registers a route ROUTE('GET /', function($) { // $ {Controller} $.json({ message: 'Hello world' }); }); // Registers a WebSocket route ROUTE('SOCKET /', function($) { // $ {Controller} $.on('open', function(client) { client.send({ message: 'Hello' }); }); $.on('message', function(client, message) { console.log(message); }); }); // Launches a web server Total.http({ load: 'none' }); ``` -------------------------------- ### Install Dependencies for LessCode Source: https://docs.totaljs.com/total5/IbGpBV2Mx61f This command installs the necessary Node.js dependencies for the LessCode project. It is a one-time setup step executed within the LessCode directory. Requires Node.js and npm to be installed. ```bash # This can be executed only once: $ cd lesscode $ npm install ``` -------------------------------- ### Run LessCode Application Source: https://docs.totaljs.com/total5/IbGpBV2Mx61f These commands execute the LessCode application after dependencies have been installed. Users can choose to run the app directly using `node index.js` or via an npm script with `npm start`. This starts the local development server. ```bash $ node index.js # or # $ npm start ``` -------------------------------- ### Basic Configuration Setup in Total.js Source: https://docs.totaljs.com/total5/IbGpBV1fx60f Demonstrates a basic configuration file setup in Total.js, including common keys like name, version, and author. The configuration is read-only and loaded during framework initialization. ```Total.js name : My Web Site name version : 1.01 author : Peter Sirka secret : mySECRET1.01 default_image_quality : 96 :# Additional configuration keys and values... ``` -------------------------------- ### Example Resource File Structure Source: https://docs.totaljs.com/total5/IbGpBV1tx60f This is an example of a plain-text resource file with key-value pairs. Comments are supported and values can include HTML tags. Resource files are loaded into memory and are read-only. ```resource key1 : value1 // comment key2 : value2 key3 : with the tag ``` -------------------------------- ### Type Detection Examples in Total.js Configuration Source: https://docs.totaljs.com/total5/IbGpBV1fx60f Provides examples of how Total.js detects and converts configuration values into numbers and booleans, highlighting cases where automatic conversion does not occur due to formatting. ```Total.js will_be_number_1 : 123 # Parsed as number will_be_number_2 : 0.3 # Parsed as number (float) will_not_be_number_1 : 0123 # Not parsed as a number due to leading zero will_not_be_number_2 : 0,3 # Not parsed due to comma will_be_boolean_1 : true # Parsed as boolean will_be_boolean_2 : false # Parsed as boolean ``` -------------------------------- ### WebSocket Client Setup - Total.js JavaScript Source: https://docs.totaljs.com/total5/IbGpBV2Dx60f Demonstrates basic WebSocketClient usage for connecting to WebSocket servers and handling connection events. Shows connection setup, event listeners for open/close/error/message events, and basic message handling. Requires WebSocketClient module and valid WebSocket server endpoint. ```javascript WEBSOCKETCLIENT(function(client) { // client.connect(url, [protocol], [origin]); client.connect('ws://127.0.0.1:8000/'); client.on('open', function() { console.log('OPEN'); }); client.on('close', function() { console.log('CLOSE'); }); client.on('error', function(e) { console.log('ERROR', e); }); client.on('message', function(message) { console.log('MESSAGE', message); }); }); ``` -------------------------------- ### Module-Specific Configuration in Total.js Source: https://docs.totaljs.com/total5/IbGpBV1fx60f Illustrates how to define custom configuration options for modules in Total.js. This example configures a 'monitor' module with a specific URL. ```Total.js :# Custom configuration for a module module#monitor (Object) : { url: '/mymonitor/' } ``` -------------------------------- ### Controller Method Examples in Total.js Source: https://docs.totaljs.com/total5/IbGpBV1dx60f Illustrates common controller methods in Total.js for sending responses and managing requests. This includes sending plain text, JSON, HTML, files, and handling redirects. ```javascript ____controller.text(value); ____controller.json(obj, [beautify], [replacer]); ____controller.html(body, [headers]); ____controller.file(filename, [download], [headers], [callback]); ____controller.redirect(url, [permanent]); ``` -------------------------------- ### Use Total.js as utility script Source: https://docs.totaljs.com/total5/IbGpBV2Lx60f Example showing how to use Total.js framework functionality in standalone utility scripts. Demonstrates slug conversion functionality. ```javascript // This code includes Total.js parts to your script require('total5'); console.log('Peter Širka'.slug()); // Output: peter-sirka ``` -------------------------------- ### Run Total.js web application Source: https://docs.totaljs.com/total5/IbGpBV2Lx60f Start script for running a Total.js web application. Includes configuration options for IP, port, unix socket, cluster, and more. Supports both debug and release modes. ```javascript // =================================================== // Total.js v5 start script // https://www.totaljs.com // =================================================== require('total5'); const options = {}; // options.ip = '127.0.0.1'; // options.port = parseInt(process.argv[2]); // options.unixsocket = PATH.join(F.tmpdir, 'app_name.socket'); // options.unixsocket777 = true; // options.config = { name: 'Total.js' }; // options.sleep = 3000; // options.inspector = 9229; // options.watch = ['private']; // options.livereload = 'https://yourhostname'; // options.watcher = true; // enables watcher for the release mode only controlled by the app `F.restart()` // options.edit = 'wss://www.yourcodeinstance.com/?id=projectname' options.release = process.argv.includes('--release'); // Service mode: options.servicemode = process.argv.includes('--service') || process.argv.includes('--servicemode'); // options.servicemode = 'definitions,modules,config'; // Cluster: // options.tz = 'utc'; // options.cluster = 'auto'; // options.limit = 10; // max 10. threads (works only with "auto" scaling) Total.run(options); ``` -------------------------------- ### Total.js Chunker Usage Example Source: https://docs.totaljs.com/total5/IbGpBV1xx60f Demonstrates how to use the Total.js Chunker to temporarily store and process imported data. It shows initializing a chunker, writing data from a stream, and iterating through the stored chunks. ```javascript var chunker = U.chunker('products', 50); // chunker === instance somestream.on('data', U.streamer('', '', function(value, index) { var product = value.parseXML(); // The chunker creates multiple files with a maximum count of chunks/items (in this case: 50 products) chunker.write(product); })); somestream.on('end', function() { // Flushs buffer chunker.end(); chunker.each(function(items, next, index) { console.log(chunker.percentage); // here we can update DB // .... // .... // Read next items next(); }, function() { // This method is called if the chunker doesn't contain any other items (optional). // Cleans up hdd (removes all files) and memory chunker.destroy(); }); }); ``` -------------------------------- ### Accessing Configuration Values in Total.js Source: https://docs.totaljs.com/total5/IbGpBV1fx60f Shows how to read configuration values in a Total.js application using the CONF object. This example accesses the 'name' and 'version' keys from the config file. ```JavaScript console.log(CONF.$name); // Outputs: "My Web Site name" console.log(CONF.version); // Outputs: "1.01" ``` -------------------------------- ### Create and Send Email Message Source: https://docs.totaljs.com/total5/IbGpBV1ix61f Shows how to create an email message using Mail.create() and configure various properties. The example demonstrates chaining methods to set recipients, attachments, and other email properties before sending. Supports both direct sending and queuing through callback functions. ```javascript // Creating a new mail message var message = Mail.create('Welcome', 'Hello World'); // Configuring message properties message.to('recipient@example.com', 'Recipient Name'); message.from('sender@example.com', 'Sender Name'); message.attachment('path/to/file.pdf', 'document.pdf'); // Sending the message message.send2(); ``` -------------------------------- ### Load, Resize, Grayscale, and Save Image with Total.js Source: https://docs.totaljs.com/total5/IbGpBV1jx60f This example demonstrates loading an image from a readable stream, resizing it to fit within a 200x200 area centered, converting it to grayscale, and then saving the modified image to a file. It utilizes the global `Image` object provided by the Total.js framework. ```javascript var image = Image.load(fs.createReadStream('/users/petersirka/desktop/header.jpg')); image.resizeCenter(200, 200); image.grayscale(); image.save('filename'); ``` -------------------------------- ### Define a route and a custom operation for loading lookup data (JavaScript) Source: https://docs.totaljs.com/total5/IbGpBV22x61f Shows how to set up a GET route that maps to a custom operation 'cl'. The operation queries the database for country, currency, and gender data, assigns them to response properties, and invokes the callback. Demonstrates use of DBMS, find, set, and $.callback. ```JavaScript exports.install = function() { ROUTE('GET /api/cl/ * --> cl'); }; NEWOPERATION('cl', function($) { var db = DBMS(); db.find('cl_country').set('countries'); db.find('cl_currency').set('currencies'); db.find('cl_gender').set('genders'); db.callback($.callback); }); ``` -------------------------------- ### Serve Specific Files with Total.js File Routing Source: https://docs.totaljs.com/total5/IbGpBV27x60f Provides examples of Total.js file routing for serving specific types of files, such as all documents or JPEG images, from designated paths. ```javascript // Example // File: /controllers/example.js exports.install = function() { ROUTE('FILE /documents/*.*', handle_documents); ROUTE('FILE /images/*.jpg', handle_images); }; function handle_documents($) { // "$" is a "Controller" instance $.file('/path/to/file.pdf'); } function handle_images($) { // "$" is a "Controller" instance // your code } ``` -------------------------------- ### Translated Resource File Example (Comment) Source: https://docs.totaljs.com/total5/IbGpBV2ex61f This shows a translated version of the resource file, where the original English text has been replaced with localized content (e.g., Slovak). The hashed keys remain the same, ensuring the translations are correctly mapped. ```comment // Total.js translation file // Created: 2020-12-04 10:32 // index.html T1c4854 : Titulok T1y5ksfx : Ahoj svet! Tpfol3 : Total.js je webový framework pre Node.js // IMPORTANT: This line was created manually message : Priame čítanie ``` -------------------------------- ### Total.js API Request Example Source: https://docs.totaljs.com/total5/IbGpBV2Zx60f Illustrates the structure of a POST request to a Total.js API endpoint. It includes the 'schema' field to specify the operation and dynamic arguments, and an optional 'data' object. ```json POST /api/ Content-Type: application/json { "schema": "schema_name/{dynamic_arg_1}/{dynamic_arg_2}?query=arguments", "data": {} } ``` -------------------------------- ### Register and Run FlowStream Components in JavaScript Source: https://docs.totaljs.com/total5/IbGpBV2bx60f This JavaScript example demonstrates registering custom FlowStream components for text transformations (uppercase and reverse), a debug component to log output, and defining a flow schema to connect them. It processes input data 'Hello world!' through the components and destroys the flow after 2 seconds. Requires Total.js FlowStream library. Inputs include component names and JSON schema; outputs are processed data to console. Limitations: Assumes synchronous data handling and single-threaded execution. ```javascript var flow = FLOWSTREAM(); // is the same as FLOWSTREAM('default'); flow.register('uppercase', function(instance) { instance.inputs = [{ id: 'input', name: 'Input' }]; instance.outputs = [{ id: 'output', name: 'Output' }]; instance.message = function(msg) { msg.data = msg.data.toUpperCase(); // sends transformed data to output "0" msg.send('output'); }; }); flow.register('reverse', function(instance) { instance.inputs = [{ id: 'input', name: 'Input' }]; instance.outputs = [{ id: 'output', name: 'Output' }]; instance.message = function(msg) { var arr = msg.data.split(''); arr.reverse(); msg.data = arr.join(''); // sends transformed data to output "0" msg.send('output'); }; }); flow.register('debug', function(instance) { instance.inputs = [{ id: 'input', name: 'Input' }]; instance.message = function(msg) { console.log(msg.data); // IMPORTANT: Destroys message msg.destroy(); }; }); flow.use(`{ "com1": { "component": "uppercase", "connections": { "output": [{ "id": "com2", "index": "input" }] } }, "com2": { "component": "reverse", "connections": { "output": [{ "id": "com3", "index": "input" }] } }, "com3": { "component": "debug" } }`, function() { flow.trigger('com1__0', 'Hello world!'); setTimeout(() => flow.destroy(), 2000); }); ``` -------------------------------- ### File Routing API Source: https://docs.totaljs.com/total5/IbGpBV27x60f This section covers file routing, which is optimized for serving static files, potentially with dynamic generation. File routes only support the GET method and can be defined using wildcards to match file patterns. ```APIDOC ## File Routing ### Description Processes and serves static files, optimized for performance. File routing only supports the `GET` method and can utilize wildcards for matching file paths. ### Method GET ### Endpoint Examples: `/relative/url/*.jpg` `/documents/*.*` `/images/*.jpg` ### Parameters No explicit path or query parameters are defined in the basic `ROUTE` syntax for file routing. ### Request Body Not applicable for file routing (GET method). ### Request Example ```javascript // In /controllers/example.js exports.install = function() { ROUTE('FILE /documents/*.*', handle_documents); ROUTE('FILE /images/*.jpg', handle_images); }; function handle_documents($) { $.file('/path/to/file.pdf'); } function handle_images($) { // your image processing code } ``` ### Response #### Success Response (200) Serves the requested file. #### Response Example Binary content of the requested file. ``` -------------------------------- ### Generated Translation Resource File (Comment) Source: https://docs.totaljs.com/total5/IbGpBV2ex61f An example of the `translate.resource` file generated by the `total5 --translate` command. It contains hashed keys (e.g., T1c4854) mapping to the original translatable text found in the views. ```comment // Total.js translation file // Created: 2020-12-04 10:32 // index.html T1c4854 : Title T1y5ksfx : Hello world! Tpfol3 : Total.js is web application framework for Node.js // IMPORTANT: This line was created manually message : Direct reading ``` -------------------------------- ### Generate Localization Dictionary (Shell) Source: https://docs.totaljs.com/total5/IbGpBV2ex61f This command-line instruction shows how to generate a localization dictionary file using the Total.js CLI. After installing Total.js globally, the `--translate` flag scans the project for translatable strings and creates a resource file. ```shell $ cd myapp $ total5 --translate ``` -------------------------------- ### Compiling and Using Flow Counter Component in JavaScript Source: https://docs.totaljs.com/total5/It2iik1cT61f This example shows how to define a Flow component using a script tag, compile it with NEWCOMPONENT, create an instance, and send data to it. It demonstrates basic component structure with exports, message handling, and status updates. Requires Total.js environment with NEWCOMPONENT available; no external dependencies. Inputs are message data, outputs include status objects and potential errors. ```javascript var COUNTER = ``; (async function() { // Compile a source-code var Counter = await NEWCOMPONENT(COUNTER); // Create instance var counter = Counter.create({ custom: 'options' }); // Send data setInterval(() => counter.input('input', { custom: 'data' }), 1000); })(); ``` -------------------------------- ### Dynamic Content Routing API Source: https://docs.totaljs.com/total5/IbGpBV27x60f This section details how to define routes for dynamic content, allowing you to map HTTP requests to controller actions for generating responses like JSON or views. It supports standard HTTP methods and includes examples of REST API routing with authorization. ```APIDOC ## Dynamic Content Routing ### Description Defines routes for dynamic content generation, mapping HTTP requests to controller actions. Supports GET, POST, PUT, PATCH, DELETE. Routes should not contain file extensions. ### Method GET, POST, PUT, PATCH, DELETE ### Endpoint Examples: `/` `/api/users/` `/api/users/{id}/` ### Parameters No explicit path or query parameters are defined in the basic `ROUTE` syntax, but controller actions can define their own parameters (e.g., `$`). ### Request Body Not explicitly defined in routing syntax, but expected for methods like POST, PUT, PATCH. ### Request Example ```javascript // In /controllers/example.js exports.install = function() { // Example of REST API routing with authorization ('+') ROUTE('+GET /api/users/ --> Users/query'); ROUTE('+GET /api/users/{id}/ --> Users/read'); ROUTE('+POST /api/users/ --> Users/insert'); ROUTE('+PUT /api/users/{id}/ --> Users/update'); ROUTE('+PATCH /api/users/{id}/ --> Users/patch'); ROUTE('+DELETE /api/users/ --> Users/remove'); }; ``` ### Response #### Success Response (200) Depends on the controller action (e.g., JSON data, rendered view). #### Response Example ```json { "message": "User data retrieved successfully" } ``` ## File Upload Routing ### Description Handles file uploads via POST requests. Specifies maximum payload size and processes uploaded files using the `HttpFile` object. ### Method POST ### Endpoint `/upload/` ### Parameters #### Query Parameters None specified. #### Request Body File upload data. ### Request Example ```javascript // In /controllers/upload.js exports.install = function() { ROUTE('POST /upload/ @upload <1MB', myupload); // Max. 1 MB payload size }; function myupload($) { console.log($.files); // $.files contains Array of HttpFile $.success(); } ``` ### Response #### Success Response (200) Indicates successful processing of the upload. #### Response Example ```json { "success": true } ``` ``` -------------------------------- ### Chained API Call with Callback in Total.js JavaScript Source: https://docs.totaljs.com/total5/IbGpBV2ox61f This one-line example creates an API call and chains callback for success and error handling. It depends on the Total.js API instance and console.log for output. Parameters include service, method, and data; it handles responses via provided functions with potential error messaging. ```JavaScript API('Payments', 'payments_insert', { amount: 100 }).callback(console.log).error('A trouble with API'); ``` -------------------------------- ### Define Actions with Schema in Total.js Source: https://docs.totaljs.com/total5/IbGpBV1ux61f This example demonstrates how to define actions in Total.js using NEWACTION with schema declarations for validating and transforming incoming data. It includes two actions: one for reading user accounts and another for creating them. The actions handle parameters, query data, and input models correctly based on the schema. ```javascript NEWACTION('Account/read', { name: 'Read user account', params: '*id:UID', query: 'output:{simple|detailed}', action: function($, model) { // "model" is alias for "$.model" // $.params {Object} // $.query {Object} // $.files {Array Object} // $.user {Object} // $.model {Object} console.log($.params); // output: { id: '...' } console.log($.query); // output: { output: 'detailed' } $.success(); }; }); NEWACTION('Account/create', { name: 'Create user account', input: '*name:String, *email:Email', action: function($, model) { // "model" is alias for "$.model" // $.params {Object} // $.query {Object} // $.files {Array Object} // $.user {Object} // $.model {Object} console.log(model); // output: { name: 'Peter', email: 'info@totaljs.com' } $.success(); }; }); ``` -------------------------------- ### Configure and Run Total.js Cluster Mode Source: https://docs.totaljs.com/total5/IbGpBV2Jx60f Enables multi-threading for Total.js applications using Node.js Cluster with the total5 framework. Configuration via options object: 'auto' enables dynamic scaling up to cluster_limit threads, while a number specifies a fixed count. WebSocket clients are isolated per instance. Note the fixed thread example contains a redundant line that would override the fixed value. ```javascript require('total5'); const options = {}; options.cluster = 'auto'; options.cluster_limit = 10; options.release = true; Total.run(options); ``` ```javascript require('total5'); const options = {}; options.cluster = 5; // opens 5 threads options.cluster = 'auto'; options.release = true; Total.run(options); ``` -------------------------------- ### Create GET request with RESTBuilder Source: https://docs.totaljs.com/total5/IbGpBV2Cx61f Creates a RESTBuilder instance with GET method. Data can be passed as query parameters or included in the URL. This method is ideal for retrieving data from APIs. ```javascript RESTBuilder.GET('https://www.totaljs.com').callback(console.log); ``` -------------------------------- ### Initialize OpenClient - Total.js WebSocket Wrapper Source: https://docs.totaljs.com/total5/IbGpBV2hx60f Demonstrates how to create and initialize an OpenClient instance with a URL and token. The client automatically merges same connections and handles message delegation. Requires Total.js v4+0.0.50 and a valid token for authentication. ```javascript var client = OPENCLIENT('https://opendb.yourserver.com/?token=123456'); // On message delegate client.message(function(msg) { // @msg {Object} }); ``` -------------------------------- ### COUNT /db.count Source: https://docs.totaljs.com/total5/IbGpBV2kx61f Get the count of records in the specified database table. ```APIDOC ## COUNT /db.count ### Description Get the count of records in the specified database table. ### Method COUNT ### Endpoint /db.count(name) ### Parameters #### Path Parameters - **name** (string) - Required - Name of the database table #### Request Example ```javascript db.count('users'); ``` ### Response #### Success Response - **count** (number) - Number of records in the table #### Response Example ```json { "count": 42 } ``` ``` -------------------------------- ### FREE /db.free Source: https://docs.totaljs.com/total5/IbGpBV2kx61f Release or free database resources and connections. ```APIDOC ## FREE /db.free ### Description Release or free database resources and connections. ### Method FREE ### Endpoint /db.free() #### Request Example ```javascript db.free(); ``` ### Response #### Success Response Returns resource release confirmation. ``` -------------------------------- ### Escaping HTML in views Source: https://docs.totaljs.com/total5/IbGpBV29x60f This example shows how the view engine automatically escapes HTML entities and how to render raw HTML using the ! syntax. ```html @{repository.tag = 'Hello World'}
ESCAPED: @{repository.tag}
RAW: @{!repository.tag}
``` -------------------------------- ### Database Initialization Source: https://docs.totaljs.com/total5/IbGpBV2kx61f Initialize database instance for performing database operations in Total.js platform. ```APIDOC ## Database Initialization ### Description Initialize a database instance to perform various database operations in the Total.js platform. ### Method DATABASE INITIALIZATION ### Endpoint DB() ### Parameters #### Request Example ```javascript var db = DB(); ``` ### Response #### Success Response Returns database instance object for performing database operations. ``` -------------------------------- ### Setting up controller with repository and model Source: https://docs.totaljs.com/total5/IbGpBV29x60f This snippet shows how to pass data from a controller to views using both repository and model. The repository data is available globally while model data is scoped to the specific view. ```javascript exports.install = function() { ROUTE('GET /', view_homepage); }; function view_homepage() { var self = this; self.repository.firstname = 'Peter'; self.view('my-view-name', { firstname: 'Lucia' }); } ``` -------------------------------- ### Client-side error handling in Total.js Source: https://docs.totaljs.com/total5/IbGpBV26x61f Illustrates client-side error detection in Total.js using AJAX. The example checks the response for errors and logs them to the console. ```JavaScript AJAX('GET /api/errors/', function(response) { // Determines error if (response instanceof Array && response.length && response[0].error) console.log(response); }); ``` -------------------------------- ### Using $.invalid in Total.js Controllers Source: https://docs.totaljs.com/total5/IbGpBV26x61f Shows how to use $.invalid() within Total.js controllers to handle errors. The example conditionally returns an error message. ```JavaScript function action($) { if (true) { $.invalid('@(Invalid operation)'); return; } // Do something } ``` -------------------------------- ### Using $.invalid in Total.js Actions Source: https://docs.totaljs.com/total5/IbGpBV26x61f Demonstrates how to use $.invalid() within Total.js actions to respond with an error. The example checks a condition and returns an error if true. ```JavaScript NEWACTION('name', { action: function($) { if (true) { $.invalid('@(Invalid operation)'); return; } // Do something } }); ``` -------------------------------- ### OpenClient Methods - Connection and Communication Source: https://docs.totaljs.com/total5/IbGpBV2hx60f Shows the available OpenClient methods including connection management, command sending, and RPC functionality. Methods support optional filters and timeouts for advanced use cases. All methods are part of the Total.js OpenClient wrapper API. ```javascript client.close(); client.cmd(msg, [filter], [timeout]); client.message(fn); client.online(fn); client.rpc(msg, [callback], [filter], [timeout]); ``` -------------------------------- ### Using sections in views Source: https://docs.totaljs.com/total5/IbGpBV29x60f This example shows how to define sections in views that can be rendered outside the main body content. Sections allow content to be injected into specific locations in layouts. ```html @{section footer}
THIS IS FOOTER FROM THE VIEW
@{end}

Homepage


``` -------------------------------- ### Basic API Call Creation in Total.js JavaScript Source: https://docs.totaljs.com/total5/IbGpBV2ox61f The API() method initializes an API call instance using a service name, method name, and parameters object. It requires the Total.js framework and returns an instance for further method chaining. Inputs are strings for service and method, and an object for data; outputs depend on the service implementation with no specified limitations. ```JavaScript var api = API('Payments', 'payments_insert', { amount: 100 }); ``` -------------------------------- ### Defining a layout with body and sections Source: https://docs.totaljs.com/total5/IbGpBV29x60f This HTML snippet shows how to create a layout template with a body placeholder and section definitions. The layout includes meta tags, imports, and a footer view. ```html @{meta} @{import('meta', 'default.css', 'default.js', 'favicon.ico')}
@{section('panel')} @{body}
@{view('footer')} ``` -------------------------------- ### Initialize and use multiple PostgreSQL databases with QueryBuilder Source: https://docs.totaljs.com/total5/IbGpBV2jx60f This snippet shows how to initialize and manage multiple PostgreSQL database connections using the QueryBuilder. It demonstrates setting up different database instances with unique connection strings and then querying tables from these specific databases by prefixing the table name with the database alias. This is useful for applications managing data across several PostgreSQL instances. ```javascript const QPG = require('querybuilderpg'); QPG.init('default', 'postgresql://user:password@localhost:5432/database1'); QPG.init('db2', 'postgresql://user:password@localhost:5432/database2'); QPG.init('db3', 'postgresql://user:password@localhost:5432/database3'); DATA.find('tbl_user').callback(console.log); // --> default DATA.find('db2/tbl_user').callback(console.log); // --> db2 DATA.find('db3/tbl_user').callback(console.log); // --> db3 ``` -------------------------------- ### Mail Module FAQ Source: https://docs.totaljs.com/total5/IbGpBV1ix61f Frequently asked questions regarding sending mail messages and configuration. ```APIDOC ## Mail Module FAQ ### Description Answers to common questions about using the Total.js Mail module. ### Questions - **How can I send mail messages?** Configure your SMTP server in the `config` file and then use the `MAIL('recipient', 'subject', 'template_path')` global function or the `Mail.send()` / `Mail.send2()` methods. - **What is the configuration for Gmail, Office or Zoho?** You will need to find the specific SMTP server details (host, port, security settings) for your email provider. For services like Gmail, you might need to enable 'less secure app access' or generate an 'app password' if 2-factor authentication is enabled. Consult your email provider's documentation for their SMTP settings. ``` -------------------------------- ### Creating views with meta and nested views Source: https://docs.totaljs.com/total5/IbGpBV29x60f This HTML snippet demonstrates how to define views with meta information and embed other views. It shows both single-line and multi-line view commands. ```html @{meta('Title', 'Description (optional)', 'Keywords (optional)')}
Hello World!
@{view('products', [{ name: 'A', price: 23.32 }, { name: 'B', price: 32.10 }])} @{view('users', model)} @{view('products', [{ name: 'A', price: 23.32 }, { name: 'B', price: 32.10 }, { name: 'C', price: 15.22 }])} ``` -------------------------------- ### Handling 'end' Event for FlowMessage in Total.js Source: https://docs.totaljs.com/total5/IbGpBV2cx61f This example shows how to attach an event listener to the 'end' event of a FlowMessage. This is useful for performing actions or cleanup when a message has been fully processed or its lifecycle is ending within the Total.js Flow. ```javascript flowmessage.on('end', function(msg) { // Code to execute when the message ends }); ``` -------------------------------- ### Total.js File Routing for Static Assets Source: https://docs.totaljs.com/total5/IbGpBV27x60f Illustrates how to implement file routing in Total.js to serve static files, including wildcard matching for specific file types or all files within a directory. ```javascript ROUTE('FILE /relative/url/*.jpg', action_fn); ``` -------------------------------- ### Route to static files in TotalJS Total5 Source: https://docs.totaljs.com/total5/IbGpBV29x60f Illustrates how to create routes to static files like JavaScript and CSS, including merging multiple files. ```html @{import('ui.js')} @{import('ui.css')} @{import('default.css + ui.css')} ``` -------------------------------- ### Handling Service Delegate for Component in JavaScript Source: https://docs.totaljs.com/total5/It2iik1cT61f Example of registering a service delegate that calls component.service on all instances when a 'service' event occurs. This triggers maintenance or periodic actions in Flow components. Depends on Total.js ON event system and component instance; no direct I/O specified. ```javascript ON('service', counter => component.service(counter)); ``` -------------------------------- ### Define and Run a Download Task in Total.js Source: https://docs.totaljs.com/total5/IbGpBV24x61f This JavaScript code defines a custom 'Download' task using the NEWTASK function. The task sequentially downloads content from provided URLs using RESTBuilder.GET. It includes error handling and manages asynchronous operations using callbacks and $.next(). The task is then executed using TASK('Download/init') with a list of URLs. ```javascript NEWTASK('Download', function(push) { push('init', function($) { // you can extend "$" by your needs: $.output = []; $.next('delay'); }); push('delay', function($) { setTimeout($.next2('download'), 1000); }); push('download', function($, value) { // value is alias for "$.value" var url = value.shift(); if (url == null) { // End of TaskBuilder and send the value to the callback $.end($.output); return; } RESTBuilder.GET(url).callback(function(err, response, output) { if (err) { // Unhandled error // Go back $.value.push(url); } else $.output.push(output.response); $.next('delay'); }); }); }); // Run task TASK('Download/init', function(err, response) { console.log(err, response); }, null, ['https://www.totaljs.com', 'https://www.google.com', 'https://nodejs.org']); ``` -------------------------------- ### Find data using QueryBuilder Source: https://docs.totaljs.com/total5/IbGpBV2jx60f This example demonstrates how to find data using the QueryBuilder's ORM for the TextDB driver. It filters data based on a specified field and value, then logs the result using a callback function. This is a basic usage pattern for querying embedded NoSQL data. ```javascript DATA.find('nosql/frameworks').where('id', 'Total.js').callback(console.log); ``` -------------------------------- ### Sample JSON output of the 'cl' operation Source: https://docs.totaljs.com/total5/IbGpBV22x61f Illustrates the response format returned by the 'cl' operation, containing arrays for countries, currencies, and genders. ```JSON { "countries": [...], "currencies": [...], "genders": [...] } ``` -------------------------------- ### Utils Object Documentation Source: https://docs.totaljs.com/total5/IbGpBV1hx60f This section details the properties and methods available within the Total.js Utils object. ```APIDOC ## Utils Object ### Description The `Utils` object (aliased as `U.`) in Total.js provides a comprehensive set of utility and helper methods for various programming tasks. ### Properties - **U.DAYS**: (Object) - Represents days of the week. - **U.MONTHS**: (Object) - Represents months of the year. - **U.success**: (Function) - Likely a function related to success indicators or callbacks. ### Methods - **U.atob(value)**: Decodes a Base64 encoded string. - **U.btoa(value)**: Encodes a string to Base64. - **U.chunker(name, [max])**: Splits a string or array into chunks. - **U.clone(source, [skip])**: Creates a deep clone of an object. - **U.combine([param..1], [param..2], [param..n])**: Combines multiple arguments into a single value or structure. - **U.connect(opt, callback)**: Establishes a connection with given options. - **U.convert62(number)**: Converts a number to a base 62 string. - **U.copy(source, [target])**: Copies properties from a source object to a target object. - **U.decodeURIComponent(value)**: Decodes a URI component encoded string. - **U.decrypt_crypto(type, key, buffer)**: Decrypts data using a specified crypto type and key. - **U.decrypt_data(value, key, [encode])**: Decrypts data using a key. - **U.decrypt_uid(value, [key])**: Decrypts a UID. - **U.destroystream(stream)**: Destroys a stream. - **U.diffarr(name, arr_db, arr_form)**: Compares two arrays and returns differences. - **U.distance(lat1, lon1, lat2, lon2)**: Calculates the distance between two geographical points. - **U.encrypt_crypto(type, key, buffer)**: Encrypts data using a specified crypto type and key. - **U.encrypt_data(value, key, [encode])**: Encrypts data using a key. - **U.encrypt_uid(value, [key])**: Encrypts a UID. - **U.etag(value, [version])**: Generates an ETag for a value. - **U.EventEmitter2(obj)**: Creates an EventEmitter instance. - **U.extend(target, source, [rewrite])**: Extends a target object with properties from a source object. - **U.filestreamer(filename, onbuffer, [onend], [buffer_size])**: (new) Reads a file in chunks. - **U.from62(val)**: Converts a base 62 string to a number. - **U.get(obj, path)**: Retrieves a value from an object using a path. - **U.getContentType(extension)**: Gets the MIME type for a file extension. - **U.getExtension(path)**: Gets the file extension from a path. - **U.getExtensionFromContentType(type)**: (new) Gets the file extension from a MIME type. - **U.getName(path)**: Gets the filename from a path. - **U.groupify(id, [length])**: Groups items by an ID. - **U.guid([max])**: Generates a GUID. - **U.httpstatus(code, [addCode])**: Returns an HTTP status message for a given code. - **U.isDate(value)**: Checks if a value is a valid date. - **U.join(path)**: Joins path segments. - **U.json2replacer(key, value)**: A replacer function for JSON stringification. - **U.keywords(content, [forSearch], [alternative], [max_count], [max_length], [min_length])**: Extracts keywords from content. - **U.link(path1, path2, pathN)**: Joins multiple path segments into a single path. - **U.ls(path, callback, [filter])**: Lists directory contents asynchronously. - **U.ls2(path, callback, [filter])**: An alternative method for listing directory contents asynchronously. - **U.minify_css(value)**: Minifies CSS code. - **U.minify_html(value)**: Minifies HTML code. - **U.minify_js(value)**: Minifies JavaScript code. - **U.noop()**: A function that does nothing. - **U.normalize(path)**: Normalizes a file path. - **U.onfinished(stream, fn)**: Executes a function when a stream finishes. - **U.parseBoolean(value, [def])**: Parses a string into a boolean. - **U.parseFloat(value, [def])**: Parses a string into a float. - **U.parseInt(value, [def])**: Parses a string into an integer. - **U.parseXML(value, [replace])**: Parses an XML string. - **U.path(url, [delimiter])**: Extracts the path from a URL. - **U.pmam(hours)**: Converts hours to AM/PM format. - **U.querify([url], data)**: Creates a query string from an object. - **U.queue(name, limit, processor, [param])**: Manages a queue of tasks. - **U.random_number(max)**: Generates a random number up to a maximum. - **U.random_string(max)**: Generates a random string of a specified length. - **U.random_text(max)**: (new) Generates random text. - **U.random([max], [min])**: Generates a random number within a range. - **U.reader([items])**: Creates a reader for items. - **U.reduce(source, prop, [reverse])**: Reduces an array or object to a single value. - **U.resolve(url, [callback])**: Resolves a URL. - **U.set(obj, path, value)**: Sets a value in an object using a path. - **U.streamer(beg, [end], fn, [skip], [stream])**: Creates a stream processor. - **U.streamer2(beg, [end], fn, [skip], [stream])**: An alternative stream processor. - **U.toError(err)**: Converts a value to an Error object. - **U.toURLEncode(value)**: Encodes a string for URL. - **U.trim(obj, [clean])**: Trims whitespace from a string or object properties. - **U.uidr()**: Generates a unique ID. - **U.wait(validator, callback, [timeout], [interval])**: Waits for a condition to be met. ``` -------------------------------- ### Declare HTML Flow Component with Server-Side Logic Source: https://docs.totaljs.com/total5/IbGpBV2dx60f Declares an HTML-based Flow component with server-side logic using the ` ``` -------------------------------- ### Client-side API Call using API() Source: https://docs.totaljs.com/total5/IbGpBV2Zx60f Demonstrates how to make an API call from the client-side using the `API()` method. This method requires a relative URL endpoint for each call and takes a callback function to handle the response. ```javascript API('/api/ users_query?page=2', function(response) { console.log('Users:', response); }); ``` -------------------------------- ### TMSCLIENT Initialization in JavaScript Source: https://docs.totaljs.com/total5/IbGpBV2Xx60f Initializes a TMS client connection to a specified URL with optional token authentication. The callback receives an error, client instance, and metadata object containing publish, subscribe, and call schemas. This method is dependency-free and outputs a WebSocketClient-extended client for messaging. It requires a valid TMS server URL and may have limitations in browser environments without WebSocket support. ```javascript // TMSCLIENT(url, [token], callback); TMSCLIENT('https://....', function(err, client, meta) { // @meta {Object} // |---- meta.name {String} // |---- meta.publish {Object Array}, example: [{ id: String, schema: Object }] // |---- meta.subscribe {Object Array}, example: [{ id: String, schema: Object }] // |---- meta.call {Object Array}, example: [{ id: String, schema: Object }] // @client {WebSocketClient} extended WebSocketClient }); ``` -------------------------------- ### Execute the custom compress operation (JavaScript) Source: https://docs.totaljs.com/total5/IbGpBV22x61f Demonstrates calling the previously defined 'compress' operation using OPERATION. Passes an object with path and filename, and handles callback to receive error and response. The response.value contains the resulting zip filename. ```JavaScript // Compress a directory: OPERATION('compress', { path: '/home/documents/', filename: '/home/documents.zip' }, function(err, response) { // response.value will be "filename" console.log(err, response.value); }); ``` -------------------------------- ### Real-World Dynamic Routing in Total.js Source: https://docs.totaljs.com/total5/IbGpBV27x60f Demonstrates practical dynamic routing scenarios in Total.js, including view rendering, REST API endpoints with authorization, and custom action mapping. ```javascript // Example // File: /controllers/example.js exports.install = function() { // View routing ROUTE('GET /'); ROUTE('GET /', 'view_name'); // Schema routing // Example of REST API routing // "+" char means that all request must be authorized ROUTE('+GET /api/users/ --> Users/query'); ROUTE('+GET /api/users/{id}/ --> Users/read'); ROUTE('+POST /api/users/ --> Users/insert'); ROUTE('+PUT /api/users/{id}/ --> Users/update'); ROUTE('+PATCH /api/users/{id}/ --> Users/patch'); ROUTE('+DELETE /api/users/ --> Users/remove'); // Custom routing to a specific function ROUTE('GET /', custom_action); }; function custom_action($) { // "$" is a "Controller" instance $.view('index'); } ```