---
title: "Typescript, Javascript"
description: "Typescript, Javascript, Agnesoft Graph Database"
---

import { Callout, Steps } from "nextra/components";

# Typescript / Javascript

The typescript agdb API client is based on [openapi-client-axios](https://www.npmjs.com/package/openapi-client-axios). The following is the quickstart guide for the agdb client in Javascript/Typescript (connecting to the server). It assumes an `agdb_server` is running locally. Please refer to the [server guide](/docs/guides/how-to-run-server) to learn how to run the server.

Looking for... [how to run a server?](/docs/guides/how-to-run-server) | [another language?](/api-docs/openapi) | [embedded db guide?](/docs/guides/quickstart)

## Usage

The following is the from-scratch guide to use `agdb-api` typescript/javascript package.

<Steps>

### Install NodeJS

https://nodejs.org/en

### Create your project

Let's create a directory (e.g. `my_agdb`) and nitialize the package:

```bash
mkdir my_agdb
cd my_agdb
npm init # follow the steps & prompts
```

### Add `typescript`

```bash
npm install typescript --save-dev
```

and create its configuration file `tsconfig.json`:

```json
{
    "compilerOptions": {
        "module": "ESNext",
        "sourceMap": true,
        "lib": ["ES2015", "DOM"],
        "moduleResolution": "node",
        "allowJs": true,
        "esModuleInterop": true
    }
}
```

<Callout>
    Consider using other dev packages such as `prettier` and `eslint` (and
    `@typescript-eslint/parser`)
</Callout>

### Add `@agnesoft/agdb_api` as a dependency.

```bash
npm install @agnesoft/agdb_api
```

### Create a client

In your main script (`indes.ts` or `main.ts` depending on your `package.json`'s `"main"` field) create a client connecting to the server:

```ts
import { QueryBuilder, Comparison, AgdbApi } from "@agnesfot/agdb_api";

async function main() {
    // Creates a client connecting to the remote server.
    let client = await AgdbApi.client("http://localhost:3000");
}
```

### Create a databasse user

To create a database user we use the default admin user:

```ts
await client.login("admin", "admin");
await client.admin_user_add("user1", { password: "password123" });
await client.login("user1", "password123");
```

### Create a database

```ts
await client.db_add({
    owner: "user1",
    db: "db1",
    db_type: "mapped", //memory mapped type, other options are "memory" and "file"
});
```

### Execute queries

To execute queries against the database we call `db_exec` with the user and their database.

<Callout type="info">
    Notice we are feeding results of the previous query to the next one with
    special alias `":0"` and `":1"` referencing first and second result
    respectively.
</Callout>

```ts
// Prepare the queries to be executed on the remote database.
let queries = [
    // :0: Inserts a root node aliased "users"
    QueryBuilder.insert().nodes().aliases(["users"]).query(),

    // :1: Inserts more nodes with some data
    QueryBuilder.insert()
        .nodes()
        .values([
            [
                ["username", "user1"],
                ["password", "password123"],
            ],
            [
                ["username", "user1"],
                ["password", "password456"],
            ],
        ])
        .query(),

    // :2: Connect the root to the inserted nodes with edges referencing both from previous queries
    QueryBuilder.insert().edges().from(":0").to(":1").query(),

    // :3: Find a node starting at the "users" node (could also be ":0" in this instance) with specific username
    QueryBuilder.select()
        .search()
        .from("users")
        .where()
        .key("username")
        .value(Comparison.Equal("user1"))
        .query(),
];

// Execute queries.
let results = (await client.db_exec({ owner: "user1", db: "db1" }, queries))
    .data;
```

### Print the the result of the final query to the console:

```ts
console.log(`User (id: ${results[3].elements[0].id})`);
for (let { key, value } of results[3].elements[0].values) {
    console.log(`${key["String"]}: ${value["String"]}`);
}
```

### Run the program

<Callout type="warning">
    Make sure the agdb_server is running at `localhost:3000`.
</Callout>

<Callout>
    If you are running this from the examples you may need to call `npm install`
    first.
</Callout>

```
npm run
```

### Full program

https://github.com/agnesoft/agdb/tree/main/examples/server_client_typescript

</Steps>
