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

66 lines
1.4 KiB
TypeScript
Raw Normal View History

import type {
IExecuteFunctions,
IHookFunctions,
IDataObject,
ILoadOptionsFunctions,
JsonObject,
} from 'n8n-workflow';
import { NodeApiError } from 'n8n-workflow';
2020-06-12 13:23:36 -07:00
import type { OptionsWithUri } from 'request';
2020-06-12 13:23:36 -07:00
/**
* Make an API request to HackerNews
*
*/
export async function hackerNewsApiRequest(
this: IHookFunctions | IExecuteFunctions | ILoadOptionsFunctions,
method: string,
endpoint: string,
qs: IDataObject,
): Promise<any> {
2020-06-12 13:23:36 -07:00
const options: OptionsWithUri = {
2020-06-24 11:02:17 -07:00
method,
2020-06-12 13:23:36 -07:00
qs,
uri: `http://hn.algolia.com/api/v1/${endpoint}`,
json: true,
};
2020-06-24 11:02:17 -07:00
try {
return await this.helpers.request(options);
2020-06-24 11:02:17 -07:00
} catch (error) {
throw new NodeApiError(this.getNode(), error as JsonObject);
2020-06-24 11:02:17 -07:00
}
2020-06-12 13:23:36 -07:00
}
/**
* Make an API request to HackerNews
* and return all results
*
* @param {(IHookFunctions | IExecuteFunctions)} this
*/
export async function hackerNewsApiRequestAllItems(
this: IHookFunctions | IExecuteFunctions | ILoadOptionsFunctions,
method: string,
endpoint: string,
qs: IDataObject,
): Promise<any> {
2020-06-12 13:23:36 -07:00
qs.hitsPerPage = 100;
const returnData: IDataObject[] = [];
let responseData;
let itemsReceived = 0;
do {
responseData = await hackerNewsApiRequest.call(this, method, endpoint, qs);
returnData.push.apply(returnData, responseData.hits as IDataObject[]);
2020-06-12 13:23:36 -07:00
if (returnData !== undefined) {
itemsReceived += returnData.length;
}
} while (responseData.nbHits > itemsReceived);
2020-06-12 13:23:36 -07:00
return returnData;
}