Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Delete --raw flag #522

Merged
merged 2 commits into from
Dec 13, 2024
Merged
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
19 changes: 3 additions & 16 deletions src/commands/query.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -88,13 +88,12 @@ async function queryCommand(argv) {
performanceHints,
summary,
color,
raw,
} = argv;

// If we're writing to a file, don't colorize the output regardless of the user's preference
const useColor = argv.output || !isTTY() ? false : color;

// Using --json or --raw takes precedence over --format
// Using --json takes precedence over --format
const outputFormat = resolveFormat(argv);

const results = await container.resolve("runQueryFromString")(expression, {
Expand All @@ -105,7 +104,6 @@ async function queryCommand(argv) {
typecheck,
performanceHints,
format: outputFormat,
raw,
color: useColor,
});

Expand All @@ -121,7 +119,6 @@ async function queryCommand(argv) {
const output = formatQueryResponse(results, {
apiVersion,
format: outputFormat,
raw,
color: useColor,
});

Expand All @@ -137,8 +134,8 @@ async function queryCommand(argv) {
throw err;
}

const { apiVersion, raw, color } = argv;
throw new CommandError(formatError(err, { apiVersion, raw, color }), {
const { apiVersion, color } = argv;
throw new CommandError(formatError(err, { apiVersion, color }), {
cause: err,
});
}
Expand All @@ -163,12 +160,6 @@ function buildQueryCommand(yargs) {
description:
"Path to a file where query results are written. Defaults to stdout.",
},
raw: {
type: "boolean",
description:
"Output the raw JSON query response, including summary and query stats.",
default: false,
},
})
.example([
[
Expand All @@ -195,10 +186,6 @@ function buildQueryCommand(yargs) {
"$0 query -i /path/to/queries.fql --output /tmp/result.json --database us/example",
"Run the query and write the results to a file.",
],
[
"$0 query -i /path/to/queries.fql --raw --output /tmp/result.json --database us/example",
"Run the query and write the full API response to a file.",
],
]);
}

Expand Down
19 changes: 3 additions & 16 deletions src/commands/shell.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@
prompt: `${argv.database || ""}> `,
ignoreUndefined: true,
preview: argv.apiVersion !== "10",
// TODO: integrate with fql-analyzer for completions

Check warning on line 41 in src/commands/shell.mjs

View workflow job for this annotation

GitHub Actions / lint

Unexpected 'todo' comment: 'TODO: integrate with fql-analyzer for...'
completer: argv.apiVersion === "10" ? () => [] : undefined,
output: container.resolve("stdoutStream"),
input: container.resolve("stdinStream"),
Expand Down Expand Up @@ -102,17 +102,6 @@
shell.prompt();
},
},
{
cmd: "toggleRawResponses",
help: "Enable or disable additional output. Disabled by default. If enabled, outputs the raw JSON query response, including summary and query stats.",
action: () => {
shell.context.raw = !shell.context.raw;
logger.stderr(
`Additional information in shell: ${shell.context.raw ? "on" : "off"}`,
);
shell.prompt();
},
},
{
cmd: "togglePerformanceHints",
help: "Enable or disable performance hints. Disabled by default. If enabled, outputs performance hints for the most recent query.",
Expand Down Expand Up @@ -161,12 +150,11 @@

// These are options used for querying and formatting the response
const { apiVersion, color } = argv;
const raw = getArgvOrCtx("raw", argv, ctx);
const performanceHints = getArgvOrCtx("performanceHints", argv, ctx);
const summary = getArgvOrCtx("summary", argv, ctx);

// Using --raw or --json output takes precedence over --format
const outputFormat = resolveFormat({ ...argv, raw });
// Using --json output takes precedence over --format
const outputFormat = resolveFormat({ ...argv });

if (apiVersion === "4") {
try {
Expand Down Expand Up @@ -198,13 +186,12 @@
}
}
} catch (err) {
logger.stderr(formatError(err, { apiVersion, raw, color }));
logger.stderr(formatError(err, { apiVersion, color }));
return cb(null);
}

const output = formatQueryResponse(res, {
apiVersion,
raw,
color,
format: outputFormat,
});
Expand Down
8 changes: 0 additions & 8 deletions src/lib/command-helpers.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -153,14 +153,6 @@ export const resolveFormat = (argv) => {
return Format.JSON;
}

if (argv.raw) {
logger.debug(
"--raw has taken precedence over other formatting options, using JSON output",
"argv",
);
return Format.JSON;
}

