ToolJet/plugins/packages/graphql/lib/index.ts
Gandharv d367720c66
Add source options types for plugins (#1861)
* add source options types

* Remove query type

* fix source options

* add accesstoken - slack

* add types.ts file

* add idx files

* Add query options type for plugins (#1878)

* add query options type

* add missing import
2022-01-24 19:29:21 +05:30

45 lines
1.3 KiB
TypeScript

import { HTTPError } from 'got';
import { QueryError, QueryResult, QueryService} from '@tooljet-plugins/common'
import got from 'got'
import { SourceOptions, QueryOptions } from './types'
export default class GraphqlQueryService implements QueryService {
async run(sourceOptions: SourceOptions, queryOptions: QueryOptions, dataSourceId: string): Promise<QueryResult> {
let result = {};
const url = sourceOptions.url;
const query = queryOptions.query;
const headers = Object.fromEntries(sourceOptions['headers']);
const searchParams = Object.fromEntries(sourceOptions['url_params']);
// Remove invalid headers from the headers object
Object.keys(headers).forEach((key) => (headers[key] === '' ? delete headers[key] : {}));
const json = {
query,
};
try {
const response = await got(url, {
method: 'post',
headers,
searchParams,
json,
});
result = JSON.parse(response.body);
} catch (error) {
console.log(error);
if (error instanceof HTTPError) {
result = {
code: error.code,
};
}
throw new QueryError('Query could not be completed', error.message, result);
}
return {
status: 'ok',
data: result,
};
}
}