# NestJS integration

`db2kit/nestjs` creates the client once for the application, closes it at shutdown, tags every statement with the route and the request id, and turns db2kit errors into HTTP responses. It ships in the same package: `@nestjs/common`, `@nestjs/core` and `rxjs` are optional peer dependencies, already present in a NestJS application.

## Module

The application reads the configuration file of the project, `db2kit.config.mts`, when Nest creates the client: the one configuration of the CLI and of the application ([configuration.md](configuration.md#the-configuration-file)), never a copy written here.

```ts
// src/app.module.ts
import { Logger, Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { consoleSink, ConsoleLevel, loadConfigFile, statsSink } from 'db2kit';
import { Db2Module } from 'db2kit/nestjs';

export const DB2_STATS = statsSink();

@Module({
  imports: [
    ConfigModule.forRoot(),
    Db2Module.forRootAsync({
      useFactory: async () => {
        // .env assigned to process.env first: the file reads the values of this environment.
        await ConfigModule.envVariablesLoaded;
        const config = await loadConfigFile();
        // What only the application needs is added to what the file gives.
        return {
          config: {
            ...config,
            audit: {
              ...config.audit,
              sinks: [
                consoleSink({ logger: new Logger('Db2'), only: ConsoleLevel.SlowAndErrors }),
                DB2_STATS,
              ],
            },
          },
        };
      },
    }),
  ],
})
export class AppModule {}
```

Without `@nestjs/config`, leave out its two lines: the factory runs once the application loaded its environment, when Nest creates the providers. Without `audit.sinks`, the events go to `consoleSink` through the Nest logger `Db2`, and the factory is one line: `useFactory: async () => ({ config: await loadConfigFile() })`.

`Db2Module.forRoot({ config })` takes a configuration built in code: for tests (with `driver`), or a service that has no configuration file.

| Option            | Default      | Effect                                                                                                                                                   |
| :---------------- | :----------- | :------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `config`          | **required** | The configuration of `createDb2` ([configuration.md](configuration.md)). Without `audit.sinks`, events go to `consoleSink` through the Nest logger `Db2` |
| `context`         | none         | `correlationHeader` and `user` of the interceptor (below)                                                                                                |
| `global`          | `true`       | The client can be injected in every module                                                                                                               |
| `interceptor`     | `true`       | Registers `Db2ContextInterceptor` for every route                                                                                                        |
| `exceptionFilter` | `true`       | Registers `Db2ExceptionFilter` for every route                                                                                                           |
| `driver`          | ibm_db       | Replaces ibm_db, for tests                                                                                                                               |

The warnings of the client (threadpool, connection lost, Db2 unreachable) go through the Nest logger `Db2`.

The factory can take other providers, for what the configuration file does not hold, the options of the interceptor for instance:

```ts
Db2Module.forRootAsync({
  imports: [ConfigModule],
  inject: [ConfigService],
  useFactory: async (settings: ConfigService) => ({
    config: await loadConfigFile(),
    context: { correlationHeader: settings.get('CORRELATION_HEADER') },
  }),
  // global, interceptor and exceptionFilter are given here, never by the factory.
});
```

### Settings compiled with the application

When the settings of the application live in a module of the sources, compiled with it, and `db2kit.config.mts` at the root only imports them for the CLI ([configuration.md](configuration.md#the-settings-of-the-application-inside-its-build)), the factory calls that function itself. A connection whose secrets come from a store (a key vault) is built there too, and replaces the one of the function:

```ts
import { defineConfig } from 'db2kit';
import { databaseConfig } from './database/database.config';

Db2Module.forRootAsync({
  useFactory: async () => {
    await ConfigModule.envVariablesLoaded;
    // readSecret: the function of the application that reads its secret store.
    const [user, password] = await Promise.all([
      readSecret('DB_APP_USER'),
      readSecret('DB_APP_PASSWORD'),
    ]);
    // Refuse rather than start with an empty login.
    if (!user || !password)
      throw new Error('secret store: DB_APP_USER or DB_APP_PASSWORD is empty');
    return {
      config: defineConfig({
        ...databaseConfig(),
        connection: {
          database: process.env.DB_APP_DATABASE!,
          host: process.env.DB_APP_HOST!,
          port: Number(process.env.DB_APP_PORT),
          user,
          password,
        },
      }),
    };
  },
});
```

- Nest waits for an `async` factory before it creates the client: the secrets are read before the first connection.
- The keys are those of `connection` ([configuration.md](configuration.md#connection)): `user`, not `username`. Another key is refused at startup with a `Db2ConfigError` that lists the keys of `connection`.
- `defineConfig` takes the configuration and returns it, for the types: `defineConfig()` without an argument returns nothing.
- Values given this way are read once, when the client is created: a password the store rotates reaches the connections only after a restart. To apply a rotation without restart, the application writes the secrets in `process.env` under the names of `connectionFromEnv`, and writes them again when the store rotates them: the next connection reads them ([configuration.md](configuration.md#from-environment-variables-read-at-each-new-connection)).
- The CLI never runs this factory: it reads `db2kit.config.mts`, its connection from the environment file of `cli.envFile`, on a test subsystem.

## Usage in a service

```ts
import { Inject, Injectable } from '@nestjs/common';
import { sql, type Db2Client } from 'db2kit';
import { DB2 } from 'db2kit/nestjs';

@Injectable()
export class ContractRepository {
  constructor(@Inject(DB2) private readonly db: Db2Client) {}

  search(category: string, lastId: number) {
    return this.db.query<{ ID: number; LABEL: string }>(sql`
      SELECT ID, LABEL FROM MYSCHEMA.CONTRACT
      WHERE CATEGORY = ${category} AND ID > ${lastId}
      ORDER BY ID FETCH FIRST 50 ROWS ONLY`);
  }
}
```

`DB2` is the injection token of the client. Inject it with `@Inject(DB2)`: the type alone does not identify it.

## Shutdown

The client closes its connections and its audit sinks when the application closes: `app.close()`, or a signal when `app.enableShutdownHooks()` is in `main.ts`. Without either, connections stay open until the process exits.

## Context interceptor

Each request runs within a db2kit context: the tag `Controller.method`, the correlation id from the `x-request-id` header (or a new one), and the user when `context.user` is given. Every statement of the request carries the tag and the correlation id in the audit trail.

```ts
Db2Module.forRoot({
  config,
  context: {
    correlationHeader: 'x-correlation-id',
    // The application user, for procedures.defaultInputs functions (procedures.md). Never audited.
    user: (request) => (request as { user?: { login: string } }).user?.login,
  },
});
```

A header value that is not 1 to 128 letters, digits, `.`, `_`, `:` or `-` is replaced by a new id: it ends up in the logs, and a forged value could hide another line. Outside HTTP (microservices, WebSocket), the interceptor sets the tag and a new id.

## Exception filter

`Db2ExceptionFilter` answers db2kit errors that reach the controller with a status and a body a client can act on. The body never carries SQL, a driver message, a host or a value; a server fault (5xx) is logged with its details through the Nest logger `Db2`, without the text of a Db2 error unless `audit.params` is `'full'` (the frames of its stack stay, [audit.md](audit.md#the-text-of-a-db2-error)). `Db2Module` gives the filter the `audit.params` of the client. A filter registered by hand takes it as second argument, `new Db2ExceptionFilter(adapterHost, db.config.audit.params)`, and leaves the text out without it.

| Error                                                                                                                                                           | Status                                                                                        | `code`                                                                                         |
| :-------------------------------------------------------------------------------------------------------------------------------------------------------------- | :-------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------------------- |
| `Db2InputError`: input values refused before sending                                                                                                            | 400                                                                                           | `INVALID_INPUT`, with `issues` (property, parameter, reason)                                   |
| `Db2QueryError` `NULL_NOT_ALLOWED`                                                                                                                              | 400                                                                                           | `NULL_NOT_ALLOWED`                                                                             |
| `Db2QueryError` `VALUE_TOO_LONG`                                                                                                                                | 400                                                                                           | `VALUE_TOO_LONG`                                                                               |
| `Db2QueryError` `DUPLICATE_KEY`, `FOREIGN_KEY`                                                                                                                  | 409                                                                                           | the same                                                                                       |
| `Db2ProcedureRejectedError`: the outcome rule recognized a rejection                                                                                            | 422                                                                                           | `PROC_REJECTED`, with `reasons` and `warnings` per field                                       |
| `Db2ProcedureStatusUnknownError`, `Db2TransactionCommitError`                                                                                                   | 502                                                                                           | `PROC_STATUS_UNKNOWN`, `COMMIT_OUTCOME_UNKNOWN`: the outcome is unknown, check before retrying |
| `Db2UnavailableError`                                                                                                                                           | 503                                                                                           | `UNAVAILABLE`, with a `Retry-After` header                                                     |
| `Db2PoolTimeoutError`, `Db2ConfigError`, `Db2QueryError` `CONNECTION_LOST`, `DEADLOCK_OR_TIMEOUT`, `RESOURCE_UNAVAILABLE`, `AUTHENTICATION_FAILED`, `CANCELLED` | 503                                                                                           | the same                                                                                       |
| `Db2TransactionRolledBackError`                                                                                                                                 | as its cause, the first error inside the transaction; 503 `TRANSACTION_TIMEOUT` for a timeout |                                                                                                |
| any other db2kit error (`SQL_SYNTAX`, `Db2UsageError`, `Db2MaxRowsError`...)                                                                                    | 500                                                                                           | the error code                                                                                 |

```json
{
  "statusCode": 400,
  "error": "Bad Request",
  "code": "INVALID_INPUT",
  "message": "Input values refused.",
  "issues": [
    {
      "property": "amount",
      "parameter": "AMOUNT",
      "reason": "3 decimal places for 2: round the value first (codec digits (scale 2))"
    }
  ]
}
```

Errors of the application itself (`HttpException`...) are left to Nest. To answer differently, set `exceptionFilter: false` and write your own filter: `db2HttpError(error)` gives the mapping above as data.

## Health check

```ts
import { Controller, Get, Inject, ServiceUnavailableException } from '@nestjs/common';
import type { Db2Client } from 'db2kit';
import { DB2, db2HealthCheck } from 'db2kit/nestjs';

@Controller('health')
export class HealthController {
  constructor(@Inject(DB2) private readonly db: Db2Client) {}

  @Get('live')
  live() {
    return db2HealthCheck(this.db); // sends nothing to Db2
  }

  @Get('ready')
  async ready() {
    const health = await db2HealthCheck(this.db, { ping: true }); // one round trip
    if (health.status === 'down') throw new ServiceUnavailableException(health);
    return health;
  }
}
```

`status` is `down` while Db2 counts as unreachable (`connection.state` not `closed`, [production.md](production.md#8-connection-recovery)) or when the ping failed (`pingError` gives its code: `POOL_TIMEOUT` when no connection came within `pool.acquireTimeoutMs`, a server that never answers the login for one, `UNAVAILABLE`, or the code of the driver error). The result holds codes and counters only, never a message or a host. With `@nestjs/terminus`, call `db2HealthCheck` from a custom indicator.

## Packaging

`db2kit/nestjs` imports `db2kit` by its package name, so that it uses the copy the application uses. It works from CommonJS (the NestJS default) and from ES modules, with TypeScript `moduleResolution` `node`, `node16`, `nodenext` or `bundler`. A CommonJS application still runs a second copy, the ES module one its `db2kit.config.mts` imports: the client takes the `procedures.fieldStatus` that copy built, and the filter recognizes an error of either copy by its class ([installation.md](installation.md#configure), One configuration, two module systems). Checked by installing the `npm pack` archive in a throwaway NestJS application (acceptance battery, N1 with a field status in its configuration), and on the built files by `npm run test:package`.
