arangojs

  • Version 8.8.1
  • Published
  • 2.34 MB
  • 5 dependencies
  • Apache-2.0 license

Install

npm i arangojs
yarn add arangojs
pnpm add arangojs

Overview

import arangojs, { aql, Database } from "arangojs";

The "index" module is the default entry point when importing the arangojs module or using the web build in the browser.

If you are just getting started, you probably want to use the arangojs function, which is also the default export of this module, or the database.Database class for which it is a wrapper.

Index

Functions

Classes

Functions

function aql

aql: <T = any>(
templateStrings: TemplateStringsArray,
...args: AqlValue[]
) => GeneratedAqlQuery<T>;
  • Template string handler (template tag) for AQL queries.

    The aql tag can be used to write complex AQL queries as multi-line strings without having to worry about bindVars and the distinction between collections and regular parameters.

    Tagged template strings will return an AqlQuery object with query and bindVars attributes reflecting any interpolated values.

    Any collection.ArangoCollection instance used in a query string will be recognized as a collection reference and generate an AQL collection bind parameter instead of a regular AQL value bind parameter.

    **Note**: you should always use the aql template tag when writing dynamic AQL queries instead of using untagged (normal) template strings. Untagged template strings will inline any interpolated values and return a plain string as result. The aql template tag will only inline references to the interpolated values and produce an AQL query object containing both the query and the values. This prevents most injection attacks when using untrusted values in dynamic queries.

    Example 1

    // Some user-supplied string that may be malicious
    const untrustedValue = req.body.email;
    // Without aql tag: BAD! DO NOT DO THIS!
    const badQuery = `
    FOR user IN users
    FILTER user.email == "${untrustedValue}"
    RETURN user
    `;
    // e.g. if untrustedValue is '" || user.admin == true || "':
    // Query:
    // FOR user IN users
    // FILTER user.email == "" || user.admin == true || ""
    // RETURN user
    // With the aql tag: GOOD! MUCH SAFER!
    const betterQuery = aql`
    FOR user IN users
    FILTER user.email == ${untrustedValue}
    RETURN user
    `;
    // Query:
    // FOR user IN users
    // FILTER user.email == @value0
    // RETURN user
    // Bind parameters:
    // value0 -> untrustedValue

    Example 2

    const collection = db.collection("some-collection");
    const minValue = 23;
    const result = await db.query(aql`
    FOR d IN ${collection}
    FILTER d.num > ${minValue}
    RETURN d
    `);
    // Equivalent raw query object
    const result2 = await db.query({
    query: `
    FOR d IN @@collection
    FILTER d.num > @minValue
    RETURN d
    `,
    bindVars: {
    "@collection": collection.name,
    minValue: minValue
    }
    });

    Example 3

    const collection = db.collection("some-collection");
    const color = "green";
    const filter = aql`FILTER d.color == ${color}'`;
    const result = await db.query(aql`
    FOR d IN ${collection}
    ${filter}
    RETURN d
    `);

function arangojs

arangojs: {
(config?: Config): Database;
(url: string | string[], name?: string): Database;
};
  • Creates a new Database instance with its own connection pool.

    This is a wrapper function for the .

    Parameter config

    An object with configuration options.

    Example 1

    const db = arangojs({
    url: "http://127.0.0.1:8529",
    databaseName: "myDatabase",
    auth: { username: "admin", password: "hunter2" },
    });
  • Creates a new Database instance with its own connection pool.

    This is a wrapper function for the .

    Parameter url

    Base URL of the ArangoDB server or list of server URLs. Equivalent to the url option in connection.Config.

    Example 1

    const db = arangojs("http://127.0.0.1:8529", "myDatabase");
    db.useBasicAuth("admin", "hunter2");

Classes

class Database

class Database {}
  • An object representing a single ArangoDB database. All arangojs collections, cursors, analyzers and so on are linked to a Database object.

constructor

constructor(config?: Config);
  • Creates a new Database instance with its own connection pool.

    See also Database#database.

    Parameter config

    An object with configuration options.

    Example 1

    const db = new Database({
    url: "http://127.0.0.1:8529",
    databaseName: "my_database",
    auth: { username: "admin", password: "hunter2" },
    });

constructor

constructor(url: string | string[], name?: string);
  • Creates a new Database instance with its own connection pool.

    See also Database#database.

    Parameter url

    Base URL of the ArangoDB server or list of server URLs. Equivalent to the url option in connection.Config.

    Example 1

    const db = new Database("http://127.0.0.1:8529", "my_database");
    db.useBasicAuth("admin", "hunter2");

property name

readonly name: string;
  • Name of the ArangoDB database this instance represents.

property queueTime

readonly queueTime: QueueTimeMetrics;
  • Methods for accessing the server-reported queue times of the mostly recently received responses.

method acquireHostList

acquireHostList: (overwrite?: boolean) => Promise<void>;
  • Updates the URL list by requesting a list of all coordinators in the cluster and adding any endpoints not initially specified in the connection.Config.

    For long-running processes communicating with an ArangoDB cluster it is recommended to run this method periodically (e.g. once per hour) to make sure new coordinators are picked up correctly and can be used for fail-over or load balancing.

    Parameter overwrite

    If set to true, the existing host list will be replaced instead of extended.

    Example 1

    const db = new Database();
    const interval = setInterval(
    () => db.acquireHostList(),
    5 * 60 * 1000 // every 5 minutes
    );
    // later
    clearInterval(interval);
    system.close();

method analyzer

analyzer: (analyzerName: string) => Analyzer;
  • Returns an analyzer.Analyzer instance representing the Analyzer with the given analyzerName.

    Example 1

    const db = new Database();
    const analyzer = db.analyzer("some-analyzer");
    const info = await analyzer.get();

method analyzers

analyzers: () => Promise<Analyzer[]>;
  • Fetches all Analyzers visible in the database and returns an array of analyzer.Analyzer instances for those Analyzers.

    See also Database#listAnalyzers.

    Example 1

    const db = new Database();
    const analyzers = await db.analyzers();
    // analyzers is an array of Analyzer instances

method beginTransaction

beginTransaction: {
(
collections: TransactionCollections,
options?: TransactionOptions
): Promise<Transaction>;
(
collections: (string | ArangoCollection)[],
options?: TransactionOptions
): Promise<Transaction>;
(
collection: string | ArangoCollection,
options?: TransactionOptions
): Promise<Transaction>;
};
  • Begins a new streaming transaction for the given collections, then returns a transaction.Transaction instance for the transaction.

    Collections can be specified as collection names (strings) or objects implementing the collection.ArangoCollection interface: Collection, graph.GraphVertexCollection, graph.GraphEdgeCollection as well as (in TypeScript) collection.DocumentCollection and collection.EdgeCollection.

    Parameter collections

    Collections involved in the transaction.

    Parameter options

    Options for the transaction.

    Example 1

    const vertices = db.collection("vertices");
    const edges = db.collection("edges");
    const trx = await db.beginTransaction({
    read: ["vertices"],
    write: [edges] // collection instances can be passed directly
    });
    const start = await trx.step(() => vertices.document("a"));
    const end = await trx.step(() => vertices.document("b"));
    await trx.step(() => edges.save({ _from: start._id, _to: end._id }));
    await trx.commit();
  • Begins a new streaming transaction for the given collections, then returns a transaction.Transaction instance for the transaction.

    Collections can be specified as collection names (strings) or objects implementing the collection.ArangoCollection interface: Collection, graph.GraphVertexCollection, graph.GraphEdgeCollection as well as (in TypeScript) collection.DocumentCollection and collection.EdgeCollection.

    Parameter collections

    Collections that can be read from and written to during the transaction.

    Parameter options

    Options for the transaction.

    Example 1

    const vertices = db.collection("vertices");
    const edges = db.collection("edges");
    const trx = await db.beginTransaction([
    "vertices",
    edges // collection instances can be passed directly
    ]);
    const start = await trx.step(() => vertices.document("a"));
    const end = await trx.step(() => vertices.document("b"));
    await trx.step(() => edges.save({ _from: start._id, _to: end._id }));
    await trx.commit();
  • Begins a new streaming transaction for the given collections, then returns a transaction.Transaction instance for the transaction.

    The Collection can be specified as a collection name (string) or an object implementing the collection.ArangoCollection interface: Collection, graph.GraphVertexCollection, graph.GraphEdgeCollection as well as (in TypeScript) collection.DocumentCollection and collection.EdgeCollection.

    Parameter collection

    A collection that can be read from and written to during the transaction.

    Parameter options

    Options for the transaction.

    Example 1

    const vertices = db.collection("vertices");
    const start = vertices.document("a");
    const end = vertices.document("b");
    const edges = db.collection("edges");
    const trx = await db.beginTransaction(
    edges // collection instances can be passed directly
    );
    await trx.step(() => edges.save({ _from: start._id, _to: end._id }));
    await trx.commit();

method clearSlowQueries

clearSlowQueries: () => Promise<void>;
  • Clears the list of recent slow queries.

    See also Database#listSlowQueries.

    Example 1

    const db = new Database();
    await db.clearSlowQueries();
    // Slow query list is now cleared

method clearUserAccessLevel

clearUserAccessLevel: (
username: string,
{ database, collection }: UserAccessLevelOptions
) => Promise<ArangoApiResponse<Record<string, AccessLevel>>>;
  • Clears the given ArangoDB user's access level for the database, or the given collection in the given database.

    Parameter username

    Name of the ArangoDB user to clear the access level for.

    Parameter database

    Database to clear the access level for.

    Parameter collection

    Collection to clear the access level for.

    Example 1

    const db = new Database();
    await db.clearUserAccessLevel("steve");
    // The access level of the user "steve" has been cleared for the current
    // database.

    Example 2

    const db = new Database();
    await db.clearUserAccessLevel("steve", { database: "staging" });
    // The access level of the user "steve" has been cleared for the "staging"
    // database.

    Example 3

    const db = new Database();
    await db.clearUserAccessLevel("steve", { collection: "pokemons" });
    // The access level of the user "steve" has been cleared for the
    // "pokemons" collection in the current database.

    Example 4

    const db = new Database();
    await db.clearUserAccessLevel("steve", {
    database: "staging",
    collection: "pokemons"
    });
    // The access level of the user "steve" has been cleared for the
    // "pokemons" collection in the "staging" database.

    Example 5

    const db = new Database();
    const staging = db.database("staging");
    await db.clearUserAccessLevel("steve", { database: staging });
    // The access level of the user "steve" has been cleared for the "staging"
    // database.

    Example 6

    const db = new Database();
    const staging = db.database("staging");
    await db.clearUserAccessLevel("steve", {
    collection: staging.collection("pokemons")
    });
    // The access level of the user "steve" has been cleared for the
    // "pokemons" collection in database "staging".

