2022-03-10 06:59:48 +00:00
|
|
|
import { ConnectionTestResult, QueryError, QueryResult, QueryService } from '@tooljet-plugins/common';
|
2022-01-27 10:31:39 +00:00
|
|
|
import Redis from 'ioredis';
|
2022-03-10 06:59:48 +00:00
|
|
|
import { SourceOptions, QueryOptions } from './types';
|
2021-07-18 14:26:05 +00:00
|
|
|
|
|
|
|
|
export default class RedisQueryService implements QueryService {
|
2022-01-24 13:59:21 +00:00
|
|
|
async run(sourceOptions: SourceOptions, queryOptions: QueryOptions, dataSourceId: string): Promise<QueryResult> {
|
2021-09-21 13:48:28 +00:00
|
|
|
let result = {};
|
|
|
|
|
const query = queryOptions.query;
|
2021-07-18 14:26:05 +00:00
|
|
|
|
|
|
|
|
const client = await this.getConnection(sourceOptions);
|
|
|
|
|
|
|
|
|
|
try {
|
|
|
|
|
const splitQuery = query.split(' ');
|
|
|
|
|
const command = splitQuery[0];
|
|
|
|
|
const args = splitQuery.length > 0 ? splitQuery.slice(1) : [];
|
|
|
|
|
result = await client.call(command, args);
|
|
|
|
|
} catch (err) {
|
|
|
|
|
client.disconnect();
|
|
|
|
|
throw new QueryError('Query could not be completed', err.message, {});
|
|
|
|
|
}
|
|
|
|
|
|
2021-09-21 13:48:28 +00:00
|
|
|
return { status: 'ok', data: result };
|
2021-07-18 14:26:05 +00:00
|
|
|
}
|
|
|
|
|
|
2022-01-24 13:59:21 +00:00
|
|
|
async testConnection(sourceOptions: SourceOptions): Promise<ConnectionTestResult> {
|
2021-07-18 14:26:05 +00:00
|
|
|
const client = await this.getConnection(sourceOptions);
|
|
|
|
|
await client.ping();
|
|
|
|
|
|
|
|
|
|
return {
|
2021-09-21 13:48:28 +00:00
|
|
|
status: 'ok',
|
|
|
|
|
};
|
2021-07-18 14:26:05 +00:00
|
|
|
}
|
|
|
|
|
|
2022-01-24 13:59:21 +00:00
|
|
|
async getConnection(sourceOptions: SourceOptions): Promise<any> {
|
2021-07-18 14:50:39 +00:00
|
|
|
const username = sourceOptions.username;
|
2021-07-18 14:26:05 +00:00
|
|
|
const host = sourceOptions.host;
|
|
|
|
|
const password = sourceOptions.password;
|
|
|
|
|
const port = sourceOptions.port;
|
|
|
|
|
|
2021-07-18 14:50:39 +00:00
|
|
|
const client = new Redis(port, host, { maxRetriesPerRequest: 1, username, password });
|
2021-07-18 14:26:05 +00:00
|
|
|
return client;
|
|
|
|
|
}
|
|
|
|
|
}
|