> ## Documentation Index
> Fetch the complete documentation index at: https://docs.peaka.com/llms.txt
> Use this file to discover all available pages before exploring further.

# NodeJS Driver

> Discover the [Peaka](https://peaka.com/) NodeJS driver

## Requirements

* Node 12 or newer.

## Install

`npm install @peaka/client`
or
`yarn add @peaka/client`

## Usage

### Create a Peaka connection

```typescript theme={null}
import { Peaka, connectToPeaka } from "@peaka/client";

const connection: Peaka = connectToPeaka("<YOUR_API_KEY>")
```

### Submit a query

```typescript theme={null}
import type { QueryResult } from "@peaka/client";

try{
  const iter: Iterator<QueryResult> = await connection.query(
    'select * from <CATALOG_NAME>.<SCHEMA_NAME>.<TABLE_NAME> limit 100'
  );
}catch(err){
  console.error(err.response.data);
})
```

### Iterate through the query results

```typescript theme={null}
for await (const queryResult of iter) {
  console.log(queryResult.data);
}
```

### Alternative: map and aggregate the data

```typescript theme={null}
import type { QueryData } from "@peaka/client";

const data: QueryData[] = await iter
  .map(r => r.data ?? [])
  .fold<QueryData[]>([], (row, acc) => [...acc, ...row]);
```

## Handle the Errors

Query errors are returned in two different ways.

* The `connection.query()` method throws an error object, and the `error.response.data` object contains the following properties:

| Error Property | Description                                                               |
| :------------- | :------------------------------------------------------------------------ |
| errorCode      | Code of error                                                             |
| message        | Description of the error                                                  |
| traceId        | The identifier that you can give Peaka Team to learn more about the error |

* The `connection.query()` method returns successfully, but the response may include an `error` object with the following structure:

```typescript theme={null}
type QueryError = {
    message: string;
    errorCode: number;
    errorName: string;
    errorType: string;
    failureInfo: QueryFailureInfo;
};
```

In order to handle all possible errors, please make sure to check both objects, as demonstrated in the example below:

```typescript theme={null}
try{
  const iter = await connection.query(
    'SELECT * FROM "peaka"."table"."lookup table"'
  );
  
  for await (const queryResult of iter) {
    if(queryResult.error){
      console.log("error", queryResult.error);
    }
  }
}catch(e){
  console.log("e", e.response.data);
}
```