method close

close: () => void;
  • Closes all active connections of this database instance.

    Can be used to clean up idling connections during longer periods of inactivity.

    **Note**: This method currently has no effect in the browser version of arangojs.

    Example 1

    const db = new Database();
    const sessions = db.collection("sessions");
    // Clean up expired sessions once per hour
    setInterval(async () => {
    await db.query(aql`
    FOR session IN ${sessions}
    FILTER session.expires < DATE_NOW()
    REMOVE session IN ${sessions}
    `);
    // Making sure to close the connections because they're no longer used
    system.close();
    }, 1000 * 60 * 60);

method collection

collection: <T extends Record<string, any> = any>(
collectionName: string
) => DocumentCollection<T> & EdgeCollection<T>;
  • Returns a Collection instance for the given collection name.

    In TypeScript the collection implements both the collection.DocumentCollection and collection.EdgeCollection interfaces and can be cast to either type to enforce a stricter API.

    Parameter T

    Type to use for document data. Defaults to any.

    Parameter collectionName

    Name of the edge collection.

    Example 1

    const db = new Database();
    const collection = db.collection("potatoes");

    Example 2

    interface Person {
    name: string;
    }
    const db = new Database();
    const persons = db.collection<Person>("persons");

    Example 3

    interface Person {
    name: string;
    }
    interface Friend {
    startDate: number;
    endDate?: number;
    }
    const db = new Database();
    const documents = db.collection("persons") as DocumentCollection<Person>;
    const edges = db.collection("friends") as EdgeCollection<Friend>;

method collections

collections: (
excludeSystem?: boolean
) => Promise<Array<DocumentCollection & EdgeCollection>>;
  • Fetches all collections from the database and returns an array of Collection instances.

    In TypeScript these instances implement both the collection.DocumentCollection and collection.EdgeCollection interfaces and can be cast to either type to enforce a stricter API.

    See also Database#listCollections.

    Parameter excludeSystem

    Whether system collections should be excluded.

    Example 1

    const db = new Database();
    const collections = await db.collections();
    // collections is an array of DocumentCollection and EdgeCollection
    // instances not including system collections

    Example 2

    const db = new Database();
    const collections = await db.collections(false);
    // collections is an array of DocumentCollection and EdgeCollection
    // instances including system collections

method commitLocalServiceState

commitLocalServiceState: (replace?: boolean) => Promise<void>;
  • Writes all locally available services to the database and updates any service bundles missing in the database.

    Parameter replace

    If set to true, outdated services will also be committed. This can be used to solve some consistency problems when service bundles are missing in the database or were deleted manually.

    Example 1

    await db.commitLocalServiceState();
    // all services available on the coordinator have been written to the db

    Example 2

    await db.commitLocalServiceState(true);
    // all service conflicts have been resolved in favor of this coordinator

method computeClusterRebalance

computeClusterRebalance: (
opts: ClusterRebalanceOptions
) => Promise<ClusterRebalanceResult>;
  • Computes a set of move shard operations to rebalance the cluster.

    Example 1

    const db = new Database();
    const result = await db.computerClusterRebalance({
    moveLeaders: true,
    moveFollowers: true
    });
    if (result.moves.length) {
    await db.executeClusterRebalance(result.moves);
    }

method createAnalyzer

createAnalyzer: (
analyzerName: string,
options: CreateAnalyzerOptions
) => Promise<Analyzer>;
  • Creates a new Analyzer with the given analyzerName and options, then returns an analyzer.Analyzer instance for the new Analyzer.

    Parameter analyzerName

    Name of the Analyzer.

    Parameter options

    An object defining the properties of the Analyzer.

    Example 1

    const db = new Database();
    const analyzer = await db.createAnalyzer("potatoes", { type: "identity" });
    // the identity Analyzer "potatoes" now exists

method createCollection

createCollection: {
<T extends Record<string, any> = any>(
collectionName: string,
options?: CreateCollectionOptions & {
type?: CollectionType.DOCUMENT_COLLECTION;
}
): Promise<DocumentCollection<T>>;
<T extends Record<string, any> = any>(
collectionName: string,
options: CreateCollectionOptions & {
type: CollectionType.EDGE_COLLECTION;
}
): Promise<EdgeCollection<T>>;
};
  • Creates a new collection with the given collectionName and options, then returns a collection.DocumentCollection instance for the new collection.

    Parameter T

    Type to use for document data. Defaults to any.

    Parameter collectionName

    Name of the new collection.

    Parameter options

    Options for creating the collection.

    Example 1

    const db = new Database();
    const documents = db.createCollection("persons");

    Example 2

    interface Person {
    name: string;
    }
    const db = new Database();
    const documents = db.createCollection<Person>("persons");
  • Creates a new edge collection with the given collectionName and options, then returns an collection.EdgeCollection instance for the new edge collection.

    Parameter T

    Type to use for edge document data. Defaults to any.

    Parameter collectionName

    Name of the new collection.

    Parameter options

    Options for creating the collection.

    Example 1

    const db = new Database();
    const edges = db.createCollection("friends", {
    type: CollectionType.EDGE_COLLECTION
    });

    Example 2

    interface Friend {
    startDate: number;
    endDate?: number;
    }
    const db = new Database();
    const edges = db.createCollection<Friend>("friends", {
    type: CollectionType.EDGE_COLLECTION
    });

method createDatabase

createDatabase: {
(databaseName: string, options?: CreateDatabaseOptions): Promise<Database>;
(databaseName: string, users: CreateDatabaseUser[]): Promise<Database>;
};
  • Creates a new database with the given databaseName with the given options and returns a Database instance for that database.

    Parameter databaseName

    Name of the database to create.

    Parameter options

    Options for creating the database.

    Example 1

    const db = new Database();
    const info = await db.createDatabase("mydb", {
    users: [{ username: "root" }]
    });
    // the database has been created
  • Creates a new database with the given databaseName with the given users and returns a Database instance for that database.

    Parameter databaseName

    Name of the database to create.

    Parameter users

    Database users to create with the database.

    Example 1

    const db = new Database();
    const info = await db.createDatabase("mydb", [{ username: "root" }]);
    // the database has been created

method createEdgeCollection

createEdgeCollection: <T extends Record<string, any> = any>(
collectionName: string,
options?: CreateCollectionOptions
) => Promise<EdgeCollection<T>>;
  • Creates a new edge collection with the given collectionName and options, then returns an collection.EdgeCollection instance for the new edge collection.

    This is a convenience method for calling Database#createCollection with options.type set to EDGE_COLLECTION.

    Parameter T

    Type to use for edge document data. Defaults to any.

    Parameter collectionName

    Name of the new collection.

    Parameter options

    Options for creating the collection.

    Example 1

    const db = new Database();
    const edges = db.createEdgeCollection("friends");

    Example 2

    interface Friend {
    startDate: number;
    endDate?: number;
    }
    const db = new Database();
    const edges = db.createEdgeCollection<Friend>("friends");

method createFunction

createFunction: (
name: string,
code: string,
isDeterministic?: boolean
) => Promise<ArangoApiResponse<{ isNewlyCreated: boolean }>>;
  • Creates an AQL user function with the given _name_ and _code_ if it does not already exist or replaces it if a function with the same name already existed.

    Parameter name

    A valid AQL function name. The function name must consist of at least two alphanumeric identifiers separated with double colons.

    Parameter code

    A string evaluating to a JavaScript function (not a JavaScript function object).

    Parameter isDeterministic

    If set to true, the function is expected to always return the same result for equivalent inputs. This option currently has no effect but may allow for optimizations in the future.

    Example 1

    const db = new Database();
    await db.createFunction(
    "ACME::ACCOUNTING::CALCULATE_VAT",
    "(price) => price * 0.19"
    );
    // Use the new function in an AQL query with template handler:
    const cursor = await db.query(aql`
    FOR product IN products
    RETURN MERGE(
    { vat: ACME::ACCOUNTING::CALCULATE_VAT(product.price) },
    product
    )
    `);
    // cursor is a cursor for the query result

method createGraph

createGraph: (
graphName: string,
edgeDefinitions: EdgeDefinitionOptions[],
options?: CreateGraphOptions
) => Promise<Graph>;
  • Creates a graph with the given graphName and edgeDefinitions, then returns a graph.Graph instance for the new graph.

    Parameter graphName

    Name of the graph to be created.

    Parameter edgeDefinitions

    An array of edge definitions.

    Parameter options

    An object defining the properties of the graph.

method createHotBackup

createHotBackup: (options?: HotBackupOptions) => Promise<HotBackupResult>;
  • (Enterprise Edition only.) Creates a hot backup of the entire ArangoDB deployment including all databases, collections, etc.

    Returns an object describing the backup result.

    Parameter options

    Options for creating the backup.

    Example 1

    const info = await db.createHotBackup();
    // a hot backup has been created

method createJob

createJob: <T>(callback: () => Promise<T>) => Promise<Job<T>>;
  • Creates an async job by executing the given callback function. The first database request performed by the callback will be marked for asynchronous execution and its result will be made available as an async job.

    Returns a Job instance that can be used to retrieve the result of the callback function once the request has been executed.

    Parameter callback

    Callback function to execute as an async job.

    Example 1

    const db = new Database();
    const job = await db.createJob(() => db.collections());
    while (!job.isLoaded) {
    await timeout(1000);
    await job.load();
    }
    // job.result is a list of Collection instances

method createUser

