Skip to content

Commit

Permalink
fix: parse json output
Browse files Browse the repository at this point in the history
  • Loading branch information
2fd committed Dec 21, 2021
1 parent dfbceb2 commit 903379e
Showing 1 changed file with 21 additions and 3 deletions.
24 changes: 21 additions & 3 deletions bin/fetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,10 @@ const parser = yargs
description: "Path to identity.json file",
type: "string",
})
.option("json", {
description: "Send and recieve data as json",
type: "boolean",
})
.option("header", {
alias: "H",
type: "array",
Expand Down Expand Up @@ -91,18 +95,23 @@ Promise.resolve()
init.method = String(args.method || "GET").toLowerCase();
}

const headers: globalThis.Headers = new Headers() as any;
if (args.header && args.header.length > 0) {
const headers: globalThis.Headers = new Headers() as any;
for (const h of args.header) {
const header = String(h);
const separator = header.indexOf(":");
const key = header.slice(0, separator).trim();
const value = header.slice(separator + 1).trim();
headers.append(key, value);
}
init.headers = headers;
}

if (args.json) {
headers.append("Content-Type", "application/json");
}

init.headers = headers;

if (args.data) {
init.body = readOption(args.data);
}
Expand All @@ -119,7 +128,16 @@ Promise.resolve()

const body = await response.text();
console.log();
console.log(body);
if (args.json) {
try {
const json = JSON.parse(body);
console.log(JSON.stringify(json, null, 2));
} catch {
console.log(body);
}
} else {
console.log(body);
}
})
.catch((err) => {
console.error(colors.red(err.message));
Expand Down

0 comments on commit 903379e

Please sign in to comment.