n8n/packages/nodes-base/nodes/Wordpress/GenericFunctions.ts
Elias Meire 100d9bc087
refactor: Add IRequestOptions type to helpers.request for more type safety (no-changelog) (#8563)
Co-authored-by: कारतोफ्फेलस्क्रिप्ट™ <aditya@netroy.in>
2024-02-14 16:29:09 +01:00

77 lines
1.9 KiB
TypeScript

import type {
IExecuteFunctions,
ILoadOptionsFunctions,
IDataObject,
JsonObject,
IHttpRequestMethods,
IRequestOptions,
} from 'n8n-workflow';
import { NodeApiError } from 'n8n-workflow';
export async function wordpressApiRequest(
this: IExecuteFunctions | ILoadOptionsFunctions,
method: IHttpRequestMethods,
resource: string,
body: any = {},
qs: IDataObject = {},
uri?: string,
option: IDataObject = {},
): Promise<any> {
const credentials = await this.getCredentials('wordpressApi');
let options: IRequestOptions = {
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
'User-Agent': 'n8n',
},
method,
qs,
body,
uri: uri || `${credentials.url}/wp-json/wp/v2${resource}`,
rejectUnauthorized: !credentials.allowUnauthorizedCerts,
json: true,
};
options = Object.assign({}, options, option);
if (Object.keys(options.body as IDataObject).length === 0) {
delete options.body;
}
try {
const credentialType = 'wordpressApi';
return await this.helpers.requestWithAuthentication.call(this, credentialType, options);
} catch (error) {
throw new NodeApiError(this.getNode(), error as JsonObject);
}
}
export async function wordpressApiRequestAllItems(
this: IExecuteFunctions | ILoadOptionsFunctions,
method: IHttpRequestMethods,
endpoint: string,
body: any = {},
query: IDataObject = {},
): Promise<any> {
const returnData: IDataObject[] = [];
let responseData;
query.per_page = 10;
query.page = 0;
do {
query.page++;
responseData = await wordpressApiRequest.call(this, method, endpoint, body, query, undefined, {
resolveWithFullResponse: true,
});
returnData.push.apply(returnData, responseData.body as IDataObject[]);
} while (
responseData.headers['x-wp-totalpages'] !== undefined &&
responseData.headers['x-wp-totalpages'] !== '0' &&
parseInt(responseData.headers['x-wp-totalpages'] as string, 10) !== query.page
);
return returnData;
}