### Install VQL and ValtheraDB Source: https://github.com/wxn0brp/vql/blob/master/docs/getting_started.md Install the required packages for VQL. This command installs both the database and VQL packages. ```bash npm install @wxn0brp/db @wxn0brp/vql ``` -------------------------------- ### Server-Side: FF_VQL setup Source: https://github.com/wxn0brp/vql/blob/master/docs/integration_http.md Sets up an HTTP endpoint using Falcon Frame and FF_VQL. Creates a Valthera database and VQLProcessor, then starts the server on port 3000. ```typescript import { FalconFrame } from "@wxn0brp/falcon-frame"; import { VQLProcessor, FF_VQL } from "@wxn0brp/vql"; import { Valthera } from "@wxn0brp/db"; const db = new Valthera("./data/my-db"); const processor = new VQLProcessor({ main: db }); const app = new FalconFrame(); FF_VQL(app, processor); app.l(3000); ``` -------------------------------- ### Install @wxn0brp/vql-client Source: https://github.com/wxn0brp/vql/blob/master/docs/integration_http.md Installs the VQL client package via npm. ```bash npm install @wxn0brp/vql-client ``` -------------------------------- ### VQL_OP_Add interface and example Source: https://github.com/wxn0brp/vql/blob/master/docs/lang/VQLR.md Defines the add operation interface and shows an example that inserts a new user document. The id_gen option defaults to true. ```typescript interface VQL_OP_Add { collection: string; data: Arg; id_gen?: boolean; // default: true } ``` ```json { db: "main", d: { add: { collection: "users", data: { name: "Alice", age: 30 } } } } ``` -------------------------------- ### VQL_OP_ToggleOne interface and example Source: https://github.com/wxn0brp/vql/blob/master/docs/lang/VQLR.md Defines the toggleOne operation interface and shows an example that toggles a favorite entry for a user and item, returning the _id field. ```typescript interface VQL_OP_ToggleOne { collection: string; search: Search; data?: Arg; select?: VQL_Fields; // Filter returned fields } ``` ```json { db: "main", d: { toggleOne: { collection: "favorites", search: { userId: "123", itemId: "456" }, select: ["_id"] } } } ``` -------------------------------- ### Comprehensive VQLS Examples Source: https://github.com/wxn0brp/vql/blob/master/docs/lang/VQLS.md A collection of common query patterns including filters, field selection, and collection management. ```bash # Find with filters and field selection db users s.status="active" s.age>18 e.name=1 e.email=1 o.limit=10 # Add record db +users d.name="Alice" d.email="alice@example.com" d.age=30 # Update single record with field selection (return only specified fields) db ~users! s._id="123" u.name="Bob" u.updatedAt=$_now e.name=1 e.updatedAt=1 # Update multiple records with field selection db ~users s.role="guest" u.role="user" e._id=1 e.name=1 # Upsert with field selection db ?users s._id="123" u.name="Bob" u.lastSeen=$_now e.name=1 # Delete with field selection (return deleted records with only specified fields) db -users s.active=false e._id=1 e.name=1 db -users! s._id="123" e.name=1 # Toggle with field selection db ^users s._id="123" e._id=1 # Relations db users r.orders.path=["db", "orders"] r.orders.search.status="pending" # Collection management db ensureCollection logs db getCollections ``` -------------------------------- ### Quick Example: VQLS and VQLR with Variables Source: https://github.com/wxn0brp/vql/blob/master/docs/index.md Shows the basic usage of VQLProcessor with both VQLS and VQLR syntaxes, including variable substitution. Requires a Valthera database instance and a user context for permission checks. ```typescript import VQLProcessor from "@wxn0brp/vql"; import { Valthera } from "@wxn0brp/db"; const db = new Valthera("./data/my-db"); const processor = new VQLProcessor({ main: db }); // VQLS const result1 = await processor.execute(`main users s.status="active" e.name=1`); // VQLR const result2 = await processor.execute({ db: "main", d: { find: { collection: "users", search: { status: "active" }, select: ["name"] } } }); // With variables const result3 = await processor.execute({ query: `main ~users! s.role=$role u.lastLogin=$_now`, var: { role: "admin" } }, userContext); ``` -------------------------------- ### VQL_OP_Find interface and example Source: https://github.com/wxn0brp/vql/blob/master/docs/lang/VQLR.md Defines the find operation interface and shows an example query that searches for active users, limits to 10, and selects only the name field. ```typescript interface VQL_OP_Find { collection: string; search?: Search; limit?: number; select?: VQL_Fields; options?: DbFindOpts; searchOpts?: FindOpts; } ``` ```json { db: "main", d: { find: { collection: "users", search: { status: "active" }, limit: 10, select: { name: 1 } } } } ``` -------------------------------- ### VQL_OP_UpdateOneOrAdd interface and example Source: https://github.com/wxn0brp/vql/blob/master/docs/lang/VQLR.md Defines the updateOneOrAdd operation interface and shows an example that updates a document if found, or adds a new one using add_arg. ```typescript interface VQL_OP_UpdateOneOrAdd { collection: string; search: Search; updater: UpdaterArg; add_arg?: Arg; id_gen?: boolean; select?: VQL_Fields; // Filter returned fields } ``` ```json { db: "main", d: { updateOneOrAdd: { collection: "users", search: { _id: "123" }, updater: { name: "Bob" }, add_arg: { name: "Bob", email: "b@x.com" } } } } ``` -------------------------------- ### Execute a VQL query with VQLProcessor Source: https://github.com/wxn0brp/vql/blob/master/README.md Shows how to initialize Valthera database instances, create a VQLProcessor, define a VQLR query object and an equivalent VQLS string, then execute the query asynchronously. The example uses the `$gt` operator to filter users older than 18 and selects only the `name` and `age` fields. The result is logged to the console, and errors are caught and logged. ```typescript import VQLProcessor from "@wxn0brp/vql"; import { Valthera } from "@wxn0brp/db"; // Initialize database instances const dbInstances = { myDatabase: new Valthera("path/to/database"), }; // Create a VQLProcessor instance const processor = new VQLProcessor(dbInstances); // Define a query (VQLR) const query = { db: "myDatabase", d: { find: { collection: "users", search: { $gt: { age: 18 } }, select: { name: 1, age: 1 }, }, }, }; // Or you can use a string query (VQLS): const vqls = ` myDatabase users s.$gt.age = 18 e.name = 1 e.age = 1 `; // Execute the query (async () => { try { const result = await processor.execute(query); console.log("Query Result:", result); } catch (error) { console.error("Error executing query:", error); } })(); ``` -------------------------------- ### VQL Client Usage Examples Source: https://github.com/wxn0brp/vql/blob/master/docs/integration_http.md Shows various ways to call the VQL endpoint: with variables, tagged template literal, VQLR object, and with hook context and fetch options. ```typescript import { fetchVQL, V } from "@wxn0brp/vql-client"; // VQLS with variables const users = await fetchVQL( "mainDB users s.status=$status", { status: "active" } ); // Tagged template literal const item = await V`mainDB items! s._id="item-001"`; // VQLR object const result = await fetchVQL({ db: "mainDB", d: { find: { collection: "users", search: { role: "admin" } } } }); // With hook context and fetch options const data = await fetchVQL( "mainDB users s.role=$role", { role: "admin" }, // vars { requestId: "123" }, // hookContext { signal: abortController.signal } // fetchOptions ); ``` -------------------------------- ### Explicit VQLS Operations Source: https://github.com/wxn0brp/vql/blob/master/docs/lang/VQLS.md Examples of explicit command-line operations for database interaction. ```bash db find users s.status="active" db findOne users s._id="123" db add users d.name="Alice" db update users s.role="guest" u.role="user" db updateOne users s._id="123" u.name="Bob" db remove users s.active=false db removeOne users s._id="123" db updateOneOrAdd users s._id="123" u.name="Bob" db toggleOne users s._id="123" db ensureCollection logs db issetCollection logs db removeCollection temp_data db getCollections ``` -------------------------------- ### VQL_OP_Update interface and examples Source: https://github.com/wxn0brp/vql/blob/master/docs/lang/VQLR.md Defines the update operation interface and shows two examples: one using 'update' to change roles and select returned fields, and one using 'updateOne' to update a single document by _id. ```typescript interface VQL_OP_Update { collection: string; search: Search; updater: UpdaterArg; select?: VQL_Fields; // Filter returned fields } ``` ```json { db: "main", d: { update: { collection: "users", search: { role: "guest" }, updater: { role: "user" }, select: ["name"] } } } ``` ```json { db: "main", d: { updateOne: { collection: "users", search: { _id: "123" }, updater: { name: "Bob" } } } } ``` -------------------------------- ### Relational Query Interface and Example Source: https://github.com/wxn0brp/vql/blob/master/docs/lang/VQLR.md Defines the VQL_Query_Relation interface and shows a concrete relational query. The example queries the orders collection with a search filter, sets many to true for a find operation, and includes relations to the users and products collections. ```typescript interface VQL_Query_Relation { r: { path: [string, string]; // [db, collection] search?: Search; relations?: Record; many?: boolean; // true = find, false = findOne options?: DbFindOpts; select?: string[] | Record; }; } ``` ```typescript { r: { path: ["main", "orders"], search: { status: "pending" }, many: true, relations: { customer: { path: ["main", "users"], select: ["name", "email"] }, items: { path: ["inventory", "products"] } } } } ``` -------------------------------- ### VQL_OP_Remove interface and examples Source: https://github.com/wxn0brp/vql/blob/master/docs/lang/VQLR.md Defines the remove operation interface and shows examples for 'remove' (multiple) and 'removeOne' (single document) with field selection. ```typescript interface VQL_OP_Remove { collection: string; search: Search; select?: VQL_Fields; // Filter returned fields } ``` ```json { db: "main", d: { remove: { collection: "users", search: { active: false } } } } ``` ```json { db: "main", d: { removeOne: { collection: "users", search: { _id: "123" }, select: { name: 1 } } } } ``` -------------------------------- ### VQL_OP_FindOne interface and examples Source: https://github.com/wxn0brp/vql/blob/master/docs/lang/VQLR.md Defines the findOne operation interface and shows two equivalent queries: one using 'findOne' and one using the alias 'f'. ```typescript interface VQL_OP_FindOne { collection: string; search: Search; select?: VQL_Fields; searchOpts?: FindOpts; } ``` ```json { db: "main", d: { findOne: { collection: "users", search: { _id: "123" } } } } ``` ```json { db: "main", d: { f: { collection: "users", search: { _id: "123" } } } } // alias ``` -------------------------------- ### Multi-line Query Template Source: https://github.com/wxn0brp/vql/blob/master/docs/lang/VQLS.md Example of embedding a VQLS query within a multi-line string in TypeScript. ```typescript const query = ` db users s.status="active" s.age>18 e.name=1 e.email=1 `; ``` -------------------------------- ### VQLS Comments Source: https://github.com/wxn0brp/vql/blob/master/docs/lang/VQLS.md Lines starting with # or // are treated as comments and ignored by the parser. ```bash # This is a comment db users s.status="active" // Another comment ``` -------------------------------- ### Initialize VQLProcessor with Databases Source: https://github.com/wxn0brp/vql/blob/master/docs/getting_started.md Initialize VQLProcessor with database instances. Creates two Valthera databases, adds sample data, and constructs a processor with a mapping of database names to instances. ```typescript import VQLProcessor from "@wxn0brp/vql"; import { Valthera } from "@wxn0brp/db"; const userDb = new Valthera("./data/users-db"); const productDb = new Valthera("./data/products-db"); // Add sample data await userDb.add("users", { _id: "user1", name: "Alice", age: 30 }); await userDb.add("users", { _id: "user2", name: "Bob", age: 25 }); await productDb.add("items", { _id: "item1", name: "Laptop", price: 1200 }); const dbInstances = { users: userDb, products: productDb }; const processor = new VQLProcessor(dbInstances); ``` -------------------------------- ### Browser/CDN Usage Source: https://github.com/wxn0brp/vql/blob/master/docs/integration_http.md Shows how to use the client when loaded via script tag, available as window.VQLClient. ```javascript VQLClient.cfg.url = "/api/vql"; const result = await VQLClient.fetchVQL("db users"); const item = await VQLClient.V`db items! s._id="123"`; ``` -------------------------------- ### VQLProcessor Constructor and Execute Source: https://github.com/wxn0brp/vql/blob/master/docs/index.md Shows the constructor signature for VQLProcessor, accepting a map of database instances, an optional VQLConfig, and an optional permission validation function. The execute method takes a query and an optional user context. ```typescript import VQLProcessor, { VQLConfig } from "@wxn0brp/vql"; const processor = new VQLProcessor( dbInstances, // Record config, // VQLConfig (optional) permValidFn // Permission function (optional) ); const result = await processor.execute(query, user); ``` -------------------------------- ### Enable Permissions with VQLConfig Source: https://github.com/wxn0brp/vql/blob/master/docs/getting_started.md Enable permission checking by creating a PermissionResolverEngine, adding a resolver, and passing a VQLConfig with noCheckPermissions set to false. The secure processor executes a query with a user context. ```typescript import { VQLConfig } from "@wxn0brp/vql"; import { PermissionResolverEngine } from "@wxn0brp/vql/permissions/resolver"; const engine = new PermissionResolverEngine(); engine.addResolver("password", async () => false, "endsWith"); const permValidFn = engine.create(); const secureProcessor = new VQLProcessor( dbInstances, new VQLConfig({ noCheckPermissions: false }), permValidFn ); const user = { _id: "user123", role: "admin" }; const result = await secureProcessor.execute(query, user); ``` -------------------------------- ### POST /custom-vql (createVqlRouteHandler) Source: https://github.com/wxn0brp/vql/blob/master/docs/integration_http.md The createVqlRouteHandler function creates a route handler that can be mounted on any path. It accepts options for user context extraction and returns a handler function for use with Falcon Frame's post method. ```APIDOC ## [POST] /custom-vql ### Description Creates a custom route handler for VQL processing with more control over routing. The handler is created via createVqlRouteHandler and can be mounted on any path. ### Method POST ### Endpoint /custom-vql (example, path is user-defined) ### Parameters #### Request Body - **query** (string) - Required - The VQL query string or VQLR object. ### Request Example ```json { "query": "mainDB users" } ``` ### Response #### Success Response (200) - **err** (boolean) - Always false on success. - **result** (object) - The query result data. #### Response Example ```json { "err": false, "result": {} } ``` #### Error Response - **err** (boolean) - Always true on error. - **msg** (string) - Error message. - **c** (number) - HTTP status code. #### Error Example ```json { "err": true, "msg": "Error message", "c": 400 } ``` ``` -------------------------------- ### VQL Client Hooks Source: https://github.com/wxn0brp/vql/blob/master/docs/integration_http.md Defines hooks for onStart, onEnd, and onError to observe query lifecycle. ```typescript VConfig.hooks = { onStart: (query, hookContext) => { console.log("Starting:", query); }, onEnd: (query, durationMs, result, hookContext) => { console.log(`Completed in ${durationMs}ms:`, result); }, onError: (query, error, result, hookContext) => { console.error("Failed:", error); } }; ``` -------------------------------- ### VQL Client Configuration Source: https://github.com/wxn0brp/vql/blob/master/docs/integration_http.md Configures the VQL client with URL, headers, default body fields, and default hook context. ```typescript import { VConfig } from "@wxn0brp/vql-client"; VConfig.url = "http://localhost:3000/VQL"; VConfig.headers = { "Authorization": "Bearer TOKEN" }; VConfig.body = {}; // Default body fields VConfig.hookContext = {}; // Default hook context ``` -------------------------------- ### Enable Permissions with VQLConfig Source: https://github.com/wxn0brp/vql/blob/master/docs/permissions.md Enables the permission system by setting noCheckPermissions to false. strictSelect must be true when permissions are enabled; strictACL is also set. The permValidFn is provided as the third argument. ```typescript import VQLProcessor, { VQLConfig } from "@wxn0brp/vql"; const processor = new VQLProcessor( dbInstances, new VQLConfig({ noCheckPermissions: false, strictSelect: true, // REQUIRED when permissions are enabled strictACL: true, }), permValidFn ); ``` -------------------------------- ### Update Data with VQLS Source: https://github.com/wxn0brp/vql/blob/master/docs/getting_started.md Update a document using VQLS updateOne syntax and verify the update. The first command updates the price of the Laptop item, and the second retrieves the item to confirm. ```typescript // VQLS updateOne await processor.execute(`products ~items! s.name="Laptop" u.price=1100`); // Verify const item = await processor.execute(`products items s.name="Laptop"`); ``` -------------------------------- ### VQLConfig Options Source: https://github.com/wxn0brp/vql/blob/master/docs/index.md Configures VQLProcessor behavior with options for permission checking, strict select, ACL fallback, error path visibility, and user context requirements. Defaults are shown in comments. ```typescript const config = new VQLConfig({ noCheckPermissions: true, // Default: true (permissions disabled) strictSelect: false, // Empty select = no filtering (true = no fields) strictACL: false, // Fallback to parent path on 404 hidePath: false, // Show actual paths in errors permissionDeniedIfNoUser: true // Deny if no user context }); ``` -------------------------------- ### Collection Management with VQLS Source: https://github.com/wxn0brp/vql/blob/master/docs/getting_started.md Manage collections: ensure a collection exists, list all collections, and remove a collection. ```typescript await processor.execute(`users ensureCollection logs`); const collections = await processor.execute(`users getCollections`); await processor.execute(`users removeCollection logs`); ``` -------------------------------- ### VQLS Query with String Syntax Source: https://github.com/wxn0brp/vql/blob/master/docs/getting_started.md Execute a VQLS query using string syntax. The query selects products with price greater than 100 and returns name and price fields, with the expected result shown as a comment. ```typescript const query: VQLUQ = `products items s.$gt.price=100 e.name=1 e.price=1`; const result = await processor.execute(query); // [{ name: "Laptop", price: 1200 }] ``` -------------------------------- ### VQLConfig Source: https://github.com/wxn0brp/vql/blob/master/docs/permissions.md Configuration for enabling the optional programmatic permission system in VQL. Disabled by default. ```APIDOC ## [CONFIG] VQLConfig ### Description Configuration for enabling the optional programmatic permission system in VQL. Disabled by default. ### Configuration Options - **noCheckPermissions** (boolean) - Set to `false` to enable permission checks. - **strictSelect** (boolean) - Required when permissions are enabled. - **strictACL** (boolean) - Optional strict ACL enforcement. ### Example ```typescript import VQLProcessor, { VQLConfig } from "@wxn0brp/vql"; const processor = new VQLProcessor( dbInstances, new VQLConfig({ noCheckPermissions: false, strictSelect: true, // REQUIRED when permissions are enabled strictACL: true, }), permValidFn ); ``` ``` -------------------------------- ### FF_VQL_Options interface Source: https://github.com/wxn0brp/vql/blob/master/docs/integration_http.md Defines the options for FF_VQL: path (default "/VQL"), getUser to extract user context, and getQuery for custom query extraction. ```typescript interface FF_VQL_Options { path?: string; // Route path (default: "/VQL") getUser?: ContextFn; // Extract user context from request getQuery?: GetQueryFn; // Custom query extraction } ``` -------------------------------- ### Find with all options Source: https://github.com/wxn0brp/vql/blob/master/docs/lang/VQLR.md Shows a find query with all options: collection, search with comparison operators, select, limit, sort, and skip. Use when you need to retrieve documents with filtering, projection, and pagination. ```typescript { db: "main", d: { find: { collection: "users", search: { status: "active", $gt: { age: 18 }, $lte: { age: 65 } }, select: { name: 1, email: 1 }, limit: 50, options: { sort: { age: -1 } }, searchOpts: { skip: 10 } } } } ``` -------------------------------- ### POST /VQL Source: https://github.com/wxn0brp/vql/blob/master/docs/integration_http.md The FF_VQL function registers a POST endpoint that accepts VQL queries and returns results or errors. The route path is configurable via options.path (default '/VQL'). ```APIDOC ## [POST] /VQL ### Description Exposes a VQLProcessor as an HTTP endpoint using Falcon Frame. The endpoint accepts VQL queries and returns results or errors. ### Method POST ### Endpoint /VQL (default, configurable via options.path) ### Parameters #### Request Body - **query** (string) - Required - The VQL query string or VQLR object. ### Request Example ```json { "query": "mainDB users s.status=$status" } ``` ### Response #### Success Response (200) - **err** (boolean) - Always false on success. - **result** (object) - The query result data. #### Response Example ```json { "err": false, "result": {} } ``` #### Error Response - **err** (boolean) - Always true on error. - **msg** (string) - Error message. - **c** (number) - HTTP status code. #### Error Example ```json { "err": true, "msg": "Error message", "c": 400 } ``` ``` -------------------------------- ### User Context with getUser Source: https://github.com/wxn0brp/vql/blob/master/docs/integration_http.md Shows how to provide a custom getUser function to FF_VQL. Extracts a Bearer token, decodes it, and returns a user object from the database or a guest fallback. ```typescript FF_VQL(app, processor, { getUser: async (req, res) => { const token = req.header("Authorization")?.replace("Bearer ", ""); const data = jwt.decode(token); if (data) { const dbUser = await db.findOne("users", { _id: data._id }); return dbUser; } return { _id: "guest", role: "guest" }; } }); ``` -------------------------------- ### VQLS Syntax Patterns Source: https://github.com/wxn0brp/vql/blob/master/docs/lang/VQLS.md The basic structure for VQLS queries using either full operation names or shorthand notation. ```text [body...] ``` ```text [body...] ``` -------------------------------- ### Custom Query Extraction with getQuery Source: https://github.com/wxn0brp/vql/blob/master/docs/integration_http.md Shows how to provide a custom getQuery function to FF_VQL. Reads the query from the 'q' query parameter, falling back to the request body's query field. ```typescript FF_VQL(app, processor, { getQuery: async (req, res) => { const query = req.query.get("q"); return query ? JSON.parse(query) : req.body.query; } }); ``` -------------------------------- ### Nested Property Queries Source: https://github.com/wxn0brp/vql/blob/master/docs/lang/VQLS.md Querying nested object properties using dot notation. ```bash db users s.address.city="NYC" db users s.profile.age>18 ``` -------------------------------- ### VQLR Query with Object Syntax Source: https://github.com/wxn0brp/vql/blob/master/docs/getting_started.md Execute a VQLR query using object syntax. The query finds users older than 20 and selects name and age fields, returning the expected result as a comment. ```typescript import type { VQLUQ } from "@wxn0brp/vql"; const query: VQLUQ = { db: "users", d: { find: { collection: "users", search: { $gt: { age: 20 } }, select: { name: 1, age: 1 } } } }; const result = await processor.execute(query); // [{ name: "Alice", age: 30 }, { name: "Bob", age: 25 }] ``` -------------------------------- ### PermissionResolverEngine Basic Usage Source: https://github.com/wxn0brp/vql/blob/master/docs/permissions.md Creates a PermissionResolverEngine, adds path-based resolvers (blocking passwords and allowing admins), and generates a permValidFn. The engine.create() returns a function that denies unmatched paths by default. ```typescript import { PermissionResolverEngine } from "@wxn0brp/vql/permissions/resolver"; const engine = new PermissionResolverEngine(); // Block passwords engine.addResolver("password", async () => false, "endsWith"); // Allow admins engine.addResolver("users", async (args) => args.user?.role === "admin", "startsWith"); const permValidFn = engine.create(); ``` -------------------------------- ### Field Selection Formats Source: https://github.com/wxn0brp/vql/blob/master/docs/lang/VQLR.md Shows the two supported formats for field selection: a record with 1 values and an array of field names. ```typescript // Record format select: { name: 1, email: 1 } // Array format select: ["name", "email"] ``` -------------------------------- ### createVqlRouteHandler usage Source: https://github.com/wxn0brp/vql/blob/master/docs/integration_http.md Creates a route handler with createVqlRouteHandler for more control over routing. The handler is then used with app.post. ```typescript import { createVqlRouteHandler } from "@wxn0brp/vql/helpers/falconFrame"; const handler = createVqlRouteHandler(processor, { getUser: async (req) => ({ _id: "user123" }) }); app.post("/custom-vql", handler); ``` -------------------------------- ### Relational Queries (r key) Source: https://github.com/wxn0brp/vql/blob/master/docs/lang/VQLR.md Perform queries with relations between collections, supporting find and findOne operations with nested relations. ```APIDOC ## Relational Queries (`r` key) ### Description Perform queries that can include related collections. The `r` key defines the main query and optional relations to other collections. ### Interface ```typescript interface VQL_Query_Relation { r: { path: [string, string]; // [db, collection] search?: Search; relations?: Record; many?: boolean; // true = find, false = findOne options?: DbFindOpts; select?: string[] | Record; }; } ``` ### Example ```json { "r": { "path": ["main", "orders"], "search": { "status": "pending" }, "many": true, "relations": { "customer": { "path": ["main", "users"], "select": ["name", "email"] }, "items": { "path": ["inventory", "products"] } } } } ``` ### Parameters - **path** (array of two strings) - Required - The database and collection to query. - **search** (Search) - Optional - Search criteria. - **relations** (Record) - Optional - Related collections to fetch. - **many** (boolean) - Optional - If true, performs a find; if false, performs a findOne. - **options** (DbFindOpts) - Optional - Additional find options. - **select** (string[] or Record) - Optional - Fields to include in the result. ``` -------------------------------- ### Variable Usage in VQLS Source: https://github.com/wxn0brp/vql/blob/master/docs/lang/VQLS.md Using custom and predefined variables within queries. ```bash # Custom variable db users s.role=$role # Predefined variables db users d.createdAt=$_now db users s.ownerId=$_me ``` -------------------------------- ### Variables Source: https://github.com/wxn0brp/vql/blob/master/docs/lang/VQLR.md Use variables in queries with the `{ __: "variableName" }` syntax for dynamic values. ```APIDOC ## Variables ### Description Use `{ __: "variableName" }` to reference variables in queries. Variables can be defined in the `var` key. ### Example ```json { "db": "main", "d": { "add": { "collection": "users", "data": { "ownerId": { "__": "_me" }, "createdAt": { "__": "_now" } } } }, "var": { "customVar": "value" } } ``` ``` -------------------------------- ### createGwValidFn Source: https://github.com/wxn0brp/vql/blob/master/docs/permissions.md Creates a permission validation function using Gate Warden without custom resolvers. ```APIDOC ## [FUNCTION] createGwValidFn ### Description Simpler Gate Warden integration without custom resolvers. Creates a `permValidFn` that delegates to a Gate Warden instance. ### Parameters - **gw** (GateWarden) - Required - Gate Warden instance ### Returns - **PermValidFn** - Permission validation function ### Example ```typescript import { createGwValidFn } from "@wxn0brp/vql"; import { GateWarden } from "@wxn0brp/gate-warden"; const gw = new GateWarden(); const permValidFn = createGwValidFn(gw); ``` ``` -------------------------------- ### Response Format: Success and Error Source: https://github.com/wxn0brp/vql/blob/master/docs/integration_http.md Shows the JSON response format for successful and error responses. ```json { "err": false, "result": { /* data */ } } ``` ```json { "err": true, "msg": "Error message", "c": 400 } ``` -------------------------------- ### PermissionResolverEngine Source: https://github.com/wxn0brp/vql/blob/master/docs/permissions.md Helper class for building permission validation functions with path-based resolvers. ```APIDOC ## [CLASS] PermissionResolverEngine ### Description Helper class for building `permValidFn` with path-based resolvers. Allows adding resolvers for specific paths and creating a permission validation function. ### Methods #### addResolver - **Description**: Adds a resolver for a given path matcher. - **Parameters**: - **matcher** (string | RegExp | function) - Required - Path matcher (string, RegExp, or custom function) - **resolver** (function) - Required - Async function returning boolean or ValidFnResult - **mode** (string) - Optional - String matcher mode: "endsWith", "startsWith", "includes", or exact (default) #### create - **Description**: Creates a `permValidFn` using only custom resolvers. Unmatched paths are denied. - **Returns**: PermValidFn #### createWithGw - **Description**: Creates a `permValidFn` that falls back to Gate Warden if no resolver matches. - **Parameters**: - **gw** (GateWarden) - Required - Gate Warden instance - **Returns**: PermValidFn ### Example ```typescript import { PermissionResolverEngine } from "@wxn0brp/vql/permissions/resolver"; const engine = new PermissionResolverEngine(); // Block passwords engine.addResolver("password", async () => false, "endsWith"); // Allow admins engine.addResolver("users", async (args) => args.user?.role === "admin", "startsWith"); const permValidFn = engine.create(); ``` ``` -------------------------------- ### TypeScript Types Source: https://github.com/wxn0brp/vql/blob/master/docs/lang/VQLR.md Importable TypeScript types for VQL queries and operations. ```APIDOC ## TypeScript Types ### Description Import these types from `@wxn0brp/vql` for type-safe VQL queries. ### Import Example ```typescript import type { VQL_Query, VQL_Query_CRUD, VQL_Query_Relation, VQL_OP_Find, VQL_OP_FindOne, VQL_OP_Add, VQL_OP_Update, VQL_OP_Remove, VQL_OP_UpdateOneOrAdd, VQL_OP_ToggleOne, VQL_Fields, VQL_Var } from "@wxn0brp/vql"; ``` ``` -------------------------------- ### TypeScript Type Imports from @wxn0brp/vql Source: https://github.com/wxn0brp/vql/blob/master/docs/lang/VQLR.md Imports the TypeScript types exported by the @wxn0brp/vql package, including query, CRUD, relation, and operation types. ```typescript import type { VQL_Query, VQL_Query_CRUD, VQL_Query_Relation, VQL_OP_Find, VQL_OP_FindOne, VQL_OP_Add, VQL_OP_Update, VQL_OP_Remove, VQL_OP_UpdateOneOrAdd, VQL_OP_ToggleOne, VQL_Fields, VQL_Var } from "@wxn0brp/vql"; ``` -------------------------------- ### VQLR variable reference syntax Source: https://github.com/wxn0brp/vql/blob/master/docs/lang/base.md VQLR syntax for referencing variables using the { __: "variableName" } pattern. Use predefined variables like _me and _now. ```typescript { data: { ownerId: { __: "_me" }, createdAt: { __: "_now" } } } ``` -------------------------------- ### Using Variables in VQLS Queries Source: https://github.com/wxn0brp/vql/blob/master/docs/getting_started.md Use predefined and custom variables in VQLS queries. The first query uses the predefined $_now variable, while the second passes a custom minAge variable. ```typescript // Predefined variables await processor.execute(`users +users d.name="Charlie" d.createdAt=$_now`); // Custom variables const result = await processor.execute({ query: `users users s.age>$minAge e.name=1`, var: { minAge: 25 } }); ``` -------------------------------- ### TypeScript types for VQL queries Source: https://github.com/wxn0brp/vql/blob/master/docs/lang/base.md TypeScript type imports and usage for VQL queries. VQLUQ accepts both string and object forms. ```typescript import type { VQLUQ, VQL_Query, VQL_Query_CRUD } from "@wxn0brp/vql"; const q1: VQLUQ = `users s.status="active"`; const q2: VQLUQ = { db: "main", d: { find: { collection: "users" } } }; ``` -------------------------------- ### VQLS variable usage in query Source: https://github.com/wxn0brp/vql/blob/master/docs/lang/base.md VQLS syntax for injecting variables into query values. Use $variableName in values; predefined variables like $_now are available. ```bash db users s.role=$role d.createdAt=$_now ``` -------------------------------- ### Field Selection Source: https://github.com/wxn0brp/vql/blob/master/docs/lang/VQLR.md Specify which fields to include in query results using either a record or array format. ```APIDOC ## Field Selection ### Description Select specific fields to return from a query. Two formats are supported: record format and array format. ### Record Format ```typescript select: { name: 1, email: 1 } ``` ### Array Format ```typescript select: ["name", "email"] ``` ``` -------------------------------- ### Multi-database relations Source: https://github.com/wxn0brp/vql/blob/master/docs/lang/VQLR.md Performs a relational query across multiple databases: fetches orders from orders_db and joins related customer and items from other databases. Use when you need to combine data from different databases in one query. ```typescript { r: { path: ["orders_db", "orders"], search: { status: "shipped" }, many: true, relations: { customer: { path: ["users_db", "users"], select: ["name", "email"] }, items: { path: ["inventory_db", "products"] } } } } ``` -------------------------------- ### Collection Management Operations Source: https://github.com/wxn0brp/vql/blob/master/docs/lang/VQLR.md Shows the four collection management operations: ensureCollection, issetCollection, removeCollection, and getCollections. Each uses the db key to specify the database and the d key to wrap the operation. ```typescript { db: "main", d: { ensureCollection: { collection: "logs" } } } { db: "main", d: { issetCollection: { collection: "logs" } } } { db: "main", d: { removeCollection: { collection: "temp" } } } { db: "main", d: { getCollections: {} } } ``` -------------------------------- ### Collection Management Source: https://github.com/wxn0brp/vql/blob/master/docs/lang/VQLR.md Operations to ensure, check, remove, and list collections in the database. ```APIDOC ## Collection Management ### Description Operations to manage collections in the database: ensure a collection exists, check if a collection exists, remove a collection, and list all collections. ### Operations #### ensureCollection - **Description**: Creates a collection if it does not exist. - **Request Format**: `{ db: "main", d: { ensureCollection: { collection: "logs" } } }` #### issetCollection - **Description**: Checks if a collection exists. - **Request Format**: `{ db: "main", d: { issetCollection: { collection: "logs" } } }` #### removeCollection - **Description**: Removes a collection. - **Request Format**: `{ db: "main", d: { removeCollection: { collection: "temp" } } }` #### getCollections - **Description**: Lists all collections in the database. - **Request Format**: `{ db: "main", d: { getCollections: {} } }` ``` -------------------------------- ### Pass custom variables to processor.execute Source: https://github.com/wxn0brp/vql/blob/master/docs/lang/base.md Pass custom variables to processor.execute for both VQLS and VQLR. The var object supplies values for $role and custom references. ```typescript // VQLS with vars await processor.execute({ query: `users s.role=$role`, var: { role: "admin" } }); ``` ```typescript // VQLR with vars await processor.execute({ db: "main", d: { find: {...} }, var: { custom: "val" } }); ``` -------------------------------- ### VQL_Query interface Source: https://github.com/wxn0brp/vql/blob/master/docs/lang/VQLR.md Defines the top-level structure of a VQLR query object. Use this interface when constructing or validating VQLR queries programmatically in TypeScript. ```typescript interface VQL_Query { db?: string; // Target database instance d?: VQL_Query_CRUD; // CRUD operation r?: VQL_Query_Relation; // Relational query var?: Record; // Variables } ``` -------------------------------- ### Variable References in Add Operation Source: https://github.com/wxn0brp/vql/blob/master/docs/lang/VQLR.md Uses the __ variable reference syntax to insert built-in variables _me and _now into an add operation, and defines a custom variable customVar in the var key. ```typescript { db: "main", d: { add: { collection: "users", data: { ownerId: { __: "_me" }, createdAt: { __: "_now" } } } }, var: { customVar: "value" } } ``` -------------------------------- ### Update with operators Source: https://github.com/wxn0brp/vql/blob/master/docs/lang/VQLR.md Updates a single document using operators: $inc to increment a field, $set to set a nested field with the _now special value. Use when you need to modify a document with atomic update operators. ```typescript { db: "main", d: { updateOne: { collection: "users", search: { _id: "123" }, updater: { name: "Bob", $inc: { loginCount: 1 }, $set: { "profile.lastLogin": { __: "_now" } } } } } } ``` -------------------------------- ### PermCRUD Source: https://github.com/wxn0brp/vql/blob/master/docs/permissions.md Enum for CRUD operation bitmask values used in permission checks. ```APIDOC ## [ENUM] PermCRUD ### Description Enum representing CRUD operation bitmask values used in permission checks. ### Values - **CREATE** = 1 - **READ** = 2 - **UPDATE** = 4 - **DELETE** = 8 - **COLLECTION** = 16 ### Example ```typescript import { PermCRUD } from "@wxn0brp/vql/types/perm"; if (args.p & PermCRUD.READ) { // allow read } ``` ``` -------------------------------- ### Permission Validation Function Types Source: https://github.com/wxn0brp/vql/blob/master/docs/permissions.md Defines the signature and argument/result types for the permission validation function. The field is hashed if hidePath is true; p is a CRUD bitmask; user comes from execute(). The result includes granted, optional via (resolver or gate-warden), and reason. ```typescript type PermValidFn = (args: PermValidFnArgs) => Promise; interface PermValidFnArgs { field: string; // Path (hashed if hidePath: true) path: string[]; // Original path segments p: number; // CRUD bitmask user: any; // User context from execute() } interface ValidFnResult { granted: boolean; via?: "resolver" | "gate-warden"; reason?: string; } ``` -------------------------------- ### Custom Transport Source: https://github.com/wxn0brp/vql/blob/master/docs/integration_http.md Overrides the default transport with a custom function that posts to a custom endpoint. ```typescript import { VConfig } from "@wxn0brp/vql-client"; VConfig.transport = async (query, fetchOptions) => { // Custom transport logic const res = await fetch("/custom-endpoint", { method: "POST", body: JSON.stringify({ query }), ...fetchOptions }); return res.json(); }; ``` -------------------------------- ### PermValidFn Source: https://github.com/wxn0brp/vql/blob/master/docs/permissions.md Type definition for the permission validation function used to check field-level access. ```APIDOC ## [FUNCTION] PermValidFn ### Description Type definition for the permission validation function passed to VQLProcessor. It is called for each field access to determine if the operation is allowed. ### Signature ```typescript type PermValidFn = (args: PermValidFnArgs) => Promise; ``` ### Parameters - **args** (PermValidFnArgs) - Required - Arguments containing field, path, CRUD bitmask, and user context. ### PermValidFnArgs - **field** (string) - Path (hashed if hidePath: true) - **path** (string[]) - Original path segments - **p** (number) - CRUD bitmask - **user** (any) - User context from execute() ### ValidFnResult - **granted** (boolean) - Whether access is granted - **via** (string) - Optional - "resolver" or "gate-warden" - **reason** (string) - Optional - Reason for denial ### Example ```typescript const permValidFn: PermValidFn = async (args) => { return { granted: true }; }; ``` ``` -------------------------------- ### PermCRUD Enum Source: https://github.com/wxn0brp/vql/blob/master/docs/permissions.md Shows the PermCRUD enum with bitmask values for CRUD operations and COLLECTION. Used to check permissions via bitwise operations. ```typescript import { PermCRUD } from "@wxn0brp/vql/types/perm"; enum PermCRUD { CREATE = 1, READ = 2, UPDATE = 4, DELETE = 8, COLLECTION = 16 } ```