2020-06-11 17:40:58 -07:00
|
|
|
import {
|
2020-06-12 00:39:56 -07:00
|
|
|
OptionsWithUri,
|
|
|
|
} from 'request';
|
2020-06-11 15:57:32 -07:00
|
|
|
|
2020-06-11 17:40:58 -07:00
|
|
|
import {
|
2020-06-12 00:39:56 -07:00
|
|
|
IExecuteFunctions,
|
|
|
|
IHookFunctions,
|
|
|
|
} from 'n8n-core';
|
2020-06-11 17:40:58 -07:00
|
|
|
|
|
|
|
import {
|
|
|
|
IDataObject,
|
2020-06-12 00:39:56 -07:00
|
|
|
} from 'n8n-workflow';
|
2020-06-11 15:57:32 -07:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Make an API request to Message Bird
|
|
|
|
*
|
|
|
|
* @param {IHookFunctions} this
|
|
|
|
* @param {string} method
|
|
|
|
* @param {string} url
|
|
|
|
* @param {object} body
|
|
|
|
* @returns {Promise<any>}
|
|
|
|
*/
|
|
|
|
export async function messageBirdApiRequest(
|
|
|
|
this: IHookFunctions | IExecuteFunctions,
|
|
|
|
method: string,
|
|
|
|
resource: string,
|
|
|
|
body: IDataObject,
|
2020-06-11 17:40:58 -07:00
|
|
|
query: IDataObject = {},
|
2020-06-12 00:39:56 -07:00
|
|
|
): Promise<any> { // tslint:disable-line:no-any
|
2020-06-11 15:57:32 -07:00
|
|
|
const credentials = this.getCredentials('messageBirdApi');
|
|
|
|
if (credentials === undefined) {
|
|
|
|
throw new Error('No credentials returned!');
|
|
|
|
}
|
|
|
|
|
|
|
|
const options: OptionsWithUri = {
|
|
|
|
headers: {
|
|
|
|
Accept: 'application/json',
|
2020-06-11 17:40:58 -07:00
|
|
|
Authorization: `AccessKey ${credentials.accessKey}`,
|
2020-06-11 15:57:32 -07:00
|
|
|
},
|
|
|
|
method,
|
|
|
|
qs: query,
|
|
|
|
body,
|
|
|
|
uri: `https://rest.messagebird.com${resource}`,
|
2020-06-12 00:39:56 -07:00
|
|
|
json: true,
|
2020-06-11 15:57:32 -07:00
|
|
|
};
|
|
|
|
|
|
|
|
try {
|
|
|
|
return await this.helpers.request(options);
|
|
|
|
} catch (error) {
|
|
|
|
if (error.statusCode === 401) {
|
|
|
|
throw new Error('The Message Bird credentials are not valid!');
|
|
|
|
}
|
|
|
|
|
|
|
|
if (error.response && error.response.body && error.response.body.errors) {
|
|
|
|
// Try to return the error prettier
|
2020-06-11 17:40:58 -07:00
|
|
|
const errorMessage = error.response.body.errors.map((e: IDataObject) => e.description);
|
|
|
|
|
|
|
|
throw new Error(`MessageBird Error response [${error.statusCode}]: ${errorMessage.join('|')}`);
|
2020-06-11 15:57:32 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
// If that data does not exist for some reason return the actual error
|
2020-06-11 17:40:58 -07:00
|
|
|
throw error;
|
2020-06-11 15:57:32 -07:00
|
|
|
}
|
|
|
|
}
|