2021-07-25 12:34:36 +00:00
|
|
|
import { HTTPError } from 'got';
|
2022-03-10 06:59:48 +00:00
|
|
|
import { QueryError, QueryResult, QueryService } from '@tooljet-plugins/common';
|
|
|
|
|
import got from 'got';
|
|
|
|
|
import { SourceOptions, QueryOptions } from './types';
|
2021-07-25 12:34:36 +00:00
|
|
|
|
|
|
|
|
export default class GraphqlQueryService implements QueryService {
|
2023-01-16 09:34:12 +00:00
|
|
|
constructor(private sendRequest = got) {}
|
|
|
|
|
|
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 = {};
|
2021-07-25 12:34:36 +00:00
|
|
|
|
|
|
|
|
const url = sourceOptions.url;
|
2022-06-02 04:28:20 +00:00
|
|
|
const { query, variables } = queryOptions;
|
2023-01-16 09:34:12 +00:00
|
|
|
// Query takes precedence over source.
|
|
|
|
|
const headers = {
|
|
|
|
|
...Object.fromEntries(sourceOptions['headers']),
|
|
|
|
|
...Object.fromEntries(queryOptions['headers'] ?? []),
|
|
|
|
|
};
|
|
|
|
|
|
2021-07-25 12:34:36 +00:00
|
|
|
const searchParams = Object.fromEntries(sourceOptions['url_params']);
|
|
|
|
|
|
2023-01-16 09:34:12 +00:00
|
|
|
// Remove invalid entries from the headers and searchParams objects
|
2021-09-21 13:48:28 +00:00
|
|
|
Object.keys(headers).forEach((key) => (headers[key] === '' ? delete headers[key] : {}));
|
2023-01-16 09:34:12 +00:00
|
|
|
Object.keys(searchParams).forEach((key) => (searchParams[key] === '' ? delete searchParams[key] : {}));
|
2021-07-25 12:34:36 +00:00
|
|
|
|
|
|
|
|
const json = {
|
2021-09-21 13:48:28 +00:00
|
|
|
query,
|
2022-06-02 04:28:20 +00:00
|
|
|
variables: variables || {},
|
2021-09-21 13:48:28 +00:00
|
|
|
};
|
2021-07-25 12:34:36 +00:00
|
|
|
|
|
|
|
|
try {
|
2023-01-16 09:34:12 +00:00
|
|
|
const response = await this.sendRequest(url, {
|
2021-07-25 12:34:36 +00:00
|
|
|
method: 'post',
|
|
|
|
|
headers,
|
|
|
|
|
searchParams,
|
2021-09-21 13:48:28 +00:00
|
|
|
json,
|
2021-07-25 12:34:36 +00:00
|
|
|
});
|
|
|
|
|
result = JSON.parse(response.body);
|
|
|
|
|
} catch (error) {
|
|
|
|
|
console.log(error);
|
2021-09-21 13:48:28 +00:00
|
|
|
if (error instanceof HTTPError) {
|
2021-07-25 12:34:36 +00:00
|
|
|
result = {
|
2021-09-21 13:48:28 +00:00
|
|
|
code: error.code,
|
|
|
|
|
};
|
2021-07-25 12:34:36 +00:00
|
|
|
}
|
|
|
|
|
throw new QueryError('Query could not be completed', error.message, result);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return {
|
|
|
|
|
status: 'ok',
|
2021-09-21 13:48:28 +00:00
|
|
|
data: result,
|
|
|
|
|
};
|
2021-07-25 12:34:36 +00:00
|
|
|
}
|
|
|
|
|
}
|