return argv.format;
};

Expand Down
18 changes: 6 additions & 12 deletions src/lib/fauna-client.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -93,18 +93,17 @@ export const runQueryFromString = (expression, argv) => {
* @param {object} err - The error to format
* @param {object} opts
* @param {string} opts.apiVersion - The API version
* @param {boolean} opts.raw - Whether to include full response bodies
* @param {boolean} opts.color - Whether to colorize the error
* @returns {string}
*/
export const formatError = (err, { apiVersion, raw, color }) => {
export const formatError = (err, { apiVersion, color }) => {
const faunaV4 = container.resolve("faunaClientV4");
const faunaV10 = container.resolve("faunaClientV10");

if (apiVersion === "4") {
return faunaV4.formatError(err, { raw, color });
return faunaV4.formatError(err, { color });
} else {
return faunaV10.formatError(err, { raw, color });
return faunaV10.formatError(err, { color });
}
};

Expand All @@ -125,7 +124,6 @@ export const isQueryable = async (argv) => {
throw new ValidationError(
formatError(err, {
apiVersion: argv.apiVersion,
raw: false,
color: false,
}),
{
Expand All @@ -143,21 +141,17 @@ export const isQueryable = async (argv) => {
* @param {object} opts
* @param {string} opts.apiVersion - The API version
* @param {string} opts.format - The data format
* @param {boolean} opts.raw - Whether to include full response bodies
* @param {boolean} opts.color - Whether to colorize the response
* @returns {string}
*/
export const formatQueryResponse = (
res,
{ apiVersion, raw, color, format },
) => {
export const formatQueryResponse = (res, { apiVersion, color, format }) => {
const faunaV4 = container.resolve("faunaClientV4");
const faunaV10 = container.resolve("faunaClientV10");

if (apiVersion === "4") {
return faunaV4.formatQueryResponse(res, { raw, color });
return faunaV4.formatQueryResponse(res, { color });
} else {
return faunaV10.formatQueryResponse(res, { raw, format, color });
return faunaV10.formatQueryResponse(res, { format, color });
}
};

Expand Down
17 changes: 4 additions & 13 deletions src/lib/fauna.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -125,25 +125,18 @@ export const runQueryFromString = async ({
*
* @param {any} err - An error to format
* @param {object} [opts]
* @param {boolean} [opts.raw] - Whether to include full response bodies
* @param {boolean} [opts.color] - Whether to colorize the error
* @returns {string} The formatted error message
*/
export const formatError = (err, opts = {}) => {
const { raw, color } = opts;

// eslint-disable-next-line no-unused-vars
export const formatError = (err, _opts = {}) => {
// If the error has a queryInfo object with a summary property, we can format it.
// Doing this check allows this code to avoid a fauna direct dependency.
if (
err &&
typeof err.queryInfo === "object" &&
typeof err.queryInfo.summary === "string"
) {
// If you want full response, use util.inspect to get the full error object.
if (raw) {
return colorize(err, { color, format: Format.JSON });
}

// Otherwise, return the summary and fall back to the message.
return `${chalk.red("The query failed with the following error:")}\n\n${formatQuerySummary(err.queryInfo?.summary) ?? err.message}`;
} else {
Expand All @@ -159,16 +152,14 @@ export const formatError = (err, opts = {}) => {
* Formats a V10 Fauna query response.
* @par [ am {import("fauna").QuerySuccess<any>} res
* @param {object} [opts]
* @param {boolean} [opts.raw] - Whether to include full response bodies
* @param {string} [opts.format] - The format to use
* @param {boolean} [opts.color] - Whether to colorize the response
* @returns {string} The formatted response
*/
export const formatQueryResponse = (res, opts = {}) => {
const { raw, format = Format.JSON, color } = opts;
const { format = Format.JSON, color } = opts;

// If raw is set, return the full response object.
const data = raw ? res : res.data;
const data = res.data;
return colorize(data, { format, color });
};

Expand Down
15 changes: 4 additions & 11 deletions src/lib/faunadb.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -85,12 +85,11 @@ export const runQuery = async ({
* Formats a V4 Fauna error for display.
* @param {any} err - An error to format
* @param {object} [opts]
* @param {boolean} [opts.raw] - Whether to include full response bodies
* @param {boolean} [opts.color] - Whether to colorize the error
* @returns {string} The formatted error message
*/
export const formatError = (err, opts = {}) => {
const { raw, color } = opts;
const { color } = opts;

// By doing this we can avoid requiring a faunadb direct dependency
if (
Expand All @@ -99,11 +98,6 @@ export const formatError = (err, opts = {}) => {
typeof err.requestResult.responseContent === "object" &&
Array.isArray(err.requestResult.responseContent.errors)
) {
// If raw is on, return the full error.
if (raw) {
return colorize(err, { color, format: Format.JSON });
}

const errorPrefix = "The query failed with the following error:\n\n";
const { errors } = err.requestResult.responseContent;
if (!errors) {
Expand Down Expand Up @@ -135,16 +129,15 @@ export const formatError = (err, opts = {}) => {
* Formats a V4 Fauna query response.
* @param {any} res - The query response to format
* @param {object} [opts]
* @param {boolean} [opts.raw] - Whether to include full response bodies
* @param {boolean} [opts.json] - Whether to return the response as a JSON string
* @param {boolean} [opts.color] - Whether to colorize the response
* @param {string} [opts.format] - The format to use for the response
* @returns {string} The formatted response
*/
export const formatQueryResponse = (res, opts = {}) => {
const { raw, color, format } = opts;
const data = raw ? res : res.value;
const resolvedFormat = raw ? Format.JSON : (format ?? Format.JSON);
const { color, format } = opts;
const data = res.value;
const resolvedFormat = format ?? Format.JSON;
return colorize(data, { format: resolvedFormat, color });
};

Expand Down
82 changes: 0 additions & 82 deletions test/query.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -273,27 +273,6 @@ describe("query", function () {
expect(logger.stderr).to.not.be.called;
});

it("can output additional response fields via --raw", async function () {
const testData = {
name: "test",
coll: "Database",
ts: 'Time("2024-07-16T19:16:15.980Z")',
global_id: "asd7zi8pharfn",
};
const testResponse = createV10QuerySuccess(testData);
runQueryFromString.resolves(testResponse);

await run(
`query "Database.all()" --raw --secret=foo --format json`,
container,
);

expect(logger.stdout).to.have.been.calledWith(
colorize(testResponse, { format: "json", color: true }),
);
expect(logger.stderr).to.not.be.called;
});

it("can output an error message", async function () {
const testSummary = createV10QueryFailure("test query");
runQueryFromString.rejects(new ServiceError(testSummary));
Expand All @@ -306,19 +285,6 @@ describe("query", function () {
expect(logger.stderr).to.have.been.calledWith(sinon.match(/test query/));
});

it("can output the full error object when --raw is used", async function () {
const failure = createV10QueryFailure("test query");
const error = new ServiceError(failure);
runQueryFromString.rejects(error);

try {
await run(`query "Database.all()" --raw --secret=foo`, container);
} catch (e) {}

expect(logger.stdout).to.not.be.called;
expect(logger.stderr).to.have.been.calledWith(sinon.match(/queryInfo/));
});

it("can set the typecheck option to true", async function () {
await run(`query "Database.all()" --typecheck --secret=foo`, container);
expect(runQueryFromString).to.have.been.calledWith(
Expand Down Expand Up @@ -424,31 +390,6 @@ describe("query", function () {
expect(logger.stderr).to.not.be.called;
});

it("can output additional response fields via --raw", async function () {
const testData = {
"@ref": {
id: "test",
collection: {
"@ref": {
id: "collections",
},
},
},
};
const testResponse = createV4QuerySuccess(testData);
runQueryFromString.resolves(testResponse);

await run(
`query "Collection('test')" --raw --apiVersion 4 --secret=foo`,
container,
);

expect(logger.stdout).to.have.been.calledWith(
colorize(testResponse, { format: "json", color: true }),
);
expect(logger.stderr).to.not.be.called;
});

it("can output an error message", async function () {
const testError = createV4QueryFailure({
position: ["paginate", "collections"],
Expand All @@ -473,28 +414,5 @@ describe("query", function () {
),
);
});

it("can output the full error object when --raw is used", async function () {
const testError = createV4QueryFailure({
position: ["paginate", "collections"],
code: "invalid argument",
description: "Database Ref or Null expected, String provided.",
});

// @ts-ignore
runQueryFromString.rejects(testError);

try {
await run(
`query "Paginate(Collection('x'))" --apiVersion 4 --raw --secret=foo`,
container,
);
} catch (e) {}

expect(logger.stdout).to.not.be.called;
expect(logger.stderr).to.have.been.calledWith(
sinon.match(/requestResult/),
);
});
});
});
Loading