import * as plugins from './smartclickhouse.plugins.js'; export interface IClickhouseHttpClientOptions { username?: string; password?: string; url: string; } export class ClickhouseHttpClient { // STATIC public static async createAndStart(optionsArg: IClickhouseHttpClientOptions) { const clickhouseHttpInstance = new ClickhouseHttpClient(optionsArg); await clickhouseHttpInstance.start(); return clickhouseHttpInstance; } // INSTANCE public options: IClickhouseHttpClientOptions; public webrequestInstance = new plugins.webrequest.WebRequest({ logging: false, }); public computedProperties: { connectionUrl: string; parsedUrl: plugins.smarturl.Smarturl; } = { connectionUrl: null, parsedUrl: null, }; constructor(optionsArg: IClickhouseHttpClientOptions) { this.options = optionsArg; } public async start() { this.computedProperties.parsedUrl = plugins.smarturl.Smarturl.createFromUrl(this.options.url); console.log(this.computedProperties.parsedUrl); this.computedProperties.connectionUrl = this.computedProperties.parsedUrl.toString(); } public async ping() { const ping = await this.webrequestInstance.request( this.computedProperties.connectionUrl.toString(), { method: 'GET', timeoutMs: 1000, } ); return ping.status === 200 ? true : false; } public async queryPromise(queryArg: string) { const returnArray = []; const response = await this.webrequestInstance.request( `${this.computedProperties.connectionUrl}?query=${encodeURIComponent(queryArg)}`, { method: 'POST', headers: this.getHeaders(), } ); // console.log('==================='); // console.log(this.computedProperties.connectionUrl); // console.log(queryArg); // console.log((await response.clone().text()).split(/\r?\n/)) if (response.headers.get('X-ClickHouse-Format') === 'JSONEachRow') { const jsonList = await response.text(); const jsonArray = jsonList.split('\n'); for (const jsonArg of jsonArray) { if (!jsonArg) { continue; } returnArray.push(JSON.parse(jsonArg)); } } else { } return returnArray; } public async insertPromise(databaseArg: string, tableArg: string, documents: any[]) { const queryArg = `INSERT INTO ${databaseArg}.${tableArg} FORMAT JSONEachRow`; const response = await this.webrequestInstance.request( `${this.computedProperties.connectionUrl}?query=${encodeURIComponent(queryArg)}`, { method: 'POST', body: documents.map((docArg) => JSON.stringify(docArg)).join('\n'), headers: this.getHeaders(), } ); return response; } private getHeaders() { const headers: { [key: string]: string } = {}; if (this.options.username) { headers['X-ClickHouse-User'] = this.options.username; } if (this.options.password) { headers['X-ClickHouse-Key'] = this.options.password; } return headers; } }