@depyronick/nestjs-clickhouse

中文文档
2.1.0发布于 2026/01/21MITTypeScriptCommonJS近 30 天下载 3526

ClickHouse Client Module for NestJS

原始使用文档
文档目录12 节
  1. Description
  2. Installation
  3. Quick Start
  4. Importing the module
  5. Interacting with ClickHouse Client
  6. Examples
  7. Multiple Clients
  8. Async Registration & Async Providers
  9. Notes
  10. Support
  11. Stay in touch
  12. License

Description

ClickHouse® is an open-source, high performance columnar OLAP database management system for real-time analytics using SQL. ClickHouse combined with TypeScript helps you develop better type safety with your ClickHouse queries, giving you end-to-end typing.

Installation

Install the following package:

$ npm i --save @depyronick/nestjs-clickhouse

Quick Start

This NestJS module is a wrapper for @depyronick/clickhouse-client. You can find latest documentation for methods there.

Importing the module

Once the installation process is complete, we can import the ClickHouseModule into the root AppModule.

import { Module } from '@nestjs/common';
import { ClickHouseModule } from '@depyronick/nestjs-clickhouse';

@Module({
  imports: [
    ClickHouseModule.register([
      {
        name: 'ANALYTICS_SERVER',
        host: '127.0.0.1',
        password: '7h3ul71m473p4555w0rd',
      },
    ]),
  ],
})
export class AppModule {}

The register() method will register a ClickHouse client with the specified connection options.

See ClickHouseOptions object for more information.

Each registered client should have an unique name definition. The default value for name property is CLICKHOUSE_DEFAULT. This property will be used as an injection token.

Interacting with ClickHouse Client

To interact with the ClickHouse server that you have just registered, inject it to your class using the injection token.

constructor(
    @Inject('ANALYTICS_SERVER')
    private analyticsServer: ClickHouseClient
) {}

The ClickHouseClient class is imported from the @depyronick/nestjs-clickhouse.

Examples

⚠️ These are only a few examples, please see @depyronick/clickhouse-client for up to date methods, like Parametrized Query Capabilities.

ClickHouseClient.query<T>(query: string): Observable<T>

import { Inject, Injectable } from '@nestjs/common';
import { ClickHouseClient } from '@depyronick/nestjs-clickhouse';

interface VisitsTable {
  timestamp: number;
  ip: string;
  userAgent: string;
  os: string;
  version: string;
  // ...
}

@Injectable()
export class AppService {
  constructor(
    @Inject('ANALYTICS_SERVER')
    private readonly analyticsServer: ClickHouseClient,
  ) {
    this.analyticsServer
      .query<VisitsTable>('SELECT * FROM visits LIMIT 10')
      .subscribe({
        error: (err: any): void => {
          // called when an error occurred during query
        },
        next: (row): void => {
          // called for each row
          // the type of row property here is VisitsTable
        },
        complete: (): void => {
          // called when stream is completed
        },
      });
  }
}

ClickHouseClient.queryPromise<T>(query: string): Promise<T[]>

import { Inject, Injectable } from '@nestjs/common';
import { ClickHouseClient } from '@depyronick/nestjs-clickhouse';

interface VisitsTable {
  timestamp: number;
  ip: string;
  userAgent: string;
  os: string;
  version: string;
  // ...
}

@Injectable()
export class AppService {
  constructor(
    @Inject('ANALYTICS_SERVER')
    private readonly analyticsServer: ClickHouseClient,
  ) {
    this.analyticsServer
      .queryPromise<VisitsTable>('SELECT * FROM visits LIMIT 10')
      .then((rows: VisitsTable[]) => {
        // all retrieved rows
      })
      .catch((err) => {
        // called when an error occurred during query
      });

    // or

    const rows = await this.analyticsServer.queryPromise(
      'SELECT * FROM visits LIMIT 10',
    );
  }
}

ClickHouseClient.insert<T>(table: string, data: T[]): Observable<any>

The insert method accepts two inputs.

  • table is the name of the table that you'll be inserting data to.
    • Table value could be prefixed with database like analytics_db.visits.
  • data: T[] array of JSON objects to insert.
import { Inject, Injectable } from '@nestjs/common';
import { ClickHouseClient } from '@depyronick/nestjs-clickhouse';

interface VisitsTable {
  timestamp: number;
  ip: string;
  userAgent: string;
  os: string;
  version: string;
  // ...
}

@Injectable()
export class AppService {
  constructor(
    @Inject('ANALYTICS_SERVER')
    private readonly analyticsServer: ClickHouseClient,
  ) {
    this.analyticsServer
      .insert<VisitsTable>('visits', [
        {
          timestamp: new Date().getTime(),
          ip: '127.0.0.1',
          os: 'OSX',
          userAgent:
            'Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/95.0.4638.69 Safari/537.36',
          version: '1.0.0',
        },
      ])
      .subscribe({
        error: (err: any): void => {
          // called when an error occurred during insert
        },
        next: (): void => {
          // currently next does not emits anything for inserts
        },
        complete: (): void => {
          // called when insert is completed
        },
      });
  }
}

Multiple Clients

You can register multiple clients in the same application as follows:

