Skip to content

Commit

Permalink
Refactor fetch wrapper w/HTTP codes + more resp data (#59)
Browse files Browse the repository at this point in the history
  • Loading branch information
jeff-mccoy authored Apr 25, 2023
1 parent 5807205 commit 88fab5a
Show file tree
Hide file tree
Showing 6 changed files with 47 additions and 14 deletions.
2 changes: 2 additions & 0 deletions index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import k8s from "@kubernetes/client-node";
import { StatusCodes as fetchStatus } from "http-status-codes";
import utils from "ramda";
import { Capability } from "./src/lib/capability";
import { fetch, fetchRaw } from "./src/lib/fetch";
Expand All @@ -22,6 +23,7 @@ export {
utils,
fetch,
fetchRaw,
fetchStatus,
k8s,

// Export the imported type information for external packages
Expand Down
6 changes: 6 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@
"commander": "10.0.1",
"express": "4.18.2",
"fast-json-patch": "3.1.1",
"http-status-codes": "2.2.0",
"node-fetch": "2.6.9",
"node-forge": "1.3.1",
"prettier": "2.8.8",
Expand Down
8 changes: 5 additions & 3 deletions src/cli/init/templates/capabilities/hello-pepr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -168,12 +168,14 @@ When(a.ConfigMap)
.IsCreated()
.WithLabel("chuck-norris")
.Then(async change => {
const joke = await fetch<TheChuckNorrisJoke>(
const response = await fetch<TheChuckNorrisJoke>(
"https://api.chucknorris.io/jokes/random?category=dev"
);

// Add the Chuck Norris joke to the configmap
change.Raw.data["chuck-says"] = joke.value;
if (response.ok) {
// Add the Chuck Norris joke to the configmap
change.Raw.data["chuck-says"] = response.data.value;
}
});

/**
Expand Down
11 changes: 7 additions & 4 deletions src/lib/fetch.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,9 @@ test.beforeEach(() => {

test("fetch: should return without type data", async t => {
const url = "https://jsonplaceholder.typicode.com/todos/1";
const response = await fetch(url);
t.is(response["title"], "Example title");
const { data, ok } = await fetch(url);
t.is(ok, true);
t.is(data["title"], "Example title");
});

test("fetch: should return parsed JSON response as a specific type", async t => {
Expand All @@ -39,7 +40,8 @@ test("fetch: should return parsed JSON response as a specific type", async t =>
}

const url = "https://jsonplaceholder.typicode.com/todos/1";
const data = await fetch<Todo>(url);
const { data, ok } = await fetch<Todo>(url);
t.is(ok, true);
t.is(data.id, 1);
t.is(typeof data.title, "string");
t.is(typeof data.completed, "boolean");
Expand All @@ -59,7 +61,8 @@ test("fetch: should handle additional request options", async t => {
},
};

const data = await fetch(url, requestOptions);
const { data, ok } = await fetch(url, requestOptions);
t.is(ok, true);
t.is(data["title"], "test todo");
t.is(data["userId"], 1);
t.is(data["completed"], false);
Expand Down
33 changes: 26 additions & 7 deletions src/lib/fetch.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: 2023-Present The Pepr Authors

import { StatusCodes } from "http-status-codes";
import f, { RequestInfo, RequestInit } from "node-fetch";
import logger from "./logger";
export { f as fetchRaw };

/**
Expand All @@ -18,13 +20,30 @@ export { f as fetchRaw };
* @returns
*/
export async function fetch<T>(url: URL | RequestInfo, init?: RequestInit) {
const resp = await f(url, init);
try {
logger.debug(`Fetching ${url}`);

// Throw an error if the response is not OK
if (!resp.ok) {
throw new Error(`HTTP ${resp.status} ${resp.statusText}`);
}
const resp = await f(url, init);
let data: T;

if (resp.ok) {
data = await resp.json();
}

const data = await resp.json();
return data as T;
return {
data,
ok: resp.ok,
status: resp.status,
statusText: resp.statusText,
};
} catch (e) {
logger.debug(`Fetch failed: ${e.message}`);

return {
data: null,
ok: false,
status: e.code || StatusCodes.BAD_REQUEST,
statusText: e.message,
};
}
}

0 comments on commit 88fab5a

Please sign in to comment.