2022-08-01 13:47:55 -07:00
|
|
|
import { IExecuteFunctions, ILoadOptionsFunctions } from 'n8n-core';
|
2021-08-21 03:53:06 -07:00
|
|
|
|
2022-08-01 13:47:55 -07:00
|
|
|
import { IHookFunctions, IWebhookFunctions, NodeApiError } from 'n8n-workflow';
|
2021-08-21 03:53:06 -07:00
|
|
|
|
|
|
|
interface IFormIoCredentials {
|
|
|
|
environment: 'cloudHosted' | ' selfHosted';
|
|
|
|
domain?: string;
|
2021-08-21 05:11:32 -07:00
|
|
|
email: string;
|
|
|
|
password: string;
|
2021-08-21 03:53:06 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Method has the logic to get jwt token from Form.io
|
|
|
|
*/
|
2022-08-01 13:47:55 -07:00
|
|
|
async function getToken(
|
|
|
|
this: IExecuteFunctions | IWebhookFunctions | IHookFunctions | ILoadOptionsFunctions,
|
|
|
|
credentials: IFormIoCredentials,
|
|
|
|
) {
|
2023-01-13 09:11:56 -08:00
|
|
|
const base = credentials.domain ?? 'https://formio.form.io';
|
2021-08-21 03:53:06 -07:00
|
|
|
const options = {
|
|
|
|
headers: {
|
|
|
|
'Content-Type': 'application/json',
|
|
|
|
},
|
|
|
|
method: 'POST',
|
|
|
|
body: {
|
|
|
|
data: {
|
|
|
|
email: credentials.email,
|
|
|
|
password: credentials.password,
|
|
|
|
},
|
|
|
|
},
|
|
|
|
uri: `${base}/user/login`,
|
|
|
|
json: true,
|
|
|
|
resolveWithFullResponse: true,
|
|
|
|
};
|
|
|
|
|
|
|
|
try {
|
2022-12-23 10:09:52 -08:00
|
|
|
const responseObject = await this.helpers.request(options);
|
2021-08-21 03:53:06 -07:00
|
|
|
return responseObject.headers['x-jwt-token'];
|
|
|
|
} catch (error) {
|
2022-08-01 13:47:55 -07:00
|
|
|
throw new Error(
|
2022-12-29 03:20:43 -08:00
|
|
|
'Authentication Failed for Form.io. Please provide valid credentails/ endpoint details',
|
2022-08-01 13:47:55 -07:00
|
|
|
);
|
2021-08-21 03:53:06 -07:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Method will call register or list webhooks based on the passed method in the parameter
|
|
|
|
*/
|
2022-08-01 13:47:55 -07:00
|
|
|
export async function formIoApiRequest(
|
|
|
|
this: IHookFunctions | ILoadOptionsFunctions | IWebhookFunctions,
|
|
|
|
method: string,
|
|
|
|
endpoint: string,
|
|
|
|
body = {},
|
|
|
|
qs = {},
|
|
|
|
): Promise<any> {
|
|
|
|
const credentials = (await this.getCredentials('formIoApi')) as unknown as IFormIoCredentials;
|
2021-08-21 03:53:06 -07:00
|
|
|
|
|
|
|
const token = await getToken.call(this, credentials);
|
|
|
|
|
2023-01-13 09:11:56 -08:00
|
|
|
const base = credentials.domain ?? 'https://api.form.io';
|
2021-08-21 03:53:06 -07:00
|
|
|
|
|
|
|
const options = {
|
|
|
|
headers: {
|
|
|
|
'Content-Type': 'application/json',
|
|
|
|
'x-jwt-token': token,
|
|
|
|
},
|
|
|
|
method,
|
|
|
|
body,
|
|
|
|
qs,
|
|
|
|
uri: `${base}${endpoint}`,
|
|
|
|
json: true,
|
|
|
|
};
|
|
|
|
|
|
|
|
try {
|
2022-12-23 10:09:52 -08:00
|
|
|
return await this.helpers.request.call(this, options);
|
2021-08-21 03:53:06 -07:00
|
|
|
} catch (error) {
|
|
|
|
throw new NodeApiError(this.getNode(), error);
|
|
|
|
}
|
|
|
|
}
|