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

63 lines
1.5 KiB
TypeScript
Raw Normal View History

import type { OptionsWithUri } from 'request';
2020-02-26 17:46:00 -08:00
import type { IExecuteFunctions, ILoadOptionsFunctions } from 'n8n-core';
2020-02-26 17:46:00 -08:00
import type { IMessage } from './MessageInterface';
import type { IStream } from './StreamInterface';
import type { IUser } from './UserInterface';
import type { IDataObject, IHookFunctions, IWebhookFunctions, JsonObject } from 'n8n-workflow';
import { NodeApiError } from 'n8n-workflow';
2020-02-26 17:46:00 -08:00
export async function zulipApiRequest(
this: IExecuteFunctions | IWebhookFunctions | IHookFunctions | ILoadOptionsFunctions,
method: string,
resource: string,
body: IMessage | IStream | IUser = {},
query: IDataObject = {},
uri?: string,
option: IDataObject = {},
) {
const credentials = await this.getCredentials('zulipApi');
2020-02-26 17:46:00 -08:00
const endpoint = `${credentials.url}/api/v1`;
let options: OptionsWithUri = {
2020-02-27 14:27:21 -08:00
auth: {
user: credentials.email as string,
password: credentials.apiKey as string,
},
2020-02-26 17:46:00 -08:00
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
method,
form: body,
qs: query,
uri: uri || `${endpoint}${resource}`,
2020-10-22 06:46:03 -07:00
json: true,
2020-02-26 17:46:00 -08:00
};
if (!Object.keys(body).length) {
delete options.form;
}
if (!Object.keys(query).length) {
delete options.qs;
}
options = Object.assign({}, options, option);
try {
return await this.helpers.request(options);
2020-02-26 17:46:00 -08:00
} catch (error) {
throw new NodeApiError(this.getNode(), error as JsonObject);
2020-02-26 17:46:00 -08:00
}
}
2020-05-19 06:19:35 -07:00
export function validateJSON(json: string | undefined): any {
2020-05-19 06:19:35 -07:00
let result;
try {
result = JSON.parse(json!);
} catch (exception) {
result = undefined;
}
return result;
}