### installService Source: https://github.com/arangodb/arangojs/blob/main/_autodocs/api-reference/routes-and-administration.md Installs a Foxx service from a given source with optional installation options. ```APIDOC ## installService() ### Description Installs a Foxx service from a given source with optional installation options. ### Method `installService` ### Parameters #### Request Body - **source** (string | Buffer) - Required - Service source (file path or zip buffer) - **options** (InstallServiceOptions) - Optional - Installation options ### Returns Promise ``` -------------------------------- ### Example: Get and Process Server Logs Source: https://github.com/arangodb/arangojs/blob/main/_autodocs/api-reference/routes-and-administration.md Demonstrates how to retrieve server log entries, specifically filtering for 'ERROR' level messages and iterating through them. ```javascript const logs = await db.getLogs({ level: "ERROR" }); logs.messages.forEach(msg => { console.log(`[${msg.level}] ${msg.message}`); }); ``` -------------------------------- ### Explain Query Example Source: https://github.com/arangodb/arangojs/blob/main/_autodocs/api-reference/database.md Example of explaining an AQL query to retrieve its execution plan and logging the nodes of the plan. ```javascript const plan = await db.explain(aql` FOR user IN users FILTER user.active RETURN user `); console.log(plan.plan.nodes); ``` -------------------------------- ### Example: Accessing and Querying a Vertex Collection Source: https://github.com/arangodb/arangojs/blob/main/_autodocs/api-reference/graphs.md Demonstrates how to get a graph, then a specific vertex collection, and finally retrieve a vertex by its key. Ensure the graph and collection exist before execution. ```javascript const graph = db.graph("social"); const users = graph.vertexCollection("users"); const user = await users.vertex("alice"); ``` -------------------------------- ### List Collections Example Source: https://github.com/arangodb/arangojs/blob/main/_autodocs/api-reference/database.md Example of listing all collections and logging their names and types. ```javascript const collections = await db.listCollections(); collections.forEach(col => { console.log(`${col.name} (${col.type === 2 ? 'document' : 'edge'})`); }); ``` -------------------------------- ### Install Foxx Service Source: https://github.com/arangodb/arangojs/blob/main/_autodocs/api-reference/routes-and-administration.md Installs a Foxx service from a given source, with optional installation configurations. ```typescript async installService( source: string | Buffer, options?: InstallServiceOptions ): Promise ``` -------------------------------- ### supportInfo() Source: https://github.com/arangodb/arangojs/blob/main/_autodocs/api-reference/routes-and-administration.md Gets support information for the deployment, which varies for cluster and single-server setups. ```APIDOC ## supportInfo() ### Description Gets support information for the deployment (cluster or single-server). ### Method GET ### Endpoint /_admin/support ### Response #### Success Response (200) - **deployment** (string) - Type of deployment ('cluster' or 'single-server'). - **version** (string) - ArangoDB version. - **coreVersion** (string) - Core ArangoDB version. - **serverVersion** (string) - Server specific version. - **dbVersion** (string) - Database version. - **edition** (string) - ArangoDB edition (e.g., 'community', 'enterprise'). - **mode** (string) - Server mode. - **uptime** (number) - Server uptime in seconds. - **error** (string) - Error message if any. - **details** (object) - Additional details specific to the deployment type. ``` -------------------------------- ### Example of Getting Transaction Status Source: https://github.com/arangodb/arangojs/blob/main/_autodocs/api-reference/transactions.md Shows how to retrieve the status and ID of a transaction using the `get` method. ```javascript const trx = db.transaction(); const status = await trx.get(); console.log(status.id); ``` -------------------------------- ### Create Edge Collection Example Source: https://github.com/arangodb/arangojs/blob/main/_autodocs/api-reference/database.md Example of creating a new edge collection. ```javascript const follows = await db.createEdgeCollection("follows"); ``` -------------------------------- ### Access Graph and Vertex Collection Source: https://github.com/arangodb/arangojs/blob/main/_autodocs/api-reference/database.md Example of getting a graph instance and then accessing one of its vertex collections. ```javascript const social = db.graph("social"); const vertices = social.vertexCollection("users"); ``` -------------------------------- ### Create Graph Example Source: https://github.com/arangodb/arangojs/blob/main/_autodocs/api-reference/database.md Example demonstrating the creation of a new graph named 'social' with a 'follows' edge definition between 'users' collections. ```javascript const graph = await db.createGraph("social", [ { collection: "follows", from: ["users"], to: ["users"] } ]); ``` -------------------------------- ### Example Transaction Collection Configuration Source: https://github.com/arangodb/arangojs/blob/main/_autodocs/api-reference/transactions.md Illustrates how to configure collections for read and write access in a transaction. ```javascript const collections = { read: ["products"], write: ["orders", "accounts"] }; const result = await db.executeTransaction(collections, ...); ``` -------------------------------- ### Example: Get Edge Collection Source: https://github.com/arangodb/arangojs/blob/main/_autodocs/api-reference/graphs.md Illustrates how to get a reference to the 'follows' edge collection within the 'social' graph. ```javascript const graph = db.graph("social"); const follows = graph.edgeCollection("follows"); ``` -------------------------------- ### Create a Graph Source: https://github.com/arangodb/arangojs/blob/main/_autodocs/api-reference/graphs.md Example demonstrating how to create a new graph with specified edge definitions. ```APIDOC ## Create a Graph ### Description Creates a new graph with the given name and edge definitions. ### Usage ```javascript const db = new Database(); const graph = await db.createGraph("social", [ { collection: "follows", from: ["users"], to: ["users"] }, { collection: "likes", from: ["users"], to: ["posts"] } ]); ``` ``` -------------------------------- ### Install ArangoJS Source: https://github.com/arangodb/arangojs/blob/main/_autodocs/README.md Install the arangojs package using npm. This is the first step to using the ArangoDB JavaScript driver. ```bash npm install arangojs ``` -------------------------------- ### Token-Based Authentication Example Source: https://github.com/arangodb/arangojs/blob/main/_autodocs/api-reference/users-and-jobs.md Shows how to create a service account, generate a long-lived API token for it, and then use that token to establish a new database connection for automated access. ```javascript // Create service account const serviceAccount = await db.createUser("api-worker", { password: Math.random().toString(36), active: true }); // Create long-lived token const token = await db.createAccessToken("api-worker", { ttl: 31536000 // 1 year }); // Use token for connection const serviceDb = new Database({ url: "http://127.0.0.1:8529", databaseName: "myapp", auth: { token } }); // Service can now authenticate without password const result = await serviceDb.query(aql`RETURN 1`); ``` -------------------------------- ### Get View Reference Source: https://github.com/arangodb/arangojs/blob/main/_autodocs/api-reference/database.md Use this method to get a reference to an existing view by its name. No setup or imports are required beyond having a database instance. ```javascript const userView = db.view("users_search"); ``` -------------------------------- ### Example: Set Server Log Levels Source: https://github.com/arangodb/arangojs/blob/main/_autodocs/api-reference/routes-and-administration.md Demonstrates how to update the log levels for 'rocksdb' and 'replication' loggers to 'debug'. ```javascript await db.setLogLevel({ "rocksdb": "debug", "replication": "debug" }); ``` -------------------------------- ### Example Transaction with Options Source: https://github.com/arangodb/arangojs/blob/main/_autodocs/api-reference/transactions.md Demonstrates executing a transaction with specific options, including a custom timeout and enabling synchronous writes. ```javascript await db.executeTransaction( { write: ["orders"] }, action, { timeout: 30000, waitForSync: true, maxTransactionSize: 134217728 // 128 MB } ); ``` -------------------------------- ### Get Foxx Service Configuration Source: https://github.com/arangodb/arangojs/blob/main/_autodocs/api-reference/routes-and-administration.md Retrieves the configuration details for a specific installed Foxx service identified by its mount path. ```typescript async getServiceConfiguration(mount: string): Promise ``` -------------------------------- ### AQL Best Practice: Using aql Tag for Dynamic Queries Source: https://github.com/arangodb/arangojs/blob/main/_autodocs/api-reference/aql.md Highlights the importance of using the `aql` tag for constructing dynamic AQL queries to prevent injection vulnerabilities. The 'Good' example shows the recommended approach, while the 'Bad' example illustrates a vulnerable method. ```javascript // Good const query = aql`FOR u IN users FILTER u.age >= ${userAge} RETURN u`; // Bad - vulnerable to injection const query = `FOR u IN users FILTER u.age >= ${userAge} RETURN u`; ``` -------------------------------- ### List and Iterate Foxx Services Source: https://github.com/arangodb/arangojs/blob/main/_autodocs/api-reference/routes-and-administration.md Demonstrates how to fetch and iterate over installed Foxx services using the listServices method. ```javascript const services = await db.listServices(); services.forEach(service => { console.log(`${service.mount}: ${service.name}`); }); ``` -------------------------------- ### Install arangojs Source: https://github.com/arangodb/arangojs/blob/main/_autodocs/README.md Install the arangojs package using npm. For Unix socket support with Node.js, also install 'undici'. ```bash npm install arangojs ``` ```bash npm install undici ``` -------------------------------- ### List Graphs and Log Names Source: https://github.com/arangodb/arangojs/blob/main/_autodocs/api-reference/database.md Example of fetching all graphs and logging the name of each graph to the console. ```javascript const graphs = await db.listGraphs(); graphs.forEach(g => console.log(g.name)); ``` -------------------------------- ### version() Source: https://github.com/arangodb/arangojs/blob/main/_autodocs/api-reference/database.md Gets server version information, including server, license, and version details. ```APIDOC ## version() ### Description Gets server version information. ### Method GET (assumed, based on typical API patterns for retrieving information) ### Endpoint / ### Parameters None ### Response #### Success Response (200) - **version** (string) - The ArangoDB server version. - **server** (string) - The server name (e.g., "ArangoDB"). - **license** (string) - The server license type. ### Response Example ```json { "version": "3.10.0", "server": "ArangoDB", "license": "community" } ``` ``` -------------------------------- ### listServices Source: https://github.com/arangodb/arangojs/blob/main/_autodocs/api-reference/routes-and-administration.md Lists installed Foxx services. Optionally excludes system services. ```APIDOC ## listServices() ### Description Lists installed Foxx services. Optionally excludes system services. ### Method `listServices` ### Parameters #### Query Parameters - **excludeSystem** (boolean) - Optional - Exclude system services. Defaults to `false`. ### Returns Promise ### Example ```javascript const services = await db.listServices(); services.forEach(service => { console.log(`${service.mount}: ${service.name}`); }); ``` ``` -------------------------------- ### Example of Committing a Transaction Source: https://github.com/arangodb/arangojs/blob/main/_autodocs/api-reference/transactions.md Shows how to execute multiple steps and then commit the transaction to finalize the changes. ```javascript const trx = db.transaction(); await trx.step(() => collection.insert(doc1)); await trx.step(() => collection.insert(doc2)); await trx.commit(); ``` -------------------------------- ### Work with Vertices Source: https://github.com/arangodb/arangojs/blob/main/_autodocs/api-reference/graphs.md Examples of inserting and fetching vertex documents within a graph. ```APIDOC ## Work with Vertices ### Description Demonstrates operations on vertex collections within a graph, including insertion and retrieval. ### Usage ```javascript const users = graph.vertexCollection("users"); // Insert vertices const alice = await users.insert({ name: "Alice", age: 30 }); const bob = await users.insert({ name: "Bob", age: 25 }); // Fetch vertex const user = await users.vertex("alice"); ``` ``` -------------------------------- ### Create Document Collection with Schema Source: https://github.com/arangodb/arangojs/blob/main/_autodocs/api-reference/database.md Example of creating a new document collection with a defined schema for its documents. ```javascript const users = await db.createCollection("users", { waitForSync: true, schema: { rule: { type: "object", properties: { email: { type: "string" }, age: { type: "integer" } }, required: ["email"] } } }); ``` -------------------------------- ### Build ArangoJS from Source Source: https://github.com/arangodb/arangojs/blob/main/CONTRIBUTING.md Clone the repository, install dependencies, and build the project. This is the first step to contributing or developing locally. ```sh git clone https://github.com/arangodb/arangojs.git cd arangojs npm install npm run build ``` -------------------------------- ### Example AQL Query with Bind Variables Source: https://github.com/arangodb/arangojs/blob/main/_autodocs/types.md Demonstrates how to construct an `AqlQuery` object with a query string and bind variables. This is a common pattern for executing parameterized AQL queries. ```typescript const query: AqlQuery = { query: `FOR user IN @@col FILTER user.age > @minAge RETURN user`, bindVars: { "@col": "users", minAge: 18 } }; const results = await db.query(query); ``` -------------------------------- ### Install ArangoDB Driver with npm or yarn Source: https://github.com/arangodb/arangojs/blob/main/README.md Install the arangojs package using npm or yarn for Node.js projects. ```sh npm install --save arangojs ## - or - yarn add arangojs ``` -------------------------------- ### Install `undici` for Unix Domain Sockets Source: https://github.com/arangodb/arangojs/blob/main/README.md Install the `undici` module as an optional peer dependency if you intend to use Unix domain sockets with arangojs. ```sh npm install --save undici ``` -------------------------------- ### Example: Add Edge Definition Source: https://github.com/arangodb/arangojs/blob/main/_autodocs/api-reference/graphs.md Demonstrates how to add a new edge definition named 'knows' connecting 'users' to 'users'. ```javascript const graph = db.graph("social"); await graph.addEdgeDefinition({ collection: "knows", from: ["users"], to: ["users"] }); ``` -------------------------------- ### getServiceConfiguration Source: https://github.com/arangodb/arangojs/blob/main/_autodocs/api-reference/routes-and-administration.md Retrieves the configuration for an installed Foxx service identified by its mount path. ```APIDOC ## getServiceConfiguration() ### Description Retrieves the configuration for an installed Foxx service identified by its mount path. ### Method `getServiceConfiguration` ### Parameters #### Path Parameters - **mount** (string) - Required - Service mount path ### Returns Promise ``` -------------------------------- ### Example of Aborting a Transaction on Error Source: https://github.com/arangodb/arangojs/blob/main/_autodocs/api-reference/transactions.md Demonstrates how to use a try-catch block to commit a transaction, and abort it if any step fails. ```javascript const trx = db.transaction(); try { await trx.step(() => collection.insert(doc1)); await trx.step(() => collection.insert(doc2)); await trx.commit(); } catch (err) { console.error("Transaction failed, rolling back"); await trx.abort(); } ``` -------------------------------- ### Query with Raw Object Source: https://github.com/arangodb/arangojs/blob/main/_autodocs/api-reference/database.md Example of executing an AQL query by providing a raw JavaScript object containing the query string and bind variables. ```javascript // Using raw object const cursor = await db.query({ query: "FOR user IN users RETURN user", bindVars: {} }); ``` -------------------------------- ### List Foxx Services Source: https://github.com/arangodb/arangojs/blob/main/_autodocs/api-reference/routes-and-administration.md Lists all installed Foxx services. Optionally excludes system services. ```typescript async listServices(excludeSystem?: boolean): Promise ``` -------------------------------- ### Query with String and Bind Variables Source: https://github.com/arangodb/arangojs/blob/main/_autodocs/api-reference/database.md Example of executing an AQL query using a string and providing bind variables for dynamic values. This is useful for parameterized queries. ```javascript // Using string and bindVars const cursor = await db.query( "FOR user IN @@col FILTER user.age >= @minAge RETURN user", { "@col": "users", minAge: 18 } ); ``` -------------------------------- ### Traverse Graph Source: https://github.com/arangodb/arangojs/blob/main/_autodocs/api-reference/graphs.md Example of performing a graph traversal using AQL to find paths and related vertices. ```APIDOC ## Traverse Graph ### Description Executes a graph traversal query using AQL to explore connections within the graph. ### Usage ```javascript const query = aql` FOR vertex, edge, path IN 1..3 ANY ${startVertex} GRAPH ${graph} RETURN { vertex, path: path.vertices[*]._key } `; const results = await db.query(query); ``` ``` -------------------------------- ### Traverse a Graph Source: https://github.com/arangodb/arangojs/blob/main/_autodocs/api-reference/graphs.md Example of a graph traversal query using AQL to explore paths of a specified depth. ```javascript const query = aql` FOR vertex, edge, path IN 1..3 ANY ${startVertex} GRAPH ${graph} RETURN { vertex, path: path.vertices[*]._key } `; const results = await db.query(query); ``` -------------------------------- ### Example Using AQL Literal for Inlining Source: https://github.com/arangodb/arangojs/blob/main/_autodocs/types.md Demonstrates using `aql.literal()` to create an `AqlLiteral` that is directly inlined into the AQL query. This is useful for functions like `DATE_NOW()` that should not be parameterized. ```typescript const now = aql.literal("DATE_NOW()"); const query = aql` FOR doc IN collection FILTER doc.createdAt > ${now} RETURN doc `; ``` -------------------------------- ### Basic Usage with async/await and ES Modules Source: https://github.com/arangodb/arangojs/blob/main/README.md Example demonstrating modern JavaScript usage with async/await and ES Modules to query for 'fire' type pokemons. Requires importing Database and aql. ```js import { Database, aql } from "arangojs"; const db = new Database(); const Pokemons = db.collection("my-pokemons"); async function main() { try { const pokemons = await db.query(aql` FOR pokemon IN ${Pokemons} FILTER pokemon.type == "fire" RETURN pokemon `); console.log("My pokemans, let me show you them:"); for await (const pokemon of pokemons) { console.log(pokemon.name); } } catch (err) { console.error(err.message); } } main(); ``` -------------------------------- ### Usage with Promises and CommonJS Source: https://github.com/arangodb/arangojs/blob/main/README.md Example demonstrating older JavaScript usage with promises and CommonJS for querying pokemons. This approach is suitable for environments without async/await support. ```js var arangojs = require("arangojs"); var Database = arangojs.Database; var db = new Database(); var pokemons = db.collection("pokemons"); db.query({ query: "FOR p IN @@c FILTER p.type == 'fire' RETURN p", bindVars: { "@c": "pokemons" }, }) .then(function (cursor) { console.log("My pokemons, let me show you them:"); return cursor.forEach(function (pokemon) { console.log(pokemon.name); }); }) .catch(function (err) { console.error(err.message); }); ``` -------------------------------- ### Access Edge Collection Source: https://github.com/arangodb/arangojs/blob/main/_autodocs/api-reference/database.md Example of how to get an edge collection reference and then access an edge within it. ```javascript const follows = db.edgeCollection("follows"); const edge = await follows.edge("user1->user2"); ``` -------------------------------- ### Access Document Collection Source: https://github.com/arangodb/arangojs/blob/main/_autodocs/api-reference/database.md Example of how to get a document collection reference and then access a document within it. ```javascript const users = db.collection("users"); const user = await users.document("john"); ``` -------------------------------- ### Instantiate Database with Configuration Source: https://github.com/arangodb/arangojs/blob/main/_autodocs/api-reference/database.md Use this when you need to specify connection details like URL, authentication, and pool size. ```javascript import { Database } from "arangojs"; // With configuration object const db = new Database({ url: "http://127.0.0.1:8529", databaseName: "myapp", auth: { username: "admin", password: "hunter2" } }); ``` -------------------------------- ### Example: Adding a Vertex Collection Source: https://github.com/arangodb/arangojs/blob/main/_autodocs/api-reference/graphs.md Shows how to add a new vertex collection named 'moderators' to a graph. The collection will be created if it doesn't already exist. ```javascript const graph = db.graph("social"); await graph.addVertexCollection("moderators"); ``` -------------------------------- ### engine() Source: https://github.com/arangodb/arangojs/blob/main/_autodocs/api-reference/routes-and-administration.md Gets storage engine information, including the engine name, endianness, and supported features. ```APIDOC ## engine() ### Description Gets storage engine information. ### Method GET ### Endpoint /_admin/engine ### Response #### Success Response (200) - **name** (string) - The name of the storage engine (e.g., 'rocksdb', 'mmfiles'). - **endianness** (string) - The endianness of the system ('little' or 'big'). - **features** (Array) - A list of features supported by the engine. ``` -------------------------------- ### Example: Replace Edge Definition Source: https://github.com/arangodb/arangojs/blob/main/_autodocs/api-reference/graphs.md Shows how to replace the 'follows' edge definition to include 'moderators' as a source vertex collection. ```javascript const graph = db.graph("social"); await graph.replaceEdgeDefinition("follows", { collection: "follows", from: ["users", "moderators"], to: ["users"] }); ``` -------------------------------- ### Get User Access Level for Database Source: https://github.com/arangodb/arangojs/blob/main/_autodocs/api-reference/users-and-jobs.md Retrieves the access level ('rw', 'ro', or 'none') for a specific user on a database. No setup is required beyond having a database instance. ```typescript async getUserAccessLevel( username: string, collection?: string ): Promise ``` -------------------------------- ### Instantiate Database with Defaults Source: https://github.com/arangodb/arangojs/blob/main/_autodocs/api-reference/database.md Create a Database instance using default connection parameters. ```javascript // Minimalist (uses defaults) const db = new Database(); ``` -------------------------------- ### Accessing Cursor Extras Source: https://github.com/arangodb/arangojs/blob/main/_autodocs/api-reference/cursors.md Example of how to access statistics, profiling data, and warnings from a cursor's extra information. Ensure profiling is enabled for the query. ```javascript const cursor = await db.query(query, { profile: true }); const stats = cursor.extra?.stats; const profile = cursor.extra?.profile; const warnings = cursor.extra?.warnings; if (warnings) { warnings.forEach(w => console.warn(`${w.code}: ${w.message}`)); } ``` -------------------------------- ### AQL Best Practice: Composing Queries from Fragments Source: https://github.com/arangodb/arangojs/blob/main/_autodocs/api-reference/aql.md Demonstrates how to build complex AQL queries by composing smaller, reusable query fragments. This improves readability and maintainability. ```javascript const filter1 = aql`FILTER doc.active == true`; const filter2 = aql`FILTER doc.verified == true`; const combined = aql`FOR doc IN col ${filter1} ${filter2} RETURN doc`; ``` -------------------------------- ### Create a Graph with Edge Definitions Source: https://github.com/arangodb/arangojs/blob/main/_autodocs/api-reference/graphs.md Demonstrates how to initialize a new graph with specified edge collections and their relationships. ```javascript const db = new Database(); const graph = await db.createGraph("social", [ { collection: "follows", from: ["users"], to: ["users"] }, { collection: "likes", from: ["users"], to: ["posts"] } ]); ``` -------------------------------- ### AQL Subquery Example Source: https://github.com/arangodb/arangojs/blob/main/_autodocs/api-reference/aql.md Illustrates the use of subqueries within an AQL query to fetch related data. The subquery result is assigned to a variable using LET. ```javascript const subquery = aql` (FOR post IN posts FILTER post.userId == user._id RETURN post._id) `; const query = aql` FOR user IN users LET posts = ${subquery} RETURN { user, postIds: posts } `; ``` -------------------------------- ### Get Document Collection Reference Source: https://github.com/arangodb/arangojs/blob/main/_autodocs/api-reference/database.md Use this to get a reference to an existing document collection by its name. This does not create the collection. ```typescript collection(name: string): DocumentCollection ``` -------------------------------- ### Instantiate Database with URL and Name Source: https://github.com/arangodb/arangojs/blob/main/_autodocs/api-reference/database.md Instantiate the Database class with a server URL and a specific database name. ```javascript // With URL and name const db = new Database("http://127.0.0.1:8529", "myapp"); db.useBasicAuth("admin", "hunter2"); ``` -------------------------------- ### Configure ArangoDB Driver with Custom URL and Authentication Source: https://github.com/arangodb/arangojs/blob/main/README.md Example showing how to instantiate the Database with a custom URL, database name, and authentication credentials. Credentials can be updated later using useBasicAuth. ```js const db = new Database({ url: "http://127.0.0.1:8529", databaseName: "pancakes", auth: { username: "root", password: "hunter2" }, }); // The credentials can be swapped at any time db.useBasicAuth("admin", "maplesyrup"); ``` -------------------------------- ### Install Specific ArangoJS Version Source: https://github.com/arangodb/arangojs/blob/main/README.md Use npm or yarn to install a specific major version of arangojs, such as version 9.x.x. ```sh yarn add arangojs@9 # - or - npm install --save arangojs@9 ``` -------------------------------- ### Send GET Request with Route Source: https://github.com/arangodb/arangojs/blob/main/_autodocs/api-reference/routes-and-administration.md Sends a GET request to a specified path relative to the route. Use when retrieving data. ```javascript const foxx = db.route("/my-service"); const users = await foxx.get("users"); ``` -------------------------------- ### Example: Using isAqlQuery to validate and execute an AQL query Source: https://github.com/arangodb/arangojs/blob/main/_autodocs/api-reference/aql.md Demonstrates how to use the `isAqlQuery` type guard to ensure a variable holds a valid AQL query object before executing it with `db.query()`. ```javascript const query = { query: "RETURN 1", bindVars: {} }; if (isAqlQuery(query)) { console.log("Valid AQL query"); await db.query(query); } ``` -------------------------------- ### Get Collection Checksum Source: https://github.com/arangodb/arangojs/blob/main/_autodocs/api-reference/collections.md Gets a checksum for the collection's data, optionally including checksums for individual documents. Useful for data integrity verification. ```typescript async checksum(options?: { withData?: boolean }): Promise ``` -------------------------------- ### Get edges connected to a vertex Source: https://github.com/arangodb/arangojs/blob/main/_autodocs/api-reference/graphs.md Use the `edges` method to retrieve all edges connected to a specified vertex. You can filter by direction (incoming, outgoing, or any) to get specific relationships. ```javascript const follows = graph.edgeCollection("follows"); // Followers of alice const incoming = await follows.edges("users/alice", { direction: "in" }); console.log(incoming.edges); // Users alice follows const outgoing = await follows.edges("users/alice", { direction: "out" }); console.log(outgoing.edges); ``` -------------------------------- ### view() Source: https://github.com/arangodb/arangojs/blob/main/_autodocs/api-reference/database.md Gets a reference to a view by its name. ```APIDOC ## view() ### Description Gets a reference to a view. ### Method Not applicable (SDK method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters #### Path Parameters - **name** (string) - Required - Name of the view ### Response #### Success Response - **View instance** - Returns a View instance. ### Example ```javascript const userView = db.view("users_search"); ``` ``` -------------------------------- ### Example of Composing Generated AQL Queries Source: https://github.com/arangodb/arangojs/blob/main/_autodocs/types.md Shows how to use the `aql` template tag to create reusable AQL fragments (`filterFragment`) and compose them into a larger query. This enhances modularity in AQL construction. ```typescript const filterFragment: GeneratedAqlQuery = aql`FILTER doc.status == "active"`; const query = aql` FOR doc IN @@col ${filterFragment} RETURN doc `; ``` -------------------------------- ### count() Source: https://github.com/arangodb/arangojs/blob/main/_autodocs/api-reference/collections.md Gets the number of documents in the collection. ```APIDOC ## count() ### Description Gets the number of documents in the collection. ### Method GET (Implicit) ### Endpoint (Collection specific endpoint, details not provided) ### Returns Promise ### Response Example ```json 100 ``` ``` -------------------------------- ### analyzer() Source: https://github.com/arangodb/arangojs/blob/main/_autodocs/api-reference/database.md Gets a reference to an existing analyzer by its name. ```APIDOC ## analyzer() ### Description Gets a reference to an analyzer. ### Method Not applicable (SDK method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters #### Path Parameters - **name** (string) - Required - Name of the analyzer ### Returns Analyzer instance ``` -------------------------------- ### collection() Source: https://github.com/arangodb/arangojs/blob/main/_autodocs/api-reference/database.md Gets a reference to a document collection by its name. ```APIDOC ## collection() ### Description Gets a reference to a document collection. ### Signature ```typescript collection(name: string): DocumentCollection ``` ### Parameters #### Path Parameters - **name** (string) - Required - Name of the collection ### Returns DocumentCollection instance ### Example ```javascript const users = db.collection("users"); const user = await users.document("john"); ``` ``` -------------------------------- ### queryTracking Source: https://github.com/arangodb/arangojs/blob/main/_autodocs/api-reference/routes-and-administration.md Gets query execution tracking statistics. ```APIDOC ## queryTracking() ### Description Gets query execution tracking statistics. ### Method `queryTracking` ### Returns Promise ``` -------------------------------- ### status() Source: https://github.com/arangodb/arangojs/blob/main/_autodocs/api-reference/routes-and-administration.md Gets the current operational status of the ArangoDB server. ```APIDOC ## status() ### Description Gets server operational status. ### Method GET ### Endpoint /_admin/status ### Response #### Success Response (200) - **running** (boolean) - Indicates if the server is running. - **lastIntError** (number) - The last internal error code. - **lastSrvState** (string) - The last server state. ``` -------------------------------- ### properties() Source: https://github.com/arangodb/arangojs/blob/main/_autodocs/api-reference/collections.md Gets collection properties such as schema, waitForSync, and replicationFactor. ```APIDOC ## properties() ### Description Gets collection properties (schema, waitForSync, replicationFactor, etc.). ### Method GET (Implicit) ### Endpoint (Collection specific endpoint, details not provided) ### Returns Promise ### Response Example ```json { "schema": {}, "waitForSync": false, "replicationFactor": 1 } ``` ``` -------------------------------- ### Configure Basic Authentication Source: https://github.com/arangodb/arangojs/blob/main/_autodocs/configuration.md Use this snippet to establish a connection using username and password authentication. ```javascript import { Database } from "arangojs"; const db = new Database({ url: "http://127.0.0.1:8529", databaseName: "myapp", auth: { username: "admin", password: "hunter2" } }); ``` -------------------------------- ### Transaction.get() Source: https://github.com/arangodb/arangojs/blob/main/_autodocs/api-reference/transactions.md Gets the current transaction's status and metadata. ```APIDOC ## Transaction.get() Gets transaction status and metadata. ### Method `async get(): Promise` ### Returns - `Promise` - Transaction status and metadata ### Example ```javascript const trx = db.transaction(); const status = await trx.get(); console.log(status.id); ``` ``` -------------------------------- ### get() Source: https://github.com/arangodb/arangojs/blob/main/_autodocs/api-reference/collections.md Retrieves collection metadata such as type, status, and document counts. ```APIDOC ## get() ### Description Retrieves collection metadata (type, status, counts, etc.). ### Method GET (Implicit) ### Endpoint (Collection specific endpoint, details not provided) ### Returns Promise ### Response Example ```json { "status": 3, "type": 2, "count": 100, "id": "12345", "name": "users" } ``` ``` -------------------------------- ### route() Source: https://github.com/arangodb/arangojs/blob/main/_autodocs/api-reference/database.md Creates a Route instance for arbitrary HTTP requests against the database, useful for accessing custom Foxx services or undocumented endpoints. ```APIDOC ## route(path?: string, headers?: Headers | Record) ### Description Creates a Route instance for arbitrary HTTP requests against the database. ### Method POST (for creating the route instance, actual HTTP method depends on the subsequent request made via the route) ### Endpoint /route ### Parameters #### Query Parameters - **path** (string) - Optional - Database-relative URL path. - **headers** (object) - Optional - Default headers for requests. ### Request Example ```javascript const foxx = db.route("/my-service"); const result = await foxx.post("users", { username: "alice", password: "secret" }); ``` ### Response #### Success Response (200) - **Route** (object) - A Route instance that can be used to make further HTTP requests. ### Response Example (The response here is an object representing the Route instance, not a direct API response. The actual response comes from methods called on the returned Route object.) ```json { "_isRoute": true } ``` ``` -------------------------------- ### Work with Edges Source: https://github.com/arangodb/arangojs/blob/main/_autodocs/api-reference/graphs.md Examples of inserting and retrieving edge documents between vertices in a graph. ```APIDOC ## Work with Edges ### Description Shows how to insert and query edge documents, linking vertices within the graph. ### Usage ```javascript const follows = graph.edgeCollection("follows"); // Insert edges await follows.insert({ _from: alice._id, _to: bob._id, since: "2023-01-01" }); // Get edges const following = await follows.edges(alice._key, { direction: "out" }); console.log(following.edges); ``` ``` -------------------------------- ### create() Source: https://github.com/arangodb/arangojs/blob/main/_autodocs/api-reference/collections.md Creates this collection in the database. Typically, Database#createCollection() is preferred. ```APIDOC ## create() ### Description Creates this collection in the database. ### Method POST (Implicit) ### Endpoint (Collection specific endpoint, details not provided) ### Parameters #### Request Body - **options** (CreateCollectionOptions) - Optional - Collection configuration ### Returns Promise> ``` -------------------------------- ### availability() Source: https://github.com/arangodb/arangojs/blob/main/_autodocs/api-reference/routes-and-administration.md Gets the server's availability status, which can be 'default', 'readonly', or false. ```APIDOC ## availability() ### Description Gets server availability status. ### Method GET ### Endpoint /_admin/availability ### Response #### Success Response (200) - **availability** (string) - Server availability status ('default', 'readonly', or false). ``` -------------------------------- ### Work with Vertex Collections Source: https://github.com/arangodb/arangojs/blob/main/_autodocs/api-reference/graphs.md Shows how to access a vertex collection and perform insert and fetch operations. ```javascript const users = graph.vertexCollection("users"); // Insert vertices const alice = await users.insert({ name: "Alice", age: 30 }); const bob = await users.insert({ name: "Bob", age: 25 }); // Fetch vertex const user = await users.vertex("alice"); ``` -------------------------------- ### Database.getUser() Source: https://github.com/arangodb/arangojs/blob/main/_autodocs/api-reference/users-and-jobs.md Gets information about a specific user. Throws an ArangoError if the user is not found. ```APIDOC ## Database.getUser(username) ### Description Gets information about a specific user. ### Method GET ### Endpoint /api/users/{username} ### Parameters #### Path Parameters - **username** (string) - Required - Username to retrieve ### Response #### Success Response (200) - **user** (ArangoUser) - User object ### Response Example { "_key": "123", "_id": "users/123", "_rev": "_abc", "user": "admin", "active": true, "extra": {} } ``` -------------------------------- ### Persistent Index Example Source: https://github.com/arangodb/arangojs/blob/main/_autodocs/types.md Defines the structure for a persistent index, which can be unique, sparse, and deduplicated. ```typescript interface PersistentIndex { id: string; type: "persistent"; fields: string[]; unique?: boolean; sparse?: boolean; deduplicate?: boolean; estimates?: boolean; selectivityEstimate?: number; } ``` -------------------------------- ### User Management Workflow Source: https://github.com/arangodb/arangojs/blob/main/_autodocs/api-reference/users-and-jobs.md Demonstrates a complete user management workflow including creation, setting access levels, updating user information, and generating API tokens. ```javascript // Create new user const user = await db.createUser("developer", { password: "initial_password", active: true, extra: { team: "backend", email: "dev@example.com" } }); // Grant database access await db.setUserAccessLevel("developer", "rw"); // Restrict access to specific collections await db.setUserAccessLevel("developer", "ro", "customer_data"); await db.setUserAccessLevel("developer", "none", "admin_only"); // Verify access const dbAccess = await db.getUserAccessLevel("developer"); const colAccess = await db.getUserAccessLevel("developer", "customer_data"); // Update user await db.updateUser("developer", { extra: { team: "frontend" } }); // Change password await db.updateUser("developer", { password: "new_secure_password" }); // Create API token for automated access const token = await db.createAccessToken("developer", { ttl: 86400 }); console.log("API Token:", token); // List all users const allUsers = await db.listUsers(); ``` -------------------------------- ### Graph Traversal in AQL Source: https://github.com/arangodb/arangojs/blob/main/_autodocs/api-reference/aql.md Demonstrates how to perform graph traversals in AQL using the `GRAPH` keyword and specifying traversal depth. It returns vertices and their depth in the traversal path. ```javascript const graph = db.graph("social"); const startId = "users/alice"; const maxDepth = 3; const query = aql` FOR vertex, edge, path IN 1..${maxDepth} ANY ${startId} GRAPH ${graph} RETURN { vertex, depth: LENGTH(path.vertices) - 1 } `; ``` -------------------------------- ### time() Source: https://github.com/arangodb/arangojs/blob/main/_autodocs/api-reference/routes-and-administration.md Gets the current server time as a UNIX timestamp in seconds since the epoch. ```APIDOC ## time() ### Description Gets current server time as UNIX timestamp. ### Method GET ### Endpoint /_admin/time ### Response #### Success Response (200) - **time** (number) - Seconds since epoch. ``` -------------------------------- ### Common Use Cases for AQL Literal Source: https://github.com/arangodb/arangojs/blob/main/_autodocs/api-reference/aql.md Illustrates common scenarios for using literal(), including function calls like DATE_NOW() and DATE_ADD(), operators, and AQL keywords such as DESC for sorting. ```javascript // Function calls const now = aql.literal("DATE_NOW()"); const tomorrow = aql.literal("DATE_ADD(DATE_NOW(), 1, 'day')"); // Operators const op = aql.literal("||"); const condition = aql`${expr1} ${op} ${expr2}`; // AQL keywords const descending = aql.literal("DESC"); const query = aql` FOR doc IN collection SORT doc.score ${descending} RETURN doc `; ``` -------------------------------- ### Query with aql Template Tag Source: https://github.com/arangodb/arangojs/blob/main/_autodocs/api-reference/database.md Example of executing an AQL query using the `aql` template tag for type safety and easier variable interpolation. Iterates over the returned cursor. ```javascript // Using aql template tag const minAge = 18; const cursor = await db.query(aql` FOR user IN users FILTER user.age >= ${minAge} RETURN user `); for await (const user of cursor) { console.log(user.name); } ``` -------------------------------- ### Simple Iteration Source: https://github.com/arangodb/arangojs/blob/main/_autodocs/api-reference/cursors.md Demonstrates how to iterate over the results of a query using a cursor in a simple for-await-of loop. ```APIDOC ## Simple Iteration ```javascript const cursor = await db.query(aql` FOR user IN users RETURN user `); for await (const user of cursor) { console.log(user.name); } ``` ``` -------------------------------- ### Get Query Tracking Statistics Source: https://github.com/arangodb/arangojs/blob/main/_autodocs/api-reference/routes-and-administration.md Fetches the current statistics related to query execution tracking. ```typescript async queryTracking(): Promise ``` -------------------------------- ### Dynamic Field Selection in AQL Source: https://github.com/arangodb/arangojs/blob/main/_autodocs/api-reference/aql.md Shows how to dynamically select fields from a collection in an AQL query. It uses `aql.join` to construct a comma-separated list of field names for the RETURN clause. ```javascript const fields = ["name", "email", "age"]; const fieldList = aql.join( fields.map(f => aql`${aql.literal(`user.${f}`)}`), ", " ); const query = aql` FOR user IN users RETURN { ${fieldList} } `; ``` -------------------------------- ### getLicense() Source: https://github.com/arangodb/arangojs/blob/main/_autodocs/api-reference/routes-and-administration.md Gets the current license information for the ArangoDB server, including license type and expiration. ```APIDOC ## getLicense() ### Description Gets license information. ### Method GET ### Endpoint /_admin/license ### Response #### Success Response (200) - **license** (string) - The type of license installed. - **expires** (string) - The expiration date of the license (ISO 8601 format). - **validUntil** (string) - The date until which the license is valid (ISO 8601 format). ``` -------------------------------- ### Integrate with Custom Foxx Services Source: https://github.com/arangodb/arangojs/blob/main/_autodocs/api-reference/routes-and-administration.md Use the `db.route()` method to create a client for a Foxx service. Perform CRUD operations like GET, POST, PUT, and DELETE on service endpoints. ```javascript const foxx = db.route("/api/v1"); // Get service data const users = await foxx.get("users"); // Create data const newUser = await foxx.post("users", { name: "Alice", email: "alice@example.com" }); // Update data const updated = await foxx.put(`users/${newUser._key}`, { email: "alice.new@example.com" }); // Delete data await foxx.delete(`users/${newUser._key}`); ``` -------------------------------- ### edgeCollection() Source: https://github.com/arangodb/arangojs/blob/main/_autodocs/api-reference/graphs.md Gets a reference to an edge collection within a graph. This allows for direct manipulation of edges. ```APIDOC ## edgeCollection(name: string) ### Description Gets a reference to an edge collection in this graph. ### Parameters #### Path Parameters - **name** (string) - Required - Name of the edge collection ### Returns GraphEdgeCollection ### Example ```javascript const graph = db.graph("social"); const follows = graph.edgeCollection("follows"); ``` ``` -------------------------------- ### Cursor Iteration: Emulating `some` with `forEach` Source: https://github.com/arangodb/arangojs/blob/main/MIGRATING.md If AQL modification is not possible, emulate the `some` method's behavior by using `forEach` and negating the result of checking for the condition. ```diff -const someJustRight = await cursor.some( - (bowl) => bowl.temperature < TOO_HOT && bowl.temperature > TOO_COLD -); +const someJustRight = !(await cursor.forEach( + (bowl) => bowl.temperature === TOO_HOT || bowl.temperature === TOO_COLD +)); ``` -------------------------------- ### checksum() Source: https://github.com/arangodb/arangojs/blob/main/_autodocs/api-reference/collections.md Gets the checksum for collection data, used for verifying data integrity or detecting changes. ```APIDOC ## checksum() ### Description Gets checksum for collection data. Used to verify data integrity or detect changes. ### Method GET (Implicit) ### Endpoint (Collection specific endpoint, details not provided) ### Parameters #### Query Parameters - **withData** (boolean) - Optional - Include checksums for each document ### Returns Promise ### Response Example ```json { "checksum": "12345abcde", "withRevisions": false } ``` ``` -------------------------------- ### Reuse Database Instance Source: https://github.com/arangodb/arangojs/blob/main/_autodocs/README.md Create a single Database instance and reuse it for all subsequent operations to improve performance. ```javascript const db = new Database({ url: "...", auth: "..." }); // Reuse db for all operations ``` -------------------------------- ### Correct Usage of Transaction.step() Source: https://github.com/arangodb/arangojs/blob/main/_autodocs/api-reference/transactions.md Demonstrates the correct way to use the `step` method for multiple database operations within a transaction, ensuring each operation is in its own step. ```javascript const collection = db.collection("users"); const trx = db.transaction(); // Step 1: Insert document await trx.step(() => collection.insert({ name: "Alice" })); // Step 2: Insert another document await trx.step(() => collection.insert({ name: "Bob" })); // Step 3: Count documents const count = await trx.step( () => collection.count(), { read: ["users"] } ); console.log(`Total users: ${count}`); ``` -------------------------------- ### Get Collection Properties Source: https://github.com/arangodb/arangojs/blob/main/_autodocs/api-reference/collections.md Retrieves detailed properties of a collection, such as schema configuration and replication settings. ```typescript async properties(): Promise ``` -------------------------------- ### Database Constructor Source: https://github.com/arangodb/arangojs/blob/main/_autodocs/api-reference/database.md Initializes a new Database instance, establishing a connection to an ArangoDB server. It can be configured using a configuration object, a URL and database name, or by deriving from an existing Database instance. ```APIDOC ## Constructor Database ### Description Initializes a new Database instance with its own connection pool. ### Parameters #### Constructor Overloads - `config?: ConfigOptions` - Configuration object with url, auth, poolSize, etc. - `url: string | string[]`, `name?: string` - Base URL(s) of ArangoDB server or list for clustering, and the database name. - `database: Database`, `name?: string` - Internal: another Database instance to derive connection from, and an optional database name. ### Returns Database instance ### Example ```javascript import { Database } from "arangojs"; // With configuration object const db = new Database({ url: "http://127.0.0.1:8529", databaseName: "myapp", auth: { username: "admin", password: "hunter2" } }); // With URL and name const db = new Database("http://127.0.0.1:8529", "myapp"); db.useBasicAuth("admin", "hunter2"); // Minimalist (uses defaults) const db = new Database(); ``` ``` -------------------------------- ### createView() Source: https://github.com/arangodb/arangojs/blob/main/_autodocs/api-reference/database.md Creates a new view with specified options. ```APIDOC ## createView() ### Description Creates a new view. ### Method Not applicable (SDK method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters #### Path Parameters - **name** (string) - Required - Name for the new view - **options** (CreateViewOptions) - Optional - View type and configuration ### Response #### Success Response - **Promise** - A promise that resolves to the created View instance. ### Example ```javascript const view = await db.createView("users_search", { type: "arangosearch", links: { users: { fields: { name: {}, email: {} } } } }); ``` ``` -------------------------------- ### RequestAbortedError Class Definition Source: https://github.com/arangodb/arangojs/blob/main/_autodocs/errors.md Defines the RequestAbortedError, indicating that a request was explicitly cancelled, for example, using an AbortController. ```typescript class RequestAbortedError extends NetworkError { name: "RequestAbortedError"; } ``` -------------------------------- ### Basic AQL Query with Collection and Variable Source: https://github.com/arangodb/arangojs/blob/main/_autodocs/api-reference/aql.md Construct a basic AQL query by interpolating a collection reference and a variable. The collection is automatically converted to a bind parameter. ```javascript const users = db.collection("users"); const minAge = 18; const query = aql` FOR user IN ${users} FILTER user.age >= ${minAge} RETURN user `; // Equivalent to: // { // query: "FOR user IN @@col0 FILTER user.age >= @value1 RETURN user", // bindVars: { "@col0": "users", value1: 18 } // } const cursor = await db.query(query); ``` -------------------------------- ### Get Graph Reference Source: https://github.com/arangodb/arangojs/blob/main/_autodocs/api-reference/database.md Retrieves a reference to an existing graph by its name. Use this to access graph-specific operations. ```typescript graph(name: string): Graph ``` -------------------------------- ### Get Analyzer Definition Source: https://github.com/arangodb/arangojs/blob/main/_autodocs/api-reference/views-and-analyzers.md Retrieves the definition and properties of a named analyzer. Use this to inspect an existing analyzer. ```javascript const analyzer = db.analyzer("my_text"); const def = await analyzer.get(); console.log(def.type); ``` -------------------------------- ### Statistics and Profiling Source: https://github.com/arangodb/arangojs/blob/main/_autodocs/api-reference/cursors.md Illustrates how to enable query profiling using the `profile: true` option and access execution statistics from the cursor's `extra.stats`. ```APIDOC ## Statistics and Profiling ```javascript const cursor = await db.query( aql` FOR user IN users FILTER user.age > @age RETURN user `, { profile: true } ); const stats = cursor.extra?.stats; if (stats) { console.log(`Scanned: ${stats.scannedIndex}`); console.log(`Filtered: ${stats.filtered}`); console.log(`Time: ${stats.executionTime}s`); } ``` ``` -------------------------------- ### Monitor Server Information Source: https://github.com/arangodb/arangojs/blob/main/_autodocs/api-reference/routes-and-administration.md Retrieve and log detailed server information, including version, engine, license, and the number of running services, using methods like `db.version()`, `db.engine()`, `db.supportInfo()`, and `db.listServices()`. ```javascript async function monitorServer() { const version = await db.version(); const engine = await db.engine(); const support = await db.supportInfo(); console.log("Server Info:"); console.log(` Version: ${version.version}`); console.log(` Engine: ${engine.name}`); console.log(` License: ${version.license}`); // Check specific services const services = await db.listServices(); console.log(` Services: ${services.length}`); } ``` -------------------------------- ### TTL Index Example Source: https://github.com/arangodb/arangojs/blob/main/_autodocs/types.md Defines the structure for a time-to-live (TTL) index, which automatically removes documents after a specified period. ```typescript interface TtlIndex { id: string; type: "ttl"; fields: string[]; expireAfter: number; // seconds } ```