createUser: {
(username: string, passwd: string): Promise<ArangoApiResponse<ArangoUser>>;
(username: string, options: UserOptions): Promise<
ArangoApiResponse<ArangoUser>
>;
};
  • Creates a new ArangoDB user with the given password.

    Parameter username

    Name of the ArangoDB user to create.

    Parameter passwd

    Password of the new ArangoDB user.

    Example 1

    const db = new Database();
    const user = await db.createUser("steve", "hunter2");
    // The user "steve" has been created
  • Creates a new ArangoDB user with the given options.

    Parameter username

    Name of the ArangoDB user to create.

    Parameter options

    Additional options for creating the ArangoDB user.

    Example 1

    const db = new Database();
    const user = await db.createUser("steve", { passwd: "hunter2" });
    // The user "steve" has been created

method createView

createView: (viewName: string, options: CreateViewOptions) => Promise<View>;
  • Creates a new View with the given viewName and options, then returns a view.View instance for the new View.

    Parameter viewName

    Name of the View.

    Parameter options

    An object defining the properties of the View.

    Example 1

    const db = new Database();
    const view = await db.createView("potatoes", { type: "arangosearch" });
    // the ArangoSearch View "potatoes" now exists

method database

database: (databaseName: string) => Database;
  • Creates a new Database instance for the given databaseName that shares this database's connection pool.

    See also .

    Parameter databaseName

    Name of the database.

    Example 1

    const systemDb = new Database();
    const myDb = system.database("my_database");

method databases

databases: () => Promise<Database[]>;
  • Fetches all databases from the server and returns an array of Database instances for those databases.

    See also Database#listDatabases and Database#userDatabases.

    Example 1

    const db = new Database();
    const names = await db.databases();
    // databases is an array of databases

method deleteAllJobResults

deleteAllJobResults: () => Promise<void>;
  • Deletes the results of all completed async jobs.

method deleteExpiredJobResults

deleteExpiredJobResults: (threshold: number) => Promise<void>;
  • Deletes the results of all completed async jobs created before the given threshold.

    Parameter threshold

    The expiration timestamp in milliseconds.

    Example 1

    const db = new Database();
    const ONE_WEEK = 7 * 24 * 60 * 60 * 1000;
    await db.deleteExpiredJobResults(Date.now() - ONE_WEEK);
    // all job results older than a week have been deleted

method deleteHotBackup

deleteHotBackup: (id: string) => Promise<void>;
  • (Enterprise Edition only.) Deletes a local hot backup.

    Parameter id

    The ID of the backup to delete.

    Example 1

    await db.deleteHotBackup("2023-09-19T15.38.21Z_example");
    // the backup has been deleted

method downloadService

downloadService: (mount: string) => Promise<Buffer | Blob>;
  • Retrieves a zip bundle containing the service files.

    Returns a Buffer in node.js or Blob in the browser.

    Parameter mount

    The service's mount point, relative to the database.

    Example 1

    const db = new Database();
    const serviceBundle = await db.downloadService("/my-foxx");

method dropDatabase

dropDatabase: (databaseName: string) => Promise<boolean>;
  • Deletes the database with the given databaseName from the server.

    Parameter databaseName

    Name of the database to delete.

    Example 1

    const db = new Database();
    await db.dropDatabase("mydb");
    // database "mydb" no longer exists

method dropFunction

dropFunction: (
name: string,
group?: boolean
) => Promise<ArangoApiResponse<{ deletedCount: number }>>;
  • Deletes the AQL user function with the given name from the database.

    Parameter name

    The name of the user function to drop.

    Parameter group

    If set to true, all functions with a name starting with name will be deleted, otherwise only the function with the exact name will be deleted.

    Example 1

    const db = new Database();
    await db.dropFunction("ACME::ACCOUNTING::CALCULATE_VAT");
    // the function no longer exists

method executeClusterRebalance

executeClusterRebalance: (moves: ClusterRebalanceMove[]) => Promise<unknown>;
  • Executes the given cluster move shard operations.

    Example 1

    const db = new Database();
    const result = await db.computerClusterRebalance({
    moveLeaders: true,
    moveFollowers: true
    });
    if (result.moves.length) {
    await db.executeClusterRebalance(result.moves);
    }

method executeTransaction

executeTransaction: {
(
collections: TransactionCollections & { allowImplicit?: boolean },
action: string,
options?: TransactionOptions & { params?: any }
): Promise<any>;
(
collections: (string | ArangoCollection)[],
action: string,
options?: TransactionOptions & { params?: any }
): Promise<any>;
(
collection: string | ArangoCollection,
action: string,
options?: TransactionOptions & { params?: any }
): Promise<any>;
};
  • Performs a server-side JavaScript transaction and returns its return value.

    Collections can be specified as collection names (strings) or objects implementing the collection.ArangoCollection interface: Collection, graph.GraphVertexCollection, graph.GraphEdgeCollection as well as (in TypeScript) collection.DocumentCollection and collection.EdgeCollection.

    **Note**: The action function will be evaluated and executed on the server inside ArangoDB's embedded JavaScript environment and can not access any values other than those passed via the params option.

    See the official ArangoDB documentation for [the JavaScript @arangodb module](https://www.arangodb.com/docs/stable/appendix-java-script-modules-arango-db.html) for information about accessing the database from within ArangoDB's server-side JavaScript environment.

    Parameter collections

    Collections involved in the transaction.

    Parameter action

    A string evaluating to a JavaScript function to be executed on the server.

    Parameter options

    Options for the transaction. If options.allowImplicit is specified, it will be used if collections.allowImplicit was not specified.

    Example 1

    const db = new Database();
    const action = `
    function(params) {
    // This code will be executed inside ArangoDB!
    const { query } = require("@arangodb");
    return query\`
    FOR user IN _users
    FILTER user.age > ${params.age}
    RETURN u.user
    \`.toArray();
    }
    `);
    const result = await db.executeTransaction({
    read: ["_users"]
    }, action, {
    params: { age: 12 }
    });
    // result contains the return value of the action
  • Performs a server-side transaction and returns its return value.

    Collections can be specified as collection names (strings) or objects implementing the collection.ArangoCollection interface: Collection, graph.GraphVertexCollection, graph.GraphEdgeCollection as well as (in TypeScript) collection.DocumentCollection and collection.EdgeCollection.

    **Note**: The action function will be evaluated and executed on the server inside ArangoDB's embedded JavaScript environment and can not access any values other than those passed via the params option. See the official ArangoDB documentation for [the JavaScript @arangodb module](https://www.arangodb.com/docs/stable/appendix-java-script-modules-arango-db.html) for information about accessing the database from within ArangoDB's server-side JavaScript environment.

    Parameter collections

    Collections that can be read from and written to during the transaction.

    Parameter action

    A string evaluating to a JavaScript function to be executed on the server.

    Parameter options

    Options for the transaction.

    Example 1

    const db = new Database();
    const action = `
    function(params) {
    // This code will be executed inside ArangoDB!
    const { query } = require("@arangodb");
    return query\`
    FOR user IN _users
    FILTER user.age > ${params.age}
    RETURN u.user
    \`.toArray();
    }
    `);
    const result = await db.executeTransaction(["_users"], action, {
    params: { age: 12 }
    });
    // result contains the return value of the action
  • Performs a server-side transaction and returns its return value.

    The Collection can be specified as a collection name (string) or an object implementing the collection.ArangoCollection interface: Collection, graph.GraphVertexCollection, graph.GraphEdgeCollection as well as (in TypeScript) collection.DocumentCollection and collection.EdgeCollection.

    **Note**: The action function will be evaluated and executed on the server inside ArangoDB's embedded JavaScript environment and can not access any values other than those passed via the params option. See the official ArangoDB documentation for [the JavaScript @arangodb module](https://www.arangodb.com/docs/stable/appendix-java-script-modules-arango-db.html) for information about accessing the database from within ArangoDB's server-side JavaScript environment.

    Parameter collection

    A collection that can be read from and written to during the transaction.

    Parameter action

    A string evaluating to a JavaScript function to be executed on the server.

    Parameter options

    Options for the transaction.

    Example 1

    const db = new Database();
    const action = `
    function(params) {
    // This code will be executed inside ArangoDB!
    const { query } = require("@arangodb");
    return query\`
    FOR user IN _users
    FILTER user.age > ${params.age}
    RETURN u.user
    \`.toArray();
    }
    `);
    const result = await db.executeTransaction("_users", action, {
    params: { age: 12 }
    });
    // result contains the return value of the action

method exists

exists: () => Promise<boolean>;
  • Checks whether the database exists.

    Example 1

    const db = new Database();
    const result = await db.exists();
    // result indicates whether the database exists

method explain

explain: {
(query: AqlQuery, options?: ExplainOptions & { allPlans?: false }): Promise<
ArangoApiResponse<SingleExplainResult>
>;
(
query: AqlQuery<any>,
options?: ExplainOptions & { allPlans: true }
): Promise<ArangoApiResponse<MultiExplainResult>>;
(
query: string | AqlLiteral,
bindVars?: Record<string, any>,
options?: ExplainOptions & { allPlans?: false }
): Promise<ArangoApiResponse<SingleExplainResult>>;
(
query: string | AqlLiteral,
bindVars?: Record<string, any>,
options?: ExplainOptions & { allPlans: true }
): Promise<ArangoApiResponse<MultiExplainResult>>;
};
  • Explains a database query using the given query.

    See the template string handler for information about how to create a query string without manually defining bind parameters nor having to worry about escaping variables.

    Parameter query

    An object containing an AQL query string and bind parameters, e.g. the object returned from an template string.

    Parameter options

    Options for explaining the query.

    Example 1

    const db = new Database();
    const collection = db.collection("some-collection");
    const explanation = await db.explain(aql`
    FOR doc IN ${collection}
    FILTER doc.flavor == "strawberry"
    RETURN doc._key
    `);
  • Explains a database query using the given query.

    See the template string handler for information about how to create a query string without manually defining bind parameters nor having to worry about escaping variables.

    Parameter query

    An object containing an AQL query string and bind parameters, e.g. the object returned from an template string.

    Parameter options

    Options for explaining the query.

    Example 1

    const db = new Database();
    const collection = db.collection("some-collection");
    const explanation = await db.explain(
    aql`
    FOR doc IN ${collection}
    FILTER doc.flavor == "strawberry"
    RETURN doc._key
    `,
    { allPlans: true }
    );
  • Explains a database query using the given query and bindVars.

    See the template string handler for a safer and easier alternative to passing strings directly.

    Parameter query

    An AQL query string.

    Parameter bindVars

    An object defining bind parameters for the query.

    Parameter options

    Options for explaining the query.

    Example 1

    const db = new Database();
    const collection = db.collection("some-collection");
    const explanation = await db.explain(
    `
    FOR doc IN @@collection
    FILTER doc.flavor == "strawberry"
    RETURN doc._key
    `,
    { "@collection": collection.name }
    );
  • Explains a database query using the given query and bindVars.

    See the template string handler for a safer and easier alternative to passing strings directly.

    Parameter query

    An AQL query string.

    Parameter bindVars

    An object defining bind parameters for the query.

    Parameter options

    Options for explaining the query.

    Example 1

    const db = new Database();
    const collection = db.collection("some-collection");
    const explanation = await db.explain(
    `
    FOR doc IN @@collection
    FILTER doc.flavor == "strawberry"
    RETURN doc._key
    `,
    { "@collection": collection.name },
    { allPlans: true }
    );

