2023-01-27 03:22:44 -08:00
|
|
|
import type { OptionsWithUri } from 'request';
|
2022-08-01 13:47:55 -07:00
|
|
|
|
2023-03-09 09:13:15 -08:00
|
|
|
import type {
|
|
|
|
IExecuteFunctions,
|
|
|
|
ILoadOptionsFunctions,
|
|
|
|
IDataObject,
|
|
|
|
JsonObject,
|
|
|
|
} from 'n8n-workflow';
|
2023-01-27 03:22:44 -08:00
|
|
|
import { NodeApiError } from 'n8n-workflow';
|
2021-03-18 15:34:15 -07:00
|
|
|
|
|
|
|
export async function deepLApiRequest(
|
2023-08-16 06:52:41 -07:00
|
|
|
this: IExecuteFunctions | ILoadOptionsFunctions,
|
2021-03-18 15:34:15 -07:00
|
|
|
method: string,
|
|
|
|
resource: string,
|
|
|
|
body: IDataObject = {},
|
|
|
|
qs: IDataObject = {},
|
|
|
|
uri?: string,
|
|
|
|
headers: IDataObject = {},
|
|
|
|
) {
|
2021-05-30 10:33:43 -07:00
|
|
|
const proApiEndpoint = 'https://api.deepl.com/v2';
|
|
|
|
const freeApiEndpoint = 'https://api-free.deepl.com/v2';
|
|
|
|
|
2021-08-20 09:57:30 -07:00
|
|
|
const credentials = await this.getCredentials('deepLApi');
|
2021-05-30 10:33:43 -07:00
|
|
|
|
2021-03-18 15:34:15 -07:00
|
|
|
const options: OptionsWithUri = {
|
|
|
|
headers: {
|
2022-07-05 00:02:25 -07:00
|
|
|
'Content-Type': 'application/x-www-form-urlencoded',
|
2021-03-18 15:34:15 -07:00
|
|
|
},
|
|
|
|
method,
|
2022-07-05 00:02:25 -07:00
|
|
|
form: body,
|
2021-03-18 15:34:15 -07:00
|
|
|
qs,
|
2023-01-19 04:37:19 -08:00
|
|
|
uri: uri || `${credentials.apiPlan === 'pro' ? proApiEndpoint : freeApiEndpoint}${resource}`,
|
2021-03-18 15:34:15 -07:00
|
|
|
json: true,
|
|
|
|
};
|
|
|
|
|
|
|
|
try {
|
|
|
|
if (Object.keys(headers).length !== 0) {
|
|
|
|
options.headers = Object.assign({}, options.headers, headers);
|
|
|
|
}
|
|
|
|
|
|
|
|
if (Object.keys(body).length === 0) {
|
|
|
|
delete options.body;
|
|
|
|
}
|
|
|
|
|
2022-07-05 00:02:25 -07:00
|
|
|
return await this.helpers.requestWithAuthentication.call(this, 'deepLApi', options);
|
2021-03-18 15:34:15 -07:00
|
|
|
} catch (error) {
|
2022-07-05 00:02:25 -07:00
|
|
|
throw new NodeApiError(this.getNode(), error as JsonObject);
|
2021-03-18 15:34:15 -07:00
|
|
|
}
|
|
|
|
}
|