n8n/packages/nodes-base/nodes/Wordpress/GenericFunctions.ts

66 lines
2 KiB
TypeScript
Raw Normal View History

2019-12-31 13:24:01 -08:00
import { OptionsWithUri } from 'request';
import {
IExecuteFunctions,
IExecuteSingleFunctions,
ILoadOptionsFunctions,
2019-12-31 13:24:01 -08:00
} from 'n8n-core';
import { IDataObject } from 'n8n-workflow';
export async function wordpressApiRequest(this: IExecuteFunctions | IExecuteSingleFunctions | ILoadOptionsFunctions, method: string, resource: string, body: any = {}, qs: IDataObject = {}, uri?: string, option: IDataObject = {}): Promise<any> { // tslint:disable-line:no-any
const credentials = this.getCredentials('wordpressApi');
if (credentials === undefined) {
throw new Error('No credentials got returned!');
}
let options: OptionsWithUri = {
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
auth: {
user: credentials!.username as string,
password: credentials!.password as string,
},
2019-12-31 13:24:01 -08:00
method,
qs,
body,
uri: uri ||`${credentials!.url}/wp-json/wp/v2${resource}`,
2019-12-31 13:24:01 -08:00
json: true
};
options = Object.assign({}, options, option);
if (Object.keys(options.body).length === 0) {
delete options.body;
}
try {
return await this.helpers.request!(options);
} catch (error) {
let errorMessage = error.message;
if (error.response.body) {
errorMessage = error.response.body.message || error.response.body.Message || error.message;
}
throw new Error('Wordpress Error: ' + errorMessage);
2019-12-31 13:24:01 -08:00
}
}
2020-01-02 14:34:48 -08:00
export async function wordpressApiRequestAllItems(this: IExecuteFunctions | ILoadOptionsFunctions, method: string, endpoint: string, body: any = {}, query: IDataObject = {}): Promise<any> { // tslint:disable-line:no-any
2020-01-01 07:58:27 -08:00
const returnData: IDataObject[] = [];
let responseData;
query.per_page = 10;
2020-01-02 14:34:48 -08:00
query.page = 0;
2020-01-01 07:58:27 -08:00
do {
2020-01-02 14:34:48 -08:00
query.page++;
responseData = await wordpressApiRequest.call(this, method, endpoint, body, query, undefined, { resolveWithFullResponse: true });
2020-01-02 14:34:48 -08:00
returnData.push.apply(returnData, responseData.body);
2020-01-01 07:58:27 -08:00
} while (
2020-01-02 14:34:48 -08:00
responseData.headers['x-wp-totalpages'] !== undefined &&
parseInt(responseData.headers['x-wp-totalpages'], 10) < query.page
2020-01-01 07:58:27 -08:00
);
return returnData;
}