method get

get: () => Promise<DatabaseInfo>;
  • Fetches the database description for the active database from the server.

    Example 1

    const db = new Database();
    const info = await db.get();
    // the database exists

method getClusterImbalance

getClusterImbalance: () => Promise<ClusterRebalanceState>;
  • Computes the current cluster imbalance.

    Example 1

    const db = new Database();
    const imbalance = await db.getClusterImbalance();

method getLogEntries

getLogEntries: (options?: LogEntriesOptions) => Promise<LogEntries>;
  • Retrieves the log messages from the server's global log.

    Parameter options

    Options for retrieving the log entries.

    Example 1

    const log = await db.getLogEntries();
    for (let i = 0; i < log.totalAmount; i++) {
    console.log(`${
    new Date(log.timestamp[i] * 1000).toISOString()
    } - [${LogLevel[log.level[i]]}] ${log.text[i]} (#${log.lid[i]})`);
    }

method getLogLevel

getLogLevel: () => Promise<Record<string, LogLevelSetting>>;
  • Retrieves the server's current log level for each topic.

    Example 1

    const levels = await db.getLogLevel();
    console.log(levels.request); // log level for incoming requests

method getLogMessages

getLogMessages: (options?: LogEntriesOptions) => Promise<LogMessage[]>;
  • Retrieves the log messages from the server's global log.

    Parameter options

    Options for retrieving the log entries.

    Example 1

    const messages = await db.getLogMessages();
    for (const m of messages) {
    console.log(`${m.date} - [${m.level}] ${m.message} (#${m.id})`);
    }

    Deprecated

    This endpoint has been deprecated in ArangoDB 3.8. Use Database#getLogEntries instead.

method getService

getService: (mount: string) => Promise<ServiceInfo>;
  • Retrieves information about a mounted service.

    Parameter mount

    The service's mount point, relative to the database.

    Example 1

    const db = new Database();
    const info = await db.getService("/my-service");
    // info contains detailed information about the service

method getServiceConfiguration

getServiceConfiguration: {
(mount: string, minimal?: false): Promise<
Record<string, ServiceConfiguration>
>;
(mount: string, minimal: true): Promise<Record<string, any>>;
};
  • Retrieves information about the service's configuration options and their current values.

    See also Database#replaceServiceConfiguration and Database#updateServiceConfiguration.

    Parameter mount

    The service's mount point, relative to the database.

    Parameter minimal

    If set to true, the result will only include each configuration option's current value. Otherwise it will include the full definition for each option.

    Example 1

    const db = new Database();
    const config = await db.getServiceConfiguration("/my-service");
    for (const [key, option] of Object.entries(config)) {
    console.log(`${option.title} (${key}): ${option.current}`);
    }
  • Retrieves information about the service's configuration options and their current values.

    See also Database#replaceServiceConfiguration and Database#updateServiceConfiguration.

    Parameter mount

    The service's mount point, relative to the database.

    Parameter minimal

    If set to true, the result will only include each configuration option's current value. Otherwise it will include the full definition for each option.

    Example 1

    const db = new Database();
    const config = await db.getServiceConfiguration("/my-service", true);
    for (const [key, value] of Object.entries(config)) {
    console.log(`${key}: ${value}`);
    }

method getServiceDependencies

getServiceDependencies: {
(mount: string, minimal?: false): Promise<
Record<string, SingleServiceDependency | MultiServiceDependency>
>;
(mount: string, minimal: true): Promise<Record<string, string | string[]>>;
};
  • Retrieves information about the service's dependencies and their current mount points.

    See also Database#replaceServiceDependencies and Database#updateServiceDependencies.

    Parameter mount

    The service's mount point, relative to the database.

    Parameter minimal

    If set to true, the result will only include each dependency's current mount point. Otherwise it will include the full definition for each dependency.

    Example 1

    const db = new Database();
    const deps = await db.getServiceDependencies("/my-service");
    for (const [key, dep] of Object.entries(deps)) {
    console.log(`${dep.title} (${key}): ${dep.current}`);
    }
  • Retrieves information about the service's dependencies and their current mount points.

    See also Database#replaceServiceDependencies and Database#updateServiceDependencies.

    Parameter mount

    The service's mount point, relative to the database.

    Parameter minimal

    If set to true, the result will only include each dependency's current mount point. Otherwise it will include the full definition for each dependency.

    Example 1

    const db = new Database();
    const deps = await db.getServiceDependencies("/my-service", true);
    for (const [key, value] of Object.entries(deps)) {
    console.log(`${key}: ${value}`);
    }

method getServiceDocumentation

getServiceDocumentation: (mount: string) => Promise<SwaggerJson>;
  • Retrieves an Open API compatible Swagger API description object for the service installed at the given mount point.

    Parameter mount

    The service's mount point, relative to the database.

    Example 1

    const db = new Database();
    const spec = await db.getServiceDocumentation("/my-service");
    // spec is a Swagger API description of the service

method getServiceReadme

getServiceReadme: (mount: string) => Promise<string | undefined>;
  • Retrieves the text content of the service's README or README.md file.

    Returns undefined if no such file could be found.

    Parameter mount

    The service's mount point, relative to the database.

    Example 1

    const db = new Database();
    const readme = await db.getServiceReadme("/my-service");
    if (readme !== undefined) console.log(readme);
    else console.warn(`No README found.`)

method getUser

getUser: (username: string) => Promise<ArangoApiResponse<ArangoUser>>;
  • Fetches the user data of a single ArangoDB user.

    Parameter username

    Name of the ArangoDB user to fetch.

    Example 1

    const db = new Database();
    const user = await db.getUser("steve");
    // user is the user object for the user named "steve"

method getUserAccessLevel

getUserAccessLevel: (
username: string,
{ database, collection }: UserAccessLevelOptions
) => Promise<AccessLevel>;
  • Fetches the given ArangoDB user's access level for the database, or the given collection in the given database.

    Parameter username

    Name of the ArangoDB user to fetch the access level for.

    Parameter database

    Database to fetch the access level for.

    Parameter collection

    Collection to fetch the access level for.

    Example 1

    const db = new Database();
    const accessLevel = await db.getUserAccessLevel("steve");
    // The access level of the user "steve" has been fetched for the current
    // database.

    Example 2

    const db = new Database();
    const accessLevel = await db.getUserAccessLevel("steve", {
    database: "staging"
    });
    // The access level of the user "steve" has been fetched for the "staging"
    // database.

    Example 3

    const db = new Database();
    const accessLevel = await db.getUserAccessLevel("steve", {
    collection: "pokemons"
    });
    // The access level of the user "steve" has been fetched for the
    // "pokemons" collection in the current database.

    Example 4

    const db = new Database();
    const accessLevel = await db.getUserAccessLevel("steve", {
    database: "staging",
    collection: "pokemons"
    });
    // The access level of the user "steve" has been fetched for the
    // "pokemons" collection in the "staging" database.

    Example 5

    const db = new Database();
    const staging = db.database("staging");
    const accessLevel = await db.getUserAccessLevel("steve", {
    database: staging
    });
    // The access level of the user "steve" has been fetched for the "staging"
    // database.

    Example 6

    const db = new Database();
    const staging = db.database("staging");
    const accessLevel = await db.getUserAccessLevel("steve", {
    collection: staging.collection("pokemons")
    });
    // The access level of the user "steve" has been fetched for the
    // "pokemons" collection in database "staging".

method getUserDatabases

getUserDatabases: {
(username: string, full?: false): Promise<Record<string, AccessLevel>>;
(username: string, full: true): Promise<
Record<
string,
{
permission: AccessLevel;
collections: Record<string, 'undefined' | AccessLevel>;
}
>
>;
};
  • Fetches an object mapping names of databases to the access level of the given ArangoDB user for those databases.

    Parameter username

    Name of the ArangoDB user to fetch the access levels for.

    Parameter full

    Whether access levels for collections should be included.

    Example 1

    const db = new Database();
    const accessLevels = await db.getUserDatabases("steve");
    for (const [databaseName, accessLevel] of Object.entries(accessLevels)) {
    console.log(`${databaseName}: ${accessLevel}`);
    }
  • Fetches an object mapping names of databases to the access level of the given ArangoDB user for those databases and the collections within each database.

    Parameter username

    Name of the ArangoDB user to fetch the access levels for.

    Parameter full

    Whether access levels for collections should be included.

    Example 1

    const db = new Database();
    const accessLevels = await db.getUserDatabases("steve", true);
    for (const [databaseName, obj] of Object.entries(accessLevels)) {
    console.log(`${databaseName}: ${obj.permission}`);
    for (const [collectionName, accessLevel] of Object.entries(obj.collections)) {
    console.log(`${databaseName}/${collectionName}: ${accessLevel}`);
    }
    }

method graph

graph: (graphName: string) => Graph;
  • Returns a graph.Graph instance representing the graph with the given graphName.

    Parameter graphName

    Name of the graph.

    Example 1

    const db = new Database();
    const graph = db.graph("some-graph");

