2023-03-09 09:13:15 -08:00
|
|
|
import type {
|
|
|
|
IExecuteFunctions,
|
|
|
|
IHookFunctions,
|
|
|
|
IDataObject,
|
|
|
|
ILoadOptionsFunctions,
|
|
|
|
JsonObject,
|
2024-02-14 07:29:09 -08:00
|
|
|
IHttpRequestMethods,
|
|
|
|
IRequestOptions,
|
2023-03-09 09:13:15 -08:00
|
|
|
} from 'n8n-workflow';
|
2023-01-27 03:22:44 -08:00
|
|
|
import { NodeApiError } from 'n8n-workflow';
|
2020-06-12 13:23:36 -07:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Make an API request to HackerNews
|
|
|
|
*
|
|
|
|
*/
|
2022-08-17 08:50:24 -07:00
|
|
|
export async function hackerNewsApiRequest(
|
|
|
|
this: IHookFunctions | IExecuteFunctions | ILoadOptionsFunctions,
|
2024-02-14 07:29:09 -08:00
|
|
|
method: IHttpRequestMethods,
|
2022-08-17 08:50:24 -07:00
|
|
|
endpoint: string,
|
|
|
|
qs: IDataObject,
|
|
|
|
): Promise<any> {
|
2024-02-14 07:29:09 -08:00
|
|
|
const options: IRequestOptions = {
|
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 {
|
2022-12-23 10:09:52 -08:00
|
|
|
return await this.helpers.request(options);
|
2020-06-24 11:02:17 -07:00
|
|
|
} catch (error) {
|
2023-02-27 19:39:43 -08:00
|
|
|
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
|
|
|
|
*/
|
2022-08-17 08:50:24 -07:00
|
|
|
export async function hackerNewsApiRequestAllItems(
|
|
|
|
this: IHookFunctions | IExecuteFunctions | ILoadOptionsFunctions,
|
2024-02-14 07:29:09 -08:00
|
|
|
method: IHttpRequestMethods,
|
2022-08-17 08:50:24 -07:00
|
|
|
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);
|
2023-02-27 19:39:43 -08:00
|
|
|
returnData.push.apply(returnData, responseData.hits as IDataObject[]);
|
2020-06-12 13:23:36 -07:00
|
|
|
|
|
|
|
if (returnData !== undefined) {
|
|
|
|
itemsReceived += returnData.length;
|
|
|
|
}
|
2022-08-17 08:50:24 -07:00
|
|
|
} while (responseData.nbHits > itemsReceived);
|
2020-06-12 13:23:36 -07:00
|
|
|
|
|
|
|
return returnData;
|
|
|
|
}
|