Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 18 additions & 17 deletions src/commands/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,19 @@ function formatEndpointLine(ep: Endpoint): string {

const LIST_ENDPOINTS_HINT = `Run ${chalk.cyan('apify api --list-endpoints')} to see all available Apify API endpoints.`;

function printResponseBody(responseText: string) {
if (!responseText) {
return;
}

try {
const parsed = JSON.parse(responseText);
simpleLog({ message: JSON.stringify(parsed, null, 2), stdout: true });
} catch {
simpleLog({ message: responseText, stdout: true });
}
}

function printSuggestions(suggestions: Endpoint[]) {
if (suggestions.length > 0) {
simpleLog({ message: `\nDid you mean:`, stdout: false });
Expand Down Expand Up @@ -361,30 +374,18 @@ export class ApiCommand extends ApifyCommand<typeof ApiCommand> {
// pipelines like `apify api ... | jq` still receive the payload on failure.
error({ message: `${response.status} ${response.statusText}` });

if (responseText) {
try {
const parsed = JSON.parse(responseText);
simpleLog({ message: JSON.stringify(parsed, null, 2), stdout: true });
} catch {
simpleLog({ message: responseText, stdout: true });
}
}

// The endpoint hints come first so the API's own error, which usually says what is actually
// wrong (e.g. an unknown record rather than an unknown endpoint), ends the output.
if (response.status === 404) {
await this.print404Suggestions(endpoint);
}

printResponseBody(responseText);

return;
}

if (responseText) {
try {
const parsed = JSON.parse(responseText);
simpleLog({ message: JSON.stringify(parsed, null, 2), stdout: true });
} catch {
simpleLog({ message: responseText, stdout: true });
}
}
printResponseBody(responseText);
}

private async getEndpoints(): Promise<Endpoint[]> {
Expand Down
2 changes: 2 additions & 0 deletions test/local/commands/api-suggestions.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,8 @@ describe('apify api 404 suggestions', () => {
expect(combined).toMatch(/404/);
expect(combined).toMatch(/did you mean/i);
expect(combined).toMatch(/--list-endpoints/);
// The API's own error body is still printed, after the hint and on stdout.
expect(logMessages.log.join('\n')).toContain('"message": "Not found"');
} finally {
fetchSpy.mockRestore();
}
Expand Down
Loading