method graphs

graphs: () => Promise<Graph[]>;
  • Fetches all graphs from the database and returns an array of graph.Graph instances for those graphs.

    See also Database#listGraphs.

    Example 1

    const db = new Database();
    const graphs = await db.graphs();
    // graphs is an array of Graph instances

method installService

installService: (
mount: string,
source: Readable | Buffer | Blob | string,
options?: InstallServiceOptions
) => Promise<ServiceInfo>;
  • Installs a new service.

    Parameter mount

    The service's mount point, relative to the database.

    Parameter source

    The service bundle to install.

    Parameter options

    Options for installing the service.

    Example 1

    const db = new Database();
    // Using a node.js file stream as source
    const source = fs.createReadStream("./my-foxx-service.zip");
    const info = await db.installService("/hello", source);

    Example 2

    const db = new Database();
    // Using a node.js Buffer as source
    const source = fs.readFileSync("./my-foxx-service.zip");
    const info = await db.installService("/hello", source);

    Example 3

    const db = new Database();
    // Using a File (Blob) from a browser file input
    const element = document.getElementById("my-file-input");
    const source = element.files[0];
    const info = await db.installService("/hello", source);

method job

job: (jobId: string) => Job;
  • Returns a job.Job instance for the given jobId.

    Parameter jobId

    ID of the async job.

    Example 1

    const db = new Database();
    const job = db.job("12345");

method killQuery

killQuery: (queryId: string) => Promise<void>;
  • Kills a running query with the given queryId.

    See also Database#listRunningQueries.

    Parameter queryId

    The ID of a currently running query.

    Example 1

    const db = new Database();
    const queries = await db.listRunningQueries();
    await Promise.all(queries.map(
    async (query) => {
    if (query.state === "executing") {
    await db.killQuery(query.id);
    }
    }
    ));

method listAnalyzers

listAnalyzers: () => Promise<AnalyzerDescription[]>;
  • Fetches all Analyzers visible in the database and returns an array of Analyzer descriptions.

    See also Database#analyzers.

    Example 1

    const db = new Database();
    const analyzers = await db.listAnalyzers();
    // analyzers is an array of Analyzer descriptions

method listCollections

listCollections: (excludeSystem?: boolean) => Promise<CollectionMetadata[]>;
  • Fetches all collections from the database and returns an array of collection descriptions.

    See also Database#collections.

    Parameter excludeSystem

    Whether system collections should be excluded.

    Example 1

    const db = new Database();
    const collections = await db.listCollections();
    // collections is an array of collection descriptions
    // not including system collections

    Example 2

    const db = new Database();
    const collections = await db.listCollections(false);
    // collections is an array of collection descriptions
    // including system collections

method listCompletedJobs

listCompletedJobs: () => Promise<string[]>;
  • Returns a list of the IDs of all currently available completed async jobs.

    Example 1

    const db = new Database();
    const completedJobs = await db.listCompletedJobs();
    console.log(completedJobs); // e.g. ["12345", "67890"]

method listDatabases

listDatabases: () => Promise<string[]>;
  • Fetches all databases from the server and returns an array of their names.

    See also Database#databases and Database#listUserDatabases.

    Example 1

    const db = new Database();
    const names = await db.listDatabases();
    // databases is an array of database names

method listFunctions

listFunctions: () => Promise<AqlUserFunction[]>;
  • Fetches a list of all AQL user functions registered with the database.

    Example 1

    const db = new Database();
    const functions = await db.listFunctions();
    const names = functions.map(fn => fn.name);

method listGraphs

listGraphs: () => Promise<GraphInfo[]>;
  • Fetches all graphs from the database and returns an array of graph descriptions.

    See also Database#graphs.

    Example 1

    const db = new Database();
    const graphs = await db.listGraphs();
    // graphs is an array of graph descriptions

method listHotBackups

listHotBackups: (id?: string | string[]) => Promise<HotBackupList>;
  • (Enterprise Edition only.) Retrieves a list of all locally found hot backups.

    Parameter id

    If specified, only the backup with the given ID will be returned.

    Example 1

    const backups = await db.listHotBackups();
    for (const backup of backups) {
    console.log(backup.id);
    }

method listPendingJobs

listPendingJobs: () => Promise<string[]>;
  • Returns a list of the IDs of all currently pending async jobs.

    Example 1

    const db = new Database();
    const pendingJobs = await db.listPendingJobs();
    console.log(pendingJobs); // e.g. ["12345", "67890"]

method listRunningQueries

listRunningQueries: () => Promise<QueryInfo[]>;

method listServices

listServices: (excludeSystem?: boolean) => Promise<ServiceSummary[]>;
  • Fetches a list of all installed service.

    Parameter excludeSystem

    Whether system services should be excluded.

    Example 1

    const db = new Database();
    const services = await db.listServices();

    Example 2

    const db = new Database();
    const services = await db.listServices(false); // all services

method listServiceScripts

listServiceScripts: (mount: string) => Promise<Record<string, string>>;
  • Retrieves a list of scripts defined in the service manifest's "scripts" section mapped to their human readable representations.

    Parameter mount

    The service's mount point, relative to the database.

    Example 1

    const db = new Database();
    const scripts = await db.listServiceScripts("/my-service");
    for (const [name, title] of Object.entries(scripts)) {
    console.log(`${name}: ${title}`);
    }

method listSlowQueries

listSlowQueries: () => Promise<QueryInfo[]>;

method listTransactions

listTransactions: () => Promise<TransactionDetails[]>;
  • Fetches all active transactions from the database and returns an array of transaction descriptions.

    See also Database#transactions.

    Example 1

    const db = new Database();
    const transactions = await db.listTransactions();
    // transactions is an array of transaction descriptions

method listUserDatabases

listUserDatabases: () => Promise<string[]>;
  • Fetches all databases accessible to the active user from the server and returns an array of their names.

    See also Database#userDatabases and Database#listDatabases.

    Example 1

    const db = new Database();
    const names = await db.listUserDatabases();
    // databases is an array of database names

method listUsers

listUsers: () => Promise<ArangoUser[]>;
  • Fetches all ArangoDB users visible to the authenticated user and returns an array of user objects.

    Example 1

    const db = new Database();
    const users = await db.listUsers();
    // users is an array of user objects

method listViews

listViews: () => Promise<ViewDescription[]>;
  • Fetches all Views from the database and returns an array of View descriptions.

    See also Database#views.

    Example 1

    const db = new Database();
    const views = await db.listViews();
    // views is an array of View descriptions

method login

login: (username?: string, password?: string) => Promise<string>;
  • Validates the given database credentials and exchanges them for an authentication token, then uses the authentication token for future requests and returns it.

    Parameter username

    The username to authenticate with.

    Parameter password

    The password to authenticate with.

    Example 1

    const db = new Database();
    await db.login("admin", "hunter2");
    // with an authentication token for the "admin" user.

method parse

parse: (query: string | AqlQuery | AqlLiteral) => Promise<ParseResult>;
  • Parses the given query and returns the result.

    See the template string handler for information about how to create a query string without manually defining bind parameters nor having to worry about escaping variables.

    Parameter query

    An AQL query string or an object containing an AQL query string and bind parameters, e.g. the object returned from an template string.

    Example 1

    const db = new Database();
    const collection = db.collection("some-collection");
    const ast = await db.parse(aql`
    FOR doc IN ${collection}
    FILTER doc.flavor == "strawberry"
    RETURN doc._key
    `);

method query

query: {
<T = any>(query: AqlQuery<T>, options?: QueryOptions): Promise<
ArrayCursor<T>
>;
<T = any>(
query: string | AqlLiteral,
bindVars?: Record<string, any>,
options?: QueryOptions
): Promise<ArrayCursor<T>>;
};
  • Performs a database query using the given query, then returns a new cursor.ArrayCursor instance for the result set.

    See the template string handler for information about how to create a query string without manually defining bind parameters nor having to worry about escaping variables.

    **Note**: When executing a query in a streaming transaction using the step method, the resulting cursor will be bound to that transaction and you do not need to use the step method to consume it.

    Parameter query

    An object containing an AQL query string and bind parameters, e.g. the object returned from an template string.

    Parameter options

    Options for the query execution.

    Example 1

    const db = new Database();
    const active = true;
    const Users = db.collection("_users");
    // Using an aql template string:
    // Bind parameters are automatically extracted and arangojs collections
    // are automatically passed as collection bind parameters.
    const cursor = await db.query(aql`
    FOR u IN ${Users}
    FILTER u.authData.active == ${active}
    RETURN u.user
    `);
    // cursor is a cursor for the query result

    Example 2

    const db = new Database();
    const active = true;
    const Users = db.collection("_users");
    // Using an object with a regular multi-line string
    const cursor = await db.query({
    query: `
    FOR u IN @@users
    FILTER u.authData.active == @active
    RETURN u.user
    `,
    bindVars: { active: active, "@users": Users.name }
    });
  • Performs a database query using the given query and bindVars, then returns a new cursor.ArrayCursor instance for the result set.

    See the template string handler for a safer and easier alternative to passing strings directly.

    **Note**: When executing a query in a streaming transaction using the step method, the resulting cursor will be bound to that transaction and you do not need to use the step method to consume it.

    Parameter query

    An AQL query string.

    Parameter bindVars

    An object defining bind parameters for the query.

    Parameter options

    Options for the query execution.

    Example 1

    const db = new Database();
    const active = true;
    const Users = db.collection("_users");
    const cursor = await db.query(
    // A normal multi-line string
    `
    FOR u IN @@users
    FILTER u.authData.active == @active
    RETURN u.user
    `,
    { active: active, "@users": Users.name }
    );

    Example 2

    const db = new Database();
    const active = true;
    const Users = db.collection("_users");
    const cursor = await db.query(
    // An AQL literal created from a normal multi-line string
    aql.literal(`
    FOR u IN @@users
    FILTER u.authData.active == @active
    RETURN u.user
    `),
    { active: active, "@users": Users.name }
    );

method queryRules

