-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
99 lines (97 loc) · 2.69 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
import { omit } from 'lodash';
import { injectable } from '@biorate/inversion';
import { Connector } from '@biorate/connector';
import { ClickHouse } from 'clickhouse';
import { ClickhouseCantConnectError } from './errors';
import {
IClickhouseConfig,
IClickhouseConnection,
IQueryParams,
IInsertParams,
} from './interfaces';
export * from './errors';
export * from './interfaces';
/**
* @description Clickhouse connector
*
* ### Features:
* - connector manager for Clickhouse
*
* @example
* ```
* import { inject, container, Types, Core } from '@biorate/inversion';
* import { IConfig, Config } from '@biorate/config';
* import { ClickhouseConnector, ClickhouseConfig } from '@biorate/clickhouse';
*
* class Root extends Core() {
* @inject(ClickhouseConnector) public connector: ClickhouseConnector;
* }
*
* container.bind<IConfig>(Types.Config).to(Config).inSingletonScope();
* container.bind<ClickhouseConnector>(ClickhouseConnector).toSelf().inSingletonScope();
* container.bind<Root>(Root).toSelf().inSingletonScope();
*
* container.get<IConfig>(Types.Config).merge({
* Clickhouse: [
* {
* name: 'connection',
* options: {
* },
* },
* ],
* });
*
* (async () => {
* const root = container.get<Root>(Root);
* await root.$run();
*
* const data = await root.connector!.query<{ result: number }>('SELECT 1 AS result;');
* console.log(data); // [{ result: 1 }]
* })();
* ```
*/
@injectable()
export class ClickhouseConnector extends Connector<
IClickhouseConfig,
IClickhouseConnection
> {
/**
* @description Private connections storage
*/
private '#connections': Map<string, IClickhouseConnection>;
/**
* @description Private link to selected (used) connection
*/
private '#current': IClickhouseConnection | undefined;
/**
* @description Namespace path for fetching configuration
*/
protected readonly namespace = 'Clickhouse';
/**
* @description Create connection
*/
protected async connect(config: IClickhouseConfig) {
let connection: ClickHouse;
try {
connection = new ClickHouse(config.options);
await connection.query('SELECT 1').toPromise();
} catch (e: unknown) {
throw new ClickhouseCantConnectError(<Error>e);
}
return connection;
}
/**
* @description Make a query
*/
public query<T = unknown>(query: string, params: IQueryParams = {}) {
return this.get(params.connection)
.query(query, omit(params, 'connection'))
.toPromise() as unknown as Promise<T[]>;
}
/**
* @description Make a insert
*/
public insert(query: string, params: IInsertParams = {}) {
return this.get(params.connection).insert(query, params.rows).toPromise();
}
}