Skip to content

Commit d20c6b3

Browse files
allow string and url when fetching from foreign apis
1 parent 94ce150 commit d20c6b3

File tree

1 file changed

+8
-6
lines changed

1 file changed

+8
-6
lines changed

src/lib/apis/fetchForeignAPI.ts

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import fetch, { Request, Response } from 'node-fetch';
1+
import fetch, { Request, RequestInfo, Response } from 'node-fetch';
22
import { ZodSchema } from 'zod';
33
import { Logger } from '../logger';
44

@@ -9,12 +9,14 @@ import { Logger } from '../logger';
99
* @param zodSchema The [Zod](https://github.com/colinhacks/zod) schema that the returned data conforms to. The promise will reject if the returned data does not conform to the schema provided.
1010
* @returns A promise that resolves to the expected type or rejects with an [Error](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error).
1111
*/
12-
export const fetchForeignAPI = async <ReturnType = unknown>(request: Request, zodSchema: ZodSchema<ReturnType>, debug?: boolean): Promise<ReturnType> => {
12+
export const fetchForeignAPI = async <ReturnType = unknown>(request: RequestInfo, zodSchema: ZodSchema<ReturnType>, debug?: boolean): Promise<ReturnType> => {
13+
const req = new Request(request);
14+
1315
let response: Response;
1416
try {
15-
response = await fetch(request);
17+
response = await fetch(req);
1618
} catch (e) {
17-
throw new Error(`An error occured while fetching data from ${request.url}: ${String(e)}`);
19+
throw new Error(`An error occured while fetching data from ${req.url}: ${String(e)}`);
1820
}
1921

2022
if (!response.ok) {
@@ -25,14 +27,14 @@ export const fetchForeignAPI = async <ReturnType = unknown>(request: Request, zo
2527
try {
2628
data = await response.json();
2729
} catch (e) {
28-
throw new Error(`Could not parse JSON. Make sure the endpoint at ${request.url} returns valid JSON. Error: ${String(e)}`);
30+
throw new Error(`Could not parse JSON. Make sure the endpoint at ${req.url} returns valid JSON. Error: ${String(e)}`);
2931
}
3032

3133
const result = zodSchema.safeParse(data);
3234

3335
if (!result.success) {
3436
Logger.error("[zod] Data validation failed! Pass the 'debug' flag to 'fetchForeignAPI()' to print the retrieved data to the console.");
35-
Logger.error(`Endpoint location: ${request.url}.`);
37+
Logger.error(`Endpoint location: ${req.url}.`);
3638
if (debug) {
3739
// winston doesn't usefully log object at the moment
3840
// eslint-disable-next-line no-console

0 commit comments

Comments
 (0)