queryRules: () => Promise<QueryOptimizerRule[]>;
  • Fetches the available optimizer rules.

    Example 1

    const db = new Database();
    const rules = await db.queryRules();
    for (const rule of rules) {
    console.log(rule.name);
    }

method queryTracking

queryTracking: {
(): Promise<QueryTracking>;
(options: QueryTrackingOptions): Promise<QueryTracking>;
};
  • Fetches the query tracking properties.

    Example 1

    const db = new Database();
    const tracking = await db.queryTracking();
    console.log(tracking.enabled);
  • Modifies the query tracking properties.

    Parameter options

    Options for query tracking.

    Example 1

    const db = new Database();
    // track up to 5 slow queries exceeding 5 seconds execution time
    await db.setQueryTracking({
    enabled: true,
    trackSlowQueries: true,
    maxSlowQueries: 5,
    slowQueryThreshold: 5
    });

method rebalanceCluster

rebalanceCluster: (
opts: ClusterRebalanceOptions
) => Promise<ClusterRebalanceResult>;
  • Computes a set of move shard operations to rebalance the cluster and executes them.

    Example 1

    const db = new Database();
    const result = await db.rebalanceCluster({
    moveLeaders: true,
    moveFollowers: true
    });
    // The cluster is now rebalanced.

method removeUser

removeUser: (
username: string
) => Promise<ArangoApiResponse<Record<string, never>>>;
  • Removes the ArangoDB user with the given username from the server.

    Parameter username

    Name of the ArangoDB user to remove.

    Example 1

    const db = new Database();
    await db.removeUser("steve");
    // The user "steve" has been removed

method renameCollection

renameCollection: (
collectionName: string,
newName: string
) => Promise<ArangoApiResponse<CollectionMetadata>>;
  • Renames the collection collectionName to newName.

    Additionally removes any stored Collection instance for collectionName from the Database instance's internal cache.

    **Note**: Renaming collections may not be supported when ArangoDB is running in a cluster configuration.

    Parameter collectionName

    Current name of the collection.

    Parameter newName

    The new name of the collection.

method renameView

renameView: (
viewName: string,
newName: string
) => Promise<ArangoApiResponse<ViewDescription>>;
  • Renames the view viewName to newName.

    Additionally removes any stored view.View instance for viewName from the Database instance's internal cache.

    **Note**: Renaming views may not be supported when ArangoDB is running in a cluster configuration.

    Parameter viewName

    Current name of the view.

    Parameter newName

    The new name of the view.

method renewAuthToken

renewAuthToken: () => Promise<string | null>;
  • Attempts to renew the authentication token passed to Database#useBearerAuth or returned and used by Database#login. If a new authentication token is issued, it will be used for future requests and returned.

    Example 1

    const db = new Database();
    await db.login("admin", "hunter2");
    // ... later ...
    const newToken = await db.renewAuthToken();
    if (!newToken) // no new token issued

method replaceService

replaceService: (
mount: string,
source: Readable | Buffer | Blob | string,
options?: ReplaceServiceOptions
) => Promise<ServiceInfo>;
  • Replaces an existing service with a new service by completely removing the old service and installing a new service at the same mount point.

    Parameter mount

    The service's mount point, relative to the database.

    Parameter source

    The service bundle to install.

    Parameter options

    Options for replacing the service.

    Example 1

    const db = new Database();
    // Using a node.js file stream as source
    const source = fs.createReadStream("./my-foxx-service.zip");
    const info = await db.replaceService("/hello", source);

    Example 2

    const db = new Database();
    // Using a node.js Buffer as source
    const source = fs.readFileSync("./my-foxx-service.zip");
    const info = await db.replaceService("/hello", source);

    Example 3

    const db = new Database();
    // Using a File (Blob) from a browser file input
    const element = document.getElementById("my-file-input");
    const source = element.files[0];
    const info = await db.replaceService("/hello", source);

method replaceServiceConfiguration

replaceServiceConfiguration: {
(mount: string, cfg: Record<string, any>, minimal?: false): Promise<
Record<string, ServiceConfiguration & { warning?: string }>
>;
(mount: string, cfg: Record<string, any>, minimal: true): Promise<{
values: Record<string, any>;
warnings: Record<string, string>;
}>;
};
  • Replaces the configuration of the given service, discarding any existing values for options not specified.

    See also Database#updateServiceConfiguration and Database#getServiceConfiguration.

    Parameter mount

    The service's mount point, relative to the database.

    Parameter cfg

    An object mapping configuration option names to values.

    Parameter minimal

    If set to true, the result will only include each configuration option's current value and warning (if any). Otherwise it will include the full definition for each option.

    Example 1

    const db = new Database();
    const config = { currency: "USD", locale: "en-US" };
    const info = await db.replaceServiceConfiguration("/my-service", config);
    for (const [key, option] of Object.entries(info)) {
    console.log(`${option.title} (${key}): ${option.value}`);
    if (option.warning) console.warn(`Warning: ${option.warning}`);
    }
  • Replaces the configuration of the given service, discarding any existing values for options not specified.

    See also Database#updateServiceConfiguration and Database#getServiceConfiguration.

    Parameter mount

    The service's mount point, relative to the database.

    Parameter cfg

    An object mapping configuration option names to values.

    Parameter minimal

    If set to true, the result will only include each configuration option's current value and warning (if any). Otherwise it will include the full definition for each option.

    Example 1

    const db = new Database();
    const config = { currency: "USD", locale: "en-US" };
    const info = await db.replaceServiceConfiguration("/my-service", config);
    for (const [key, value] of Object.entries(info.values)) {
    console.log(`${key}: ${value}`);
    if (info.warnings[key]) console.warn(`Warning: ${info.warnings[key]}`);
    }

method replaceServiceDependencies

replaceServiceDependencies: {
(mount: string, deps: Record<string, string>, minimal?: false): Promise<
Record<
string,
(SingleServiceDependency | MultiServiceDependency) & {
warning?: string;
}
>
>;
(mount: string, deps: Record<string, string>, minimal: true): Promise<{
values: Record<string, string>;
warnings: Record<string, string>;
}>;
};
  • Replaces the dependencies of the given service, discarding any existing mount points for dependencies not specified.

    See also Database#updateServiceDependencies and Database#getServiceDependencies.

    Parameter mount

    The service's mount point, relative to the database.

    Parameter cfg

    An object mapping dependency aliases to mount points.

    Parameter minimal

    If set to true, the result will only include each dependency's current mount point. Otherwise it will include the full definition for each dependency.

    Example 1

    const db = new Database();
    const deps = { mailer: "/mailer-api", auth: "/remote-auth" };
    const info = await db.replaceServiceDependencies("/my-service", deps);
    for (const [key, dep] of Object.entries(info)) {
    console.log(`${dep.title} (${key}): ${dep.current}`);
    if (dep.warning) console.warn(`Warning: ${dep.warning}`);
    }
  • Replaces the dependencies of the given service, discarding any existing mount points for dependencies not specified.

    See also Database#updateServiceDependencies and Database#getServiceDependencies.

    Parameter mount

    The service's mount point, relative to the database.

    Parameter cfg

    An object mapping dependency aliases to mount points.

    Parameter minimal

    If set to true, the result will only include each dependency's current mount point. Otherwise it will include the full definition for each dependency.

    Example 1

    const db = new Database();
    const deps = { mailer: "/mailer-api", auth: "/remote-auth" };
    const info = await db.replaceServiceDependencies(
    "/my-service",
    deps,
    true
    );
    for (const [key, value] of Object.entries(info)) {
    console.log(`${key}: ${value}`);
    if (info.warnings[key]) console.warn(`Warning: ${info.warnings[key]}`);
    }

method replaceUser

replaceUser: (
username: string,
options: UserOptions
) => Promise<ArangoApiResponse<ArangoUser>>;
  • Replaces the ArangoDB user's option with the new options.

    Parameter username

    Name of the ArangoDB user to modify.

    Parameter options

    New options to replace the user's existing options.

    Example 1

    const db = new Database();
    const user = await db.replaceUser("steve", { passwd: "", active: false });
    // The user "steve" has been set to inactive with an empty password

method restoreHotBackup

restoreHotBackup: (id: string) => Promise<string>;
  • (Enteprise Edition only.) Restores a consistent local hot backup.

    Returns the directory path of the restored backup.

    Parameter id

    The ID of the backup to restore.

    Example 1

    await db.restoreHotBackup("2023-09-19T15.38.21Z_example");
    // the backup has been restored

method route

route: (path?: string, headers?: Headers) => Route;
  • Returns a new route.Route instance for the given path (relative to the database) that can be used to perform arbitrary HTTP requests.

    Parameter path

    The database-relative URL of the route. Defaults to the database API root.

    Parameter headers

    Default headers that should be sent with each request to the route.

    Example 1

    const db = new Database();
    const myFoxxService = db.route("my-foxx-service");
    const response = await myFoxxService.post("users", {
    username: "admin",
    password: "hunter2"
    });
    // response.body is the result of
    // POST /_db/_system/my-foxx-service/users
    // with JSON request body '{"username": "admin", "password": "hunter2"}'

method runServiceScript

runServiceScript: (mount: string, name: string, params?: any) => Promise<any>;
  • Executes a service script and retrieves its result exposed as module.exports (if any).

    Parameter mount

    The service's mount point, relative to the database.

    Parameter name

    Name of the service script to execute as defined in the service manifest.

    Parameter params

    Arbitrary value that will be exposed to the script as argv[0] in the service context (e.g. module.context.argv[0]). Must be serializable to JSON.

    Example 1

    const db = new Database();
    const result = await db.runServiceScript(
    "/my-service",
    "create-user",
    {
    username: "service_admin",
    password: "hunter2"
    }
    );

method runServiceTests