@Module({
  imports: [
    ClickHouseModule.register([
      {
        name: 'ANALYTICS_SERVER',
        host: '127.0.0.1',
        password: '7h3ul71m473p4555w0rd',
      },
      {
        name: 'CHAT_SERVER',
        host: '192.168.1.110',
        password: 'ch5ts3rv3Rp455w0rd',
      },
    ]),
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

Then you can interact with these servers using their assigned injection tokens.

constructor(
    @Inject('ANALYTICS_SERVER')
    private analyticsServer: ClickHouseClient,

    @Inject('CHAT_SERVER')
    private chatServer: ClickHouseClient
) { }

Async Registration & Async Providers

For example, if you want to wait for the application to accept new connections until the necessary configuration settings for clickhouse are received from an asynchronous target, you can use the registerAsync method.

import { Inject, Module } from '@nestjs/common';
import { ClickHouseModule } from '@depyronick/nestjs-clickhouse';
import { ConfigModule, ConfigService } from '@nestjs/config';

@Module({
  imports: [
    ConfigModule.forRoot({
      envFilePath: ['.development.env'],
      isGlobal: true,
    }),
    ClickHouseModule.registerAsync({
      useFactory: (config: ConfigService) => {
        return {
          host: config.get('CH_HOST'),
          database: config.get('CH_DB'),
          password: config.get('CH_PWD'),
          username: config.get('CH_USERNAME'),
        };
      },
      inject: [ConfigService],
    }),
  ],
  controllers: [],
  providers: [],
})
export class AppModule {}

Then you can use the CLICKHOUSE_ASYNC_INSTANCE_TOKEN to inject the ClickHouseClient with the asynchronous configuration that you just provided.

import {
  ClickHouseClient,
  CLICKHOUSE_ASYNC_INSTANCE_TOKEN,
} from '@depyronick/nestjs-clickhouse';

export class AppModule {
  constructor(
    @Inject(CLICKHOUSE_ASYNC_INSTANCE_TOKEN)
    private readonly chWithAsyncConfig: ClickHouseClient,
  ) {
    this.chWithAsyncConfig
      .query('SELECT * FROM [TABLE] LIMIT 1')
      .subscribe((row) => console.log('row', row));
  }
}

You can also use the InjectClickHouse helper to avoid importing Inject directly:

import { ClickHouseClient, InjectClickHouse } from '@depyronick/nestjs-clickhouse';

export class AppModule {
  constructor(
    @InjectClickHouse()
    private readonly chWithAsyncConfig: ClickHouseClient,
  ) {}
}

If you registered a named client, pass its name to InjectClickHouse('ANALYTICS_SERVER').

If you want to define more than one ClickHouseClient using registerAsync method, you will need to create different modules, and inject CLICKHOUSE_ASYNC_INSTANCE_TOKEN into feature modules.

But you don't have to use registerAsync method to create asynchronous ClickHouseClient instances. You can also use custom providers:

import { Inject, Module } from '@nestjs/common';
import { ClickHouseClient } from '@depyronick/nestjs-clickhouse';
import { ConfigModule, ConfigService } from '@nestjs/config';

@Module({
  imports: [
    ConfigModule.forRoot({
      envFilePath: ['.development.env'],
      isGlobal: true,
    }),
  ],
  controllers: [],
  providers: [
    {
      provide: 'CH2',
      useFactory: (config: ConfigService) => {
        return new ClickHouseClient({
          host: config.get('CH2_HOST'),
          database: config.get('CH2_DB'),
          password: config.get('CH2_PWD'),
          username: config.get('CH2_USERNAME'),
        });
      },
      inject: [ConfigService],
    },
  ],
})
export class AppModule {
  constructor(
    @Inject('CH2')
    private readonly clickhouse: ClickHouseClient,
  ) {
    this.clickhouse
      .query('SELECT * FROM [TABLE] LIMIT 1')
      .subscribe((row) => console.log('row', row));
  }
}

With custom providers, you can create as many as asynchronously loaded clients with the name you provided.

Notes

  • This repository will be actively maintained and improved.
  • Planning to implement TCP protocol, if ClickHouse decides to documentate it.
  • Planning to implement inserts with streams.
  • This library supports http response compressions such as brotli, gzip and deflate.

Support

Nest is an MIT-licensed open source project. It can grow thanks to the sponsors and support by the amazing backers. If you'd like to join them, please read more here.

Stay in touch

License

MIT licensed.

版本与发布记录

@depyronick/nestjs-clickhouse 共发布 17 个版本,首次发布于 2021/11/12;过去 12 个月发布了 1 个版本。

版本发布日期距今
2.1.0latest2026/01/219 个月前
2.0.52024/10/172 年前
2.0.42024/01/292 年前
2.0.22023/04/193 年前
2.0.12023/02/203 年前
2.0.02022/11/243 年前

关于 @depyronick/nestjs-clickhouse 的常见问题

@depyronick/nestjs-clickhouse 是什么?

ClickHouse Client Module for NestJS

如何安装 @depyronick/nestjs-clickhouse?

在项目目录运行 npm install @depyronick/nestjs-clickhouse,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:@nestjs/common(^10.0.0 || ^11.0.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@depyronick/nestjs-clickhouse 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@depyronick/nestjs-clickhouse 支持 ESM 还是 CommonJS?

以 CommonJS 形式发布,可以直接 require();在 ES Module 项目中也可以用 import 引入(Node.js 会把 module.exports 作为默认导出)。

@depyronick/nestjs-clickhouse 可以商用吗?

@depyronick/nestjs-clickhouse 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@depyronick/nestjs-clickhouse 的下载量有多少?

根据 npm 官方下载统计,@depyronick/nestjs-clickhouse 在 2026/10/12 – 2026/11/10 这 30 天内被下载 3,526 次,日均约 118 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@depyronick/nestjs-clickhouse 还在维护吗?

最新版本 2.1.0 发布于 2026/01/21(9 个月前);至今共发布 17 个版本,其中过去 12 个月发布了 1 个;首次发布于 2021/11/12。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。