Skip to content

Commit

Permalink
fix: better logging of API responses (#734)
Browse files Browse the repository at this point in the history
  • Loading branch information
kanadgupta authored Jan 26, 2023
1 parent 579aaa0 commit ec81720
Show file tree
Hide file tree
Showing 11 changed files with 24 additions and 25 deletions.
2 changes: 1 addition & 1 deletion src/cmds/categories/create.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ export default class CategoriesCreateCommand extends Command {
type: categoryType,
}),
})
.then(res => handleRes(res))
.then(handleRes)
.then(res => `🌱 successfully created '${res.title}' with a type of '${res.type}' and an id of '${res.id}'`);
}

Expand Down
8 changes: 3 additions & 5 deletions src/cmds/docs/edit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ export default class DocsEditCommand extends Command {
Accept: 'application/json',
})
),
}).then(res => handleRes(res));
}).then(handleRes);

await writeFile(filename, existingDoc.body);

Expand Down Expand Up @@ -99,11 +99,9 @@ export default class DocsEditCommand extends Command {
})
),
})
.then(res => res.json())
.then(res => handleRes(res, false))
.then(async res => {
Command.debug(`response from PUT request: ${res}`);
// The reason we aren't using our handleRes() function here is
// because we need to use the `reject` function from
// We need to use the `reject` function from
// the Promise that's wrapping this function.
if (res.error) {
return reject(new APIError(res));
Expand Down
7 changes: 2 additions & 5 deletions src/cmds/openapi/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -153,9 +153,7 @@ export default class OpenAPICommand extends Command {
? `You've successfully uploaded a new ${specType} file to your ReadMe project!`
: `You've successfully updated an existing ${specType} file on your ReadMe project!`;

Command.debug(`successful ${data.status} response`);
const body = await data.json();
Command.debug(`successful response payload: ${JSON.stringify(body)}`);
const body = await handleRes(data, false);

const output = {
commandType: isUpdate ? 'update' : 'create',
Expand Down Expand Up @@ -300,8 +298,7 @@ export default class OpenAPICommand extends Command {
Command.debug(`total pages: ${totalPages}`);
Command.debug(`pagination result: ${JSON.stringify(parsedDocs)}`);

const apiSettingsBody = await apiSettings.json();
Command.debug(`api settings list response payload: ${JSON.stringify(apiSettingsBody)}`);
const apiSettingsBody = await handleRes(apiSettings);
if (!apiSettingsBody.length) return createSpec();

if (update) {
Expand Down
2 changes: 1 addition & 1 deletion src/cmds/versions/create.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ export default class CreateVersionCommand extends Command {
versionList = await fetch(`${config.get('host')}/api/v1/version`, {
method: 'get',
headers: cleanHeaders(key),
}).then(res => handleRes(res));
}).then(handleRes);
}

const versionPrompt = promptHandler.createVersionPrompt(versionList || [], {
Expand Down
2 changes: 1 addition & 1 deletion src/cmds/versions/update.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ export default class UpdateVersionCommand extends Command {
const foundVersion = await fetch(`${config.get('host')}/api/v1/version/${selectedVersion}`, {
method: 'get',
headers: cleanHeaders(key),
}).then(res => handleRes(res));
}).then(handleRes);

const promptResponse = await promptTerminal(promptHandler.createVersionPrompt([], opts, foundVersion));

Expand Down
8 changes: 6 additions & 2 deletions src/lib/fetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -136,14 +136,18 @@ export default function fetch(url: string, options: RequestInit = { headers: new
*
* If we receive non-JSON responses, we consider them errors and throw them.
*
* @param rejectOnJsonError if omitted (or set to true), the function will return
* an `APIError` if the JSON body contains an `error` property. If set to false,
* the function will return a resolved promise containing the JSON object.
*
*/
async function handleRes(res: Response) {
async function handleRes(res: Response, rejectOnJsonError = true) {
const contentType = res.headers.get('content-type');
const extension = mime.extension(contentType);
if (extension === 'json') {
const body = await res.json();
debug(`received status code ${res.status} from ${res.url} with JSON response: ${JSON.stringify(body)}`);
if (body.error) {
if (body.error && rejectOnJsonError) {
return Promise.reject(new APIError(body));
}
return body;
Expand Down
2 changes: 1 addition & 1 deletion src/lib/getCategories.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ export default async function getCategories(key: string, selectedVersion: string
Accept: 'application/json',
})
),
}).then(res => handleRes(res));
}).then(handleRes);
})
))
);
Expand Down
5 changes: 3 additions & 2 deletions src/lib/prompts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import type { Choice, PromptObject } from 'prompts';
import parse from 'parse-link-header';
import semver from 'semver';

import { handleRes } from './fetch';
import promptTerminal from './promptWrapper';

interface Spec {
Expand Down Expand Up @@ -69,7 +70,7 @@ const updateOasPrompt = (
try {
const newSpecs = await getSpecs(`${parsedDocs.prev.url}`);
const newParsedDocs = parse(newSpecs.headers.get('link'));
const newSpecList = await newSpecs.json();
const newSpecList = await handleRes(newSpecs);
// @todo: figure out how to add a stricter type here, see:
// https://github.com/readmeio/rdme/pull/570#discussion_r949715913
const { specId } = await promptTerminal(
Expand All @@ -83,7 +84,7 @@ const updateOasPrompt = (
try {
const newSpecs = await getSpecs(`${parsedDocs.next.url}`);
const newParsedDocs = parse(newSpecs.headers.get('link'));
const newSpecList = await newSpecs.json();
const newSpecList = await handleRes(newSpecs);
// @todo: figure out how to add a stricter type here, see:
// https://github.com/readmeio/rdme/pull/570#discussion_r949715913
const { specId } = await promptTerminal(
Expand Down
2 changes: 1 addition & 1 deletion src/lib/streamSpecToRegistry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ export default async function streamSpecToRegistry(spec: string) {
};

return fetch(`${config.get('host')}/api/v1/api-registry`, options)
.then(res => handleRes(res))
.then(handleRes)
.then(body => {
spinner.stop();
return body.registryUUID;
Expand Down
7 changes: 3 additions & 4 deletions src/lib/syncDocsPath.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ async function pushDoc(
...payload,
}),
})
.then(res => handleRes(res))
.then(handleRes)
// eslint-disable-next-line no-underscore-dangle
.then(res => `🌱 successfully created '${res.slug}' (ID: ${res._id}) with contents from ${filepath}`)
);
Expand Down Expand Up @@ -110,7 +110,7 @@ async function pushDoc(
})
),
})
.then(res => handleRes(res))
.then(handleRes)
.then(res => `✏️ successfully updated '${res.slug}' with contents from ${filepath}`);
}

Expand All @@ -125,8 +125,7 @@ async function pushDoc(
),
})
.then(async res => {
const body = await res.json();
debug(`GET /${type}/:slug API response for ${slug}: ${JSON.stringify(body)}`);
const body = await handleRes(res, false);
if (!res.ok) {
if (res.status !== 404) return Promise.reject(new APIError(body));
debug(`error retrieving data for ${slug}, creating doc`);
Expand Down
4 changes: 2 additions & 2 deletions src/lib/versionSelect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ export async function getProjectVersion(versionFlag: string, key: string, return
method: 'get',
headers: cleanHeaders(key),
})
.then(res => handleRes(res))
.then(handleRes)
.then((res: Version) => res.version);
}

Expand All @@ -34,7 +34,7 @@ export async function getProjectVersion(versionFlag: string, key: string, return
const versionList: Version[] = await fetch(`${config.get('host')}/api/v1/version`, {
method: 'get',
headers: cleanHeaders(key),
}).then(res => handleRes(res));
}).then(handleRes);

if (versionList.length === 1) {
return versionList[0].version;
Expand Down

0 comments on commit ec81720

Please sign in to comment.