runServiceTests: {
(
mount: string,
options?: { reporter?: 'default'; idiomatic?: false; filter?: string }
): Promise<ServiceTestDefaultReport>;
(
mount: string,
options: { reporter: 'suite'; idiomatic?: false; filter?: string }
): Promise<ServiceTestSuiteReport>;
(
mount: string,
options: { reporter: 'stream'; idiomatic?: false; filter?: string }
): Promise<ServiceTestStreamReport>;
(
mount: string,
options: { reporter: 'tap'; idiomatic?: false; filter?: string }
): Promise<ServiceTestTapReport>;
(
mount: string,
options: { reporter: 'xunit'; idiomatic?: false; filter?: string }
): Promise<ServiceTestXunitReport>;
(
mount: string,
options: { reporter: 'stream'; idiomatic: true; filter?: string }
): Promise<string>;
(
mount: string,
options: { reporter: 'tap'; idiomatic: true; filter?: string }
): Promise<string>;
(
mount: string,
options: { reporter: 'xunit'; idiomatic: true; filter?: string }
): Promise<string>;
};
  • Runs the tests of a given service and returns the results using the "default" reporter.

    Parameter mount

    The service's mount point, relative to the database.

    Parameter options

    Options for running the tests.

    Example 1

    const db = new Database();
    const testReport = await db.runServiceTests("/my-foxx");
  • Runs the tests of a given service and returns the results using the "suite" reporter, which groups the test result by test suite.

    Parameter mount

    The service's mount point, relative to the database.

    Parameter options

    Options for running the tests.

    Example 1

    const db = new Database();
    const suiteReport = await db.runServiceTests(
    "/my-foxx",
    { reporter: "suite" }
    );
  • Runs the tests of a given service and returns the results using the "stream" reporter, which represents the results as a sequence of tuples representing events.

    Parameter mount

    The service's mount point, relative to the database.

    Parameter options

    Options for running the tests.

    Example 1

    const db = new Database();
    const streamEvents = await db.runServiceTests(
    "/my-foxx",
    { reporter: "stream" }
    );
  • Runs the tests of a given service and returns the results using the "tap" reporter, which represents the results as an array of strings using the "tap" format.

    Parameter mount

    The service's mount point, relative to the database.

    Parameter options

    Options for running the tests.

    Example 1

    const db = new Database();
    const tapLines = await db.runServiceTests(
    "/my-foxx",
    { reporter: "tap" }
    );
  • Runs the tests of a given service and returns the results using the "xunit" reporter, which represents the results as an XML document using the JSONML exchange format.

    Parameter mount

    The service's mount point, relative to the database.

    Parameter options

    Options for running the tests.

    Example 1

    const db = new Database();
    const jsonML = await db.runServiceTests(
    "/my-foxx",
    { reporter: "xunit" }
    );
  • Runs the tests of a given service and returns the results as a string using the "stream" reporter in "idiomatic" mode, which represents the results as a line-delimited JSON stream of tuples representing events.

    Parameter mount

    The service's mount point, relative to the database.

    Parameter options

    Options for running the tests.

    Example 1

    const db = new Database();
    const streamReport = await db.runServiceTests(
    "/my-foxx",
    { reporter: "stream", idiomatic: true }
    );
  • Runs the tests of a given service and returns the results as a string using the "tap" reporter in "idiomatic" mode, which represents the results using the "tap" format.

    Parameter mount

    The service's mount point, relative to the database.

    Parameter options

    Options for running the tests.

    Example 1

    const db = new Database();
    const tapReport = await db.runServiceTests(
    "/my-foxx",
    { reporter: "tap", idiomatic: true }
    );
  • Runs the tests of a given service and returns the results as a string using the "xunit" reporter in "idiomatic" mode, which represents the results as an XML document.

    Parameter mount

    The service's mount point, relative to the database.

    Parameter options

    Options for running the tests.

    Example 1

    const db = new Database();
    const xml = await db.runServiceTests(
    "/my-foxx",
    { reporter: "xunit", idiomatic: true }
    );

method setLogLevel

setLogLevel: (
levels: Record<string, LogLevelSetting>
) => Promise<Record<string, LogLevelSetting>>;
  • Sets the server's log level for each of the given topics to the given level.

    Any omitted topics will be left unchanged.

    Parameter levels

    An object mapping topic names to log levels.

    Example 1

    await db.setLogLevel({ request: "debug" });
    // Debug information will now be logged for each request

method setResponseQueueTimeSamples

setResponseQueueTimeSamples: (responseQueueTimeSamples: number) => void;
  • Sets the limit for the number of values of the most recently received server-reported queue times that can be accessed using Database#queueTime.

    Parameter responseQueueTimeSamples

    Number of values to maintain.

method setServiceDevelopmentMode

setServiceDevelopmentMode: (
mount: string,
enabled?: boolean
) => Promise<ServiceInfo>;
  • Enables or disables development mode for the given service.

    Parameter mount

    The service's mount point, relative to the database.

    Parameter enabled

    Whether development mode should be enabled or disabled.

    Example 1

    const db = new Database();
    await db.setServiceDevelopmentMode("/my-service", true);
    // the service is now in development mode
    await db.setServiceDevelopmentMode("/my-service", false);
    // the service is now in production mode

method setUserAccessLevel

setUserAccessLevel: (
username: string,
{
database,
collection,
grant,
}: UserAccessLevelOptions & { grant: AccessLevel }
) => Promise<ArangoApiResponse<Record<string, AccessLevel>>>;
  • Sets the given ArangoDB user's access level for the database, or the given collection in the given database.

    Parameter username

    Name of the ArangoDB user to set the access level for.

    Parameter database

    Database to set the access level for.

    Parameter collection

    Collection to set the access level for.

    Parameter grant

    Access level to set for the given user.

    Example 1

    const db = new Database();
    await db.setUserAccessLevel("steve", { grant: "rw" });
    // The user "steve" now has read-write access to the current database.

    Example 2

    const db = new Database();
    await db.setUserAccessLevel("steve", {
    database: "staging",
    grant: "rw"
    });
    // The user "steve" now has read-write access to the "staging" database.

    Example 3

    const db = new Database();
    await db.setUserAccessLevel("steve", {
    collection: "pokemons",
    grant: "rw"
    });
    // The user "steve" now has read-write access to the "pokemons" collection
    // in the current database.

    Example 4

    const db = new Database();
    await db.setUserAccessLevel("steve", {
    database: "staging",
    collection: "pokemons",
    grant: "rw"
    });
    // The user "steve" now has read-write access to the "pokemons" collection
    // in the "staging" database.

    Example 5

    const db = new Database();
    const staging = db.database("staging");
    await db.setUserAccessLevel("steve", {
    database: staging,
    grant: "rw"
    });
    // The user "steve" now has read-write access to the "staging" database.

    Example 6

    const db = new Database();
    const staging = db.database("staging");
    await db.setUserAccessLevel("steve", {
    collection: staging.collection("pokemons"),
    grant: "rw"
    });
    // The user "steve" now has read-write access to the "pokemons" collection
    // in database "staging".

method shutdown

shutdown: () => Promise<void>;
  • Attempts to initiate a clean shutdown of the server.

method time

time: () => Promise<number>;
  • Retrives the server's current system time in milliseconds with microsecond precision.

method transaction

transaction: (transactionId: string) => Transaction;
  • Returns a transaction.Transaction instance for an existing streaming transaction with the given id.

    See also Database#beginTransaction.

    Parameter id

    The id of an existing stream transaction.

    Example 1

    const trx1 = await db.beginTransaction(collections);
    const id = trx1.id;
    // later
    const trx2 = db.transaction(id);
    await trx2.commit();

method transactions

transactions: () => Promise<Transaction[]>;
  • Fetches all active transactions from the database and returns an array of transaction.Transaction instances for those transactions.

    See also Database#listTransactions.

    Example 1

    const db = new Database();
    const transactions = await db.transactions();
    // transactions is an array of transactions

method uninstallService

uninstallService: (
mount: string,
options?: UninstallServiceOptions
) => Promise<void>;
  • Completely removes a service from the database.

    Parameter mount

    The service's mount point, relative to the database.

    Parameter options

    Options for uninstalling the service.

    Example 1

    const db = new Database();
    await db.uninstallService("/my-foxx");

method updateServiceConfiguration

updateServiceConfiguration: {
(mount: string, cfg: Record<string, any>, minimal?: false): Promise<
Record<string, ServiceConfiguration & { warning?: string }>
>;
(mount: string, cfg: Record<string, any>, minimal: true): Promise<{
values: Record<string, any>;
warnings: Record<string, string>;
}>;
};
  • Updates the configuration of the given service while maintaining any existing values for options not specified.

    See also Database#replaceServiceConfiguration and Database#getServiceConfiguration.

    Parameter mount

    The service's mount point, relative to the database.

    Parameter cfg

    An object mapping configuration option names to values.

    Parameter minimal

    If set to true, the result will only include each configuration option's current value and warning (if any). Otherwise it will include the full definition for each option.

    Example 1

    const db = new Database();
    const config = { currency: "USD", locale: "en-US" };
    const info = await db.updateServiceConfiguration("/my-service", config);
    for (const [key, option] of Object.entries(info)) {
    console.log(`${option.title} (${key}): ${option.value}`);
    if (option.warning) console.warn(`Warning: ${option.warning}`);
    }
  • Updates the configuration of the given service while maintaining any existing values for options not specified.

    See also Database#replaceServiceConfiguration and Database#getServiceConfiguration.

    Parameter mount

    The service's mount point, relative to the database.

    Parameter cfg

    An object mapping configuration option names to values.

    Parameter minimal

    If set to true, the result will only include each configuration option's current value and warning (if any). Otherwise it will include the full definition for each option.

    Example 1

    const db = new Database();
    const config = { currency: "USD", locale: "en-US" };
    const info = await db.updateServiceConfiguration("/my-service", config);
    for (const [key, value] of Object.entries(info.values)) {
    console.log(`${key}: ${value}`);
    if (info.warnings[key]) console.warn(`Warning: ${info.warnings[key]}`);
    }

method updateServiceDependencies

