ToolJet/plugins/packages/openapi/lib/index.ts
Ganesh Kumar 0eb2440023
Release: Marketplace sprint 12 (#13207)
* Feature: Prometheus plugin (#13161)

* prometheus plugin

* added existing props

* Host and database can be dynamically configured in query builder for PostgreSQL and MySQL data sources (#13163)

* Fix: Postgresql datasource tries to connect via ssl even when ssl toggle is off (#13167)

* The ability to provide a partition key for deleting items in CosmosDB datasource has been enabled (#13166)

* Feature: Ability to configure the database name in Redis datasource (#13165)

* Fix: Avoid setting Content-Type header for requests without body and configure different host for all environments in OpenAPI [PRE-RELEASE] (#13230)

* Send content-type only with body in request

* Persist OpenAPI parameters per operation only

* Configure different host

* Add disable styles to the select input

* Feat: New fields 'client id' and 'client secret' have been introduced in the Slack datasource configuration page in pre-release (#13162)

* Update slack frontend

* Update slack backend to handle custom creds

* Add backfill migrations

* Dynamically change dropdown according to versions

* Change migration file name

* Correctly access scope in chat:write logic

---------

Co-authored-by: Akshay Sasidharan <akshaysasidharan93@gmail.com>
Co-authored-by: Parth <108089718+parthy007@users.noreply.github.com>
Co-authored-by: Akshay <akshaysasidrn@gmail.com>
2025-07-11 12:15:39 +05:30

149 lines
4.4 KiB
TypeScript

import {
QueryResult,
User,
App,
OAuthUnauthorizedClientError,
QueryError,
QueryService,
getRefreshedToken,
validateAndSetRequestOptionsBasedOnAuthType,
getAuthUrl,
} from '@tooljet-plugins/common';
import { SourceOptions, QueryOptions, RestAPIResult } from './types';
import got, { HTTPError, OptionsOfTextResponseBody } from 'got';
import urrl from 'url';
export default class Openapi implements QueryService {
private resolvePathParams(params: any, path: string) {
let newString = path;
Object.entries(params).map(([key, value]) => {
newString = newString.replace(`{${key}}`, value as any);
});
return newString;
}
private sanitizeObject(params: any) {
Object.keys(params).forEach((key) => (params[key] === '' ? delete params[key] : {}));
return params;
}
private parseValue = (value) => {
if (typeof value !== 'string') return value;
try {
return JSON.parse(value);
} catch (e) {
return value;
}
};
private parseRequest = (obj) => {
if (!obj) return obj;
return Object.keys(obj).reduce((acc, key) => {
acc[key] = this.parseValue(obj[key]);
return acc;
}, {});
};
async run(
sourceOptions: SourceOptions,
queryOptions: QueryOptions,
dataSourceId: string,
dataSourceUpdatedAt: string,
context?: { user?: User; app?: App }
): Promise<RestAPIResult> {
const { host, path, operation, params } = queryOptions;
const { request, query, header, path: pathParams } = params;
const resolvedHost = sourceOptions.host || host;
const url = new URL(resolvedHost + this.resolvePathParams(pathParams, path));
const parsedRequest = request ? this.parseRequest(request) : undefined;
const json =
operation !== 'get' && parsedRequest && Object.keys(parsedRequest).length > 0
? this.sanitizeObject(parsedRequest)
: undefined;
const _requestOptions: OptionsOfTextResponseBody = {
method: operation,
headers: header,
searchParams: {
...query,
},
};
if (json && Object.keys(json).length > 0) {
_requestOptions.json = json;
}
const authValidatedRequestOptions: QueryResult = await validateAndSetRequestOptionsBasedOnAuthType(
sourceOptions,
context,
_requestOptions,
{ url }
);
const { status, data } = authValidatedRequestOptions;
if (status === 'needs_oauth') return authValidatedRequestOptions;
const requestOptions = data as OptionsOfTextResponseBody;
let result = {};
let requestObject = {};
let responseObject = {};
let responseHeaders = {};
try {
const response = await got(url, requestOptions);
const contentType = response.headers['content-type'];
result = contentType !== 'application/json' ? response.body : JSON.parse(response.body);
requestObject = {
requestUrl: response.request.requestUrl,
method: response.request.options.method,
headers: response.request.options.headers,
params: urrl.parse(response.request.requestUrl.toString(), true).query,
};
responseObject = {
body: response.body,
statusCode: response.statusCode,
};
responseHeaders = response.headers;
} catch (error) {
console.log(error);
if (error instanceof HTTPError) {
result = {
requestObject: {
requestUrl: error.request.requestUrl,
requestHeaders: error.request.options.headers,
requestParams: urrl.parse(error.request.requestUrl.toString(), true).query,
},
responseObject: {
statusCode: error.response.statusCode,
responseBody: error.response.body,
},
responseHeaders: error.response.headers,
};
}
if (sourceOptions['auth_type'] === 'oauth2' && error?.response?.statusCode == 401) {
throw new OAuthUnauthorizedClientError('Unauthorized status from API server', error.message, result);
}
throw new QueryError('Query could not be completed', error.message, result);
}
return {
status: 'ok',
data: result,
request: requestObject,
response: responseObject,
responseHeaders,
};
}
authUrl(sourceOptions: SourceOptions): string {
return getAuthUrl(sourceOptions);
}
async refreshToken(sourceOptions: any, error: any, userId: string, isAppPublic: boolean) {
return getRefreshedToken(sourceOptions, error, userId, isAppPublic);
}
}