smartclickhouse/ts/smartclickhouse.classes.httpclient.ts

86 lines
2.8 KiB
TypeScript
Raw Permalink Normal View History

2022-07-28 14:53:07 +00:00
import * as plugins from './smartclickhouse.plugins.js';
export interface IClickhouseHttpClientOptions {
user?: 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);
this.computedProperties.parsedUrl.username = this.options.user ? this.options.user : '';
this.computedProperties.parsedUrl.password = this.options.password ? this.options.password : '';
this.computedProperties.connectionUrl = this.computedProperties.parsedUrl.toString();
}
public async ping() {
const parsedUrlForPing = plugins.smarturl.Smarturl.createFromUrl(
this.computedProperties.connectionUrl.toString()
);
parsedUrlForPing.username = null;
parsedUrlForPing.password = null;
const ping = await this.webrequestInstance.request(parsedUrlForPing.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'
});
// console.log('===================');
// 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')
});
return response;
}
}