updateServiceDependencies: {
(mount: string, deps: Record<string, string>, minimal?: false): Promise<
Record<
string,
(SingleServiceDependency | MultiServiceDependency) & {
warning?: string;
}
>
>;
(mount: string, deps: Record<string, string>, minimal: true): Promise<{
values: Record<string, string>;
warnings: Record<string, string>;
}>;
};
  • Updates the dependencies of the given service while maintaining any existing mount points for dependencies not specified.

    See also Database#replaceServiceDependencies and Database#getServiceDependencies.

    Parameter mount

    The service's mount point, relative to the database.

    Parameter cfg

    An object mapping dependency aliases to mount points.

    Parameter minimal

    If set to true, the result will only include each dependency's current mount point. Otherwise it will include the full definition for each dependency.

    Example 1

    const db = new Database();
    const deps = { mailer: "/mailer-api", auth: "/remote-auth" };
    const info = await db.updateServiceDependencies("/my-service", deps);
    for (const [key, dep] of Object.entries(info)) {
    console.log(`${dep.title} (${key}): ${dep.current}`);
    if (dep.warning) console.warn(`Warning: ${dep.warning}`);
    }
  • Updates the dependencies of the given service while maintaining any existing mount points for dependencies not specified.

    See also Database#replaceServiceDependencies and Database#getServiceDependencies.

    Parameter mount

    The service's mount point, relative to the database.

    Parameter cfg

    An object mapping dependency aliases to mount points.

    Parameter minimal

    If set to true, the result will only include each dependency's current mount point. Otherwise it will include the full definition for each dependency.

    Example 1

    const db = new Database();
    const deps = { mailer: "/mailer-api", auth: "/remote-auth" };
    const info = await db.updateServiceDependencies(
    "/my-service",
    deps,
    true
    );
    for (const [key, value] of Object.entries(info)) {
    console.log(`${key}: ${value}`);
    if (info.warnings[key]) console.warn(`Warning: ${info.warnings[key]}`);
    }

method updateUser

updateUser: {
(username: string, passwd: string): Promise<ArangoApiResponse<ArangoUser>>;
(username: string, options: Partial<UserOptions>): Promise<
ArangoApiResponse<ArangoUser>
>;
};
  • Sets the password of a given ArangoDB user to the new value.

    Parameter username

    Name of the ArangoDB user to change the password for.

    Parameter passwd

    New password for the ArangoDB user.

    Example 1

    const db = new Database();
    const user = await db.updateUser("steve", "hunter2");
    // The user "steve" has received a new password
  • Updates the ArangoDB user with the new options.

    Parameter username

    Name of the ArangoDB user to modify.

    Parameter options

    Options of the ArangoDB user to modify.

    Example 1

    const db = new Database();
    const user = await db.updateUser("steve", { active: false });
    // The user "steve" has been set to inactive

method upgradeService

upgradeService: (
mount: string,
source: Readable | Buffer | Blob | string,
options?: UpgradeServiceOptions
) => Promise<ServiceInfo>;
  • Replaces an existing service with a new service while retaining the old service's configuration and dependencies.

    Parameter mount

    The service's mount point, relative to the database.

    Parameter source

    The service bundle to install.

    Parameter options

    Options for upgrading the service.

    Example 1

    const db = new Database();
    // Using a node.js file stream as source
    const source = fs.createReadStream("./my-foxx-service.zip");
    const info = await db.upgradeService("/hello", source);

    Example 2

    const db = new Database();
    // Using a node.js Buffer as source
    const source = fs.readFileSync("./my-foxx-service.zip");
    const info = await db.upgradeService("/hello", source);

    Example 3

    const db = new Database();
    // Using a File (Blob) from a browser file input
    const element = document.getElementById("my-file-input");
    const source = element.files[0];
    const info = await db.upgradeService("/hello", source);

method useBasicAuth

useBasicAuth: (username?: string, password?: string) => this;
  • Updates the underlying connection's authorization header to use Basic authentication with the given username and password, then returns itself.

    Parameter username

    The username to authenticate with.

    Parameter password

    The password to authenticate with.

    Example 1

    const db = new Database();
    db.useBasicAuth("admin", "hunter2");
    // with the username "admin" and password "hunter2".

method useBearerAuth

useBearerAuth: (token: string) => this;
  • Updates the underlying connection's authorization header to use Bearer authentication with the given authentication token, then returns itself.

    Parameter token

    The token to authenticate with.

    Example 1

    const db = new Database();
    db.useBearerAuth("keyboardcat");
    // The database instance now uses Bearer authentication.

method userDatabases

userDatabases: () => Promise<Database[]>;
  • Fetches all databases accessible to the active user from the server and returns an array of Database instances for those databases.

    See also Database#listUserDatabases and Database#databases.

    Example 1

    const db = new Database();
    const names = await db.userDatabases();
    // databases is an array of databases

method version

version: (details?: boolean) => Promise<VersionInfo>;
  • Fetches version information from the ArangoDB server.

    Parameter details

    If set to true, additional information about the ArangoDB server will be available as the details property.

    Example 1

    const db = new Database();
    const version = await db.version();
    // the version object contains the ArangoDB version information.
    // license: "community" or "enterprise"
    // version: ArangoDB version number
    // server: description of the server

method view

view: (viewName: string) => View;
  • Returns a view.View instance for the given viewName.

    Parameter viewName

    Name of the ArangoSearch or SearchAlias View.

    Example 1

    const db = new Database();
    const view = db.view("potatoes");

method views

views: () => Promise<View[]>;
  • Fetches all Views from the database and returns an array of view.View instances for the Views.

    See also Database#listViews.

    Example 1

    const db = new Database();
    const views = await db.views();
    // views is an array of ArangoSearch View instances

method waitForPropagation

waitForPropagation: (request: RequestOptions, timeout?: number) => Promise<void>;
  • Performs a request against every known coordinator and returns when the request has succeeded against every coordinator or the timeout is reached.

    **Note**: This method is primarily intended to make database setup easier in cluster scenarios and requires all coordinators to be known to arangojs before the method is invoked. The method is not useful in single-server or leader-follower replication scenarios.

    Parameter request

    Request to perform against each known coordinator.

    Parameter timeout

    Maximum number of milliseconds to wait for propagation.

    Example 1

    const db = new Database({ loadBalancingStrategy: "ROUND_ROBIN" });
    await system.acquireHostList();
    const analyzer = db.analyzer("my-analyzer");
    await analyzer.create();
    await db.waitForPropagation(
    { path: `/_api/analyzer/${encodeURIComponent(analyzer.name)}` },
    30000
    );
    // Analyzer has been propagated to all coordinators and can safely be used

method withTransaction

withTransaction: {
<T>(
collections: TransactionCollections,
callback: (step: Transaction['step']) => Promise<T>,
options?: TransactionOptions
): Promise<T>;
<T>(
collections: (string | ArangoCollection)[],
callback: (
step: <T>(callback: () => Promise<T>) => Promise<T>
) => Promise<T>,
options?: TransactionOptions
): Promise<T>;
<T>(
collection: string | ArangoCollection,
callback: (
step: <T>(callback: () => Promise<T>) => Promise<T>
) => Promise<T>,
options?: TransactionOptions
): Promise<T>;
};
  • Begins and commits a transaction using the given callback. Individual requests that are part of the transaction need to be wrapped in the step function passed into the callback. If the promise returned by the callback is rejected, the transaction will be aborted.

    Collections can be specified as collection names (strings) or objects implementing the collection.ArangoCollection interface: Collection, graph.GraphVertexCollection, graph.GraphEdgeCollection as well as (in TypeScript) collection.DocumentCollection and collection.EdgeCollection.

    Parameter collections

    Collections involved in the transaction.

    Parameter callback

    Callback function executing the transaction steps.

    Parameter options

    Options for the transaction.

    Example 1

    const vertices = db.collection("vertices");
    const edges = db.collection("edges");
    await db.withTransaction(
    {
    read: ["vertices"],
    write: [edges] // collection instances can be passed directly
    },
    async (step) => {
    const start = await step(() => vertices.document("a"));
    const end = await step(() => vertices.document("b"));
    await step(() => edges.save({ _from: start._id, _to: end._id }));
    }
    );
  • Begins and commits a transaction using the given callback. Individual requests that are part of the transaction need to be wrapped in the step function passed into the callback. If the promise returned by the callback is rejected, the transaction will be aborted.

    Collections can be specified as collection names (strings) or objects implementing the collection.ArangoCollection interface: Collection, graph.GraphVertexCollection, graph.GraphEdgeCollection as well as (in TypeScript) collection.DocumentCollection and collection.EdgeCollection.

    Parameter collections

    Collections that can be read from and written to during the transaction.

    Parameter callback

    Callback function executing the transaction steps.

    Parameter options

    Options for the transaction.

    Example 1

    const vertices = db.collection("vertices");
    const edges = db.collection("edges");
    await db.withTransaction(
    [
    "vertices",
    edges, // collection instances can be passed directly
    ],
    async (step) => {
    const start = await step(() => vertices.document("a"));
    const end = await step(() => vertices.document("b"));
    await step(() => edges.save({ _from: start._id, _to: end._id }));
    }
    );
  • Begins and commits a transaction using the given callback. Individual requests that are part of the transaction need to be wrapped in the step function passed into the callback. If the promise returned by the callback is rejected, the transaction will be aborted.

    The Collection can be specified as a collection name (string) or an object implementing the collection.ArangoCollection interface: Collection, graph.GraphVertexCollection, graph.GraphEdgeCollection as well as (in TypeScript) collection.DocumentCollection and collection.EdgeCollection.

    Parameter collection

    A collection that can be read from and written to during the transaction.

    Parameter callback

    Callback function executing the transaction steps.

    Parameter options

    Options for the transaction.

    Example 1

    const vertices = db.collection("vertices");
    const start = vertices.document("a");
    const end = vertices.document("b");
    const edges = db.collection("edges");
    await db.withTransaction(
    edges, // collection instances can be passed directly
    async (step) => {
    await step(() => edges.save({ _from: start._id, _to: end._id }));
    }
    );

Package Files (3)

Dependencies (5)

Dev Dependencies (0)

No dev dependencies.

Peer Dependencies (0)

No peer dependencies.

Badge

To add a badge like this onejsDocs.io badgeto your package's README, use the codes available below.

You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/arangojs.

  • Markdown
    [![jsDocs.io](https://img.shields.io/badge/jsDocs.io-reference-blue)](https://www.jsdocs.io/package/arangojs)
  • HTML
    <a href="https://www.jsdocs.io/package/arangojs"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>