2021-07-18 14:26:05 +00:00
|
|
|
import { Injectable } from '@nestjs/common';
|
|
|
|
|
import { QueryResult } from 'src/modules/data_sources/query_result.type';
|
|
|
|
|
import { ConnectionTestResult } from 'src/modules/data_sources/connection_test_result.type';
|
|
|
|
|
import { QueryService } from 'src/modules/data_sources/query_service.interface';
|
2021-09-21 13:48:28 +00:00
|
|
|
const Redis = require('ioredis');
|
2021-07-18 14:26:05 +00:00
|
|
|
import { QueryError } from 'src/modules/data_sources/query.error';
|
|
|
|
|
|
|
|
|
|
@Injectable()
|
|
|
|
|
export default class RedisQueryService implements QueryService {
|
|
|
|
|
async run(sourceOptions: any, queryOptions: any, 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
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async testConnection(sourceOptions: object): Promise<ConnectionTestResult> {
|
|
|
|
|
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
|
|
|
}
|
|
|
|
|
|
2021-09-21 13:48:28 +00:00
|
|
|
async getConnection(sourceOptions: any): 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;
|
|
|
|
|
}
|
|
|
|
|
}
|