Skip to content

Commit

Permalink
FE-6299 Implement FQL formatting for v4 queries (#559)
Browse files Browse the repository at this point in the history
* v4 FQL formating

* update tests

* no need for special formatting

* review suggestions

* more comment tweaks

---------

Co-authored-by: E. Cooper <[email protected]>
  • Loading branch information
ptpaterson and ecooper authored Jan 15, 2025
1 parent 9e8aecc commit fdc2f3d
Show file tree
Hide file tree
Showing 6 changed files with 562 additions and 486 deletions.
2 changes: 1 addition & 1 deletion src/lib/fauna-client.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,7 @@ export const formatQueryResponse = (res, { apiVersion, color, format }) => {
const faunaV10 = container.resolve("faunaClientV10");

if (apiVersion === "4") {
return faunaV4.formatQueryResponse(res, { color });
return faunaV4.formatQueryResponse(res, { format, color });
} else {
return faunaV10.formatQueryResponse(res, { format, color });
}
Expand Down
26 changes: 22 additions & 4 deletions src/lib/faunadb.mjs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
// @ts-check
import util from "node:util";
import { createContext, runInContext } from "node:vm";

import faunadb from "faunadb";
Expand Down Expand Up @@ -46,11 +47,18 @@ export const getClient = async (argv) => {
*/
export async function stringExpressionToQuery(expression) {
const faunadb = (await import("faunadb")).default;
return runInContext(expression, createContext(faunadb.query));

// The `runInContext` function from node:vm does not work with all valid FQL
// expressions, including `null` and objects. Wrapping the provided expression
// in an IIFE ensure that all expressions are supported.
const wrappedCode = `(function() { return ${expression} })()`;

return runInContext(wrappedCode, createContext(faunadb.query));
}

const validateQueryParams = ({ query, client, url, secret }) => {
if (!query) {
// `null` and other falsy values are acceptable queries
if (query === undefined) {
throw new Error("A query is required.");
} else if (!client && (!url || !secret)) {
throw new Error("A client or url and secret are required.");
Expand Down Expand Up @@ -177,9 +185,19 @@ export const faunadbToCommandError = ({ err, handler, color }) => {
*/
export const formatQueryResponse = (res, opts = {}) => {
const { color, format } = opts;

const data = res.value;
const resolvedFormat = format ?? Format.JSON;
return colorize(data, { format: resolvedFormat, color });
let resolvedOutput;
let resolvedFormat;

if (!format || format === Format.FQL) {
resolvedOutput = util.inspect(data, { showHidden: false, depth: null });
resolvedFormat = Format.FQL;
} else {
resolvedOutput = data;
resolvedFormat = Format.JSON;
}
return colorize(resolvedOutput, { format: resolvedFormat, color });
};

/**
Expand Down
Loading

0 comments on commit fdc2f3d

Please sign in to comment.