Skip to content

Commit 616946e

Browse files
author
E. Cooper
committed
Add prototype of a format factory for account API crud commands
1 parent 0ce3015 commit 616946e

File tree

23 files changed

+196
-152
lines changed

23 files changed

+196
-152
lines changed

src/cli.mjs

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -184,12 +184,6 @@ function buildYargs(argvInput) {
184184
description: "Profile from the CLI config file to use.",
185185
group: "Config:",
186186
},
187-
json: {
188-
type: "boolean",
189-
description: "Output the results as JSON.",
190-
default: false,
191-
group: "Output:",
192-
},
193187
quiet: {
194188
type: "boolean",
195189
description:

src/commands/database/create.mjs

Lines changed: 28 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,25 @@ import { container } from "../../config/container.mjs";
55
import { CommandError } from "../../lib/errors.mjs";
66
import { faunaToCommandError } from "../../lib/fauna.mjs";
77
import { getSecret, retryInvalidCredsOnce } from "../../lib/fauna-client.mjs";
8-
import { colorize, Format } from "../../lib/formatting/colorize.mjs";
8+
import { createFormatter } from "../../lib/formatting/formatter.mjs";
99
import { validateDatabaseOrSecret } from "../../lib/middleware.mjs";
10+
import { FORMATTABLE_OPTIONS } from "../../lib/options.mjs";
11+
12+
const formatter = createFormatter({
13+
header: "fauna database create",
14+
columns: [
15+
"global_id",
16+
"name",
17+
"coll",
18+
"ts",
19+
"protected",
20+
"typechecked",
21+
"priority",
22+
],
23+
short: {
24+
formatter: ({ global_id, name }) => `${name} (${global_id})`, // eslint-disable-line camelcase
25+
},
26+
});
1027

1128
async function runCreateQuery(secret, argv) {
1229
const { fql } = container.resolve("fauna");
@@ -29,20 +46,18 @@ async function createDatabase(argv) {
2946
const logger = container.resolve("logger");
3047

3148
try {
32-
await retryInvalidCredsOnce(secret, async (secret) =>
49+
const { data } = await retryInvalidCredsOnce(secret, async (secret) =>
3350
runCreateQuery(secret, argv),
3451
);
52+
const dataWithAllFields = {
53+
protected: undefined,
54+
typechecked: undefined,
55+
priority: undefined,
56+
...data,
57+
};
3558

36-
logger.stderr(`Database successfully created.`);
37-
38-
const { color, json } = argv;
39-
if (json) {
40-
logger.stdout(
41-
colorize({ name: argv.name }, { color, format: Format.JSON }),
42-
);
43-
} else {
44-
logger.stdout(argv.name);
45-
}
59+
const { color, format } = argv;
60+
logger.stdout(formatter({ data: dataWithAllFields, color, format }));
4661
} catch (e) {
4762
faunaToCommandError({
4863
err: e,
@@ -76,6 +91,7 @@ async function createDatabase(argv) {
7691

7792
function buildCreateCommand(yargs) {
7893
return yargs
94+
.options(FORMATTABLE_OPTIONS)
7995
.options({
8096
name: {
8197
type: "string",

src/commands/database/list.mjs

Lines changed: 24 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -3,21 +3,30 @@ import chalk from "chalk";
33

44
import { container } from "../../config/container.mjs";
55
import { faunaToCommandError } from "../../lib/fauna.mjs";
6-
import { colorize, Format } from "../../lib/formatting/colorize.mjs";
6+
import { createFormatter } from "../../lib/formatting/formatter.mjs";
7+
import { FORMATTABLE_OPTIONS } from "../../lib/options.mjs";
8+
9+
const formatter = createFormatter({
10+
header: "fauna database list",
11+
columns: ["name", "path"],
12+
short: {
13+
formatter: ({ path, name }) => `${path ?? name}`,
14+
},
15+
});
716

817
async function listDatabasesWithAccountAPI(argv) {
9-
const { pageSize, database } = argv;
18+
const { maxSize, database } = argv;
1019
const { listDatabases } = container.resolve("accountAPI");
1120
const response = await listDatabases({
12-
pageSize,
21+
pageSize: maxSize,
1322
path: database,
1423
});
1524

1625
return response.results.map(({ path, name }) => ({ path, name }));
1726
}
1827

1928
async function listDatabasesWithSecret(argv) {
20-
const { url, secret, pageSize } = argv;
29+
const { url, secret, maxSize, color } = argv;
2130
const { runQueryFromString } = container.resolve("faunaClientV10");
2231

2332
try {
@@ -26,11 +35,11 @@ async function listDatabasesWithSecret(argv) {
2635
secret,
2736
// This gives us back an array of database names. If we want to
2837
// provide the after token at some point this query will need to be updated.
29-
expression: `Database.all().paginate(${pageSize}).data { name }`,
38+
expression: `Database.all().paginate(${maxSize}).data { name }`,
3039
});
3140
return res.data;
3241
} catch (e) {
33-
return faunaToCommandError({ err: e, color: argv.color });
42+
return faunaToCommandError({ err: e, color });
3443
}
3544
}
3645

@@ -54,22 +63,19 @@ async function doListDatabases(argv) {
5463
);
5564
}
5665

57-
if (argv.json) {
58-
logger.stdout(colorize(res, { format: Format.JSON, color: argv.color }));
59-
} else {
60-
res.forEach(({ path, name }) => {
61-
logger.stdout(path ?? name);
62-
});
63-
}
66+
const { format, color } = argv;
67+
logger.stdout(formatter({ data: res, format, color }));
6468
}
6569

6670
function buildListCommand(yargs) {
6771
return yargs
72+
.options(FORMATTABLE_OPTIONS)
6873
.options({
69-
"page-size": {
74+
"max-size": {
75+
alias: "max",
7076
type: "number",
7177
description: "Maximum number of databases to return.",
72-
default: 1000,
78+
default: 10,
7379
},
7480
})
7581
.example([
@@ -83,12 +89,12 @@ function buildListCommand(yargs) {
8389
"List all child databases directly under a database scoped to a secret.",
8490
],
8591
[
86-
"$0 database list --json",
92+
"$0 database list -f json",
8793
"List all top-level databases and output as JSON.",
8894
],
8995
[
90-
"$0 database list --page-size 10",
91-
"List the first 10 top-level databases.",
96+
"$0 database list --max-size 100",
97+
"List the first 100 top-level databases.",
9298
],
9399
]);
94100
}

src/commands/local.mjs

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import { pushSchema } from "../commands/schema/push.mjs";
55
import { container } from "../config/container.mjs";
66
import { ensureContainerRunning } from "../lib/docker-containers.mjs";
77
import { CommandError, ValidationError } from "../lib/errors.mjs";
8-
import { colorize, Format } from "../lib/formatting/colorize.mjs";
8+
import { colorize, Language } from "../lib/formatting/colorize.mjs";
99

1010
/**
1111
* Starts the local Fauna container
@@ -40,7 +40,7 @@ async function createDatabaseSchema(argv) {
4040
colorize(
4141
`[CreateDatabaseSchema] Creating schema for database '${argv.database}' from directory '${argv.directory}'...`,
4242
{
43-
format: Format.LOG,
43+
language: Language.LOG,
4444
color: argv.color,
4545
},
4646
),
@@ -52,7 +52,7 @@ async function createDatabaseSchema(argv) {
5252
colorize(
5353
`[CreateDatabaseSchema] Schema for database '${argv.database}' created from directory '${argv.directory}'.`,
5454
{
55-
format: Format.LOG,
55+
language: Language.LOG,
5656
color: argv.color,
5757
},
5858
),
@@ -66,7 +66,7 @@ async function createDatabase(argv) {
6666
const color = argv.color;
6767
logger.stderr(
6868
colorize(`[CreateDatabase] Creating database '${argv.database}'...`, {
69-
format: Format.LOG,
69+
language: Language.LOG,
7070
color,
7171
}),
7272
);
@@ -105,17 +105,17 @@ async function createDatabase(argv) {
105105
});
106106
logger.stderr(
107107
colorize(`[CreateDatabase] Database '${argv.database}' created.`, {
108-
format: Format.LOG,
108+
language: Language.LOG,
109109
color,
110110
}),
111111
);
112-
logger.stderr(colorize(db.data, { format: Format.FQL, color }));
112+
logger.stderr(colorize(db.data, { language: Language.FQL, color }));
113113
} catch (e) {
114114
if (e instanceof AbortError) {
115115
throw new CommandError(
116116
`${chalk.red(`[CreateDatabase] Database '${argv.database}' already exists but with differrent properties than requested:\n`)}
117117
-----------------
118-
${colorize(e.abort, { format: Format.FQL, color })}
118+
${colorize(e.abort, { language: Language.FQL, color })}
119119
-----------------
120120
${chalk.red("Please use choose a different name using --name or align the --typechecked, --priority, and --protected with what is currently present.")}`,
121121
);

src/commands/query.mjs

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ import {
2121
DATABASE_PATH_OPTIONS,
2222
QUERY_OPTIONS,
2323
} from "../lib/options.mjs";
24-
import { isTTY, resolveFormat } from "../lib/utils.mjs";
24+
import { isTTY } from "../lib/utils.mjs";
2525

2626
function validate(argv) {
2727
const { existsSync, accessSync, constants } = container.resolve("fs");
@@ -96,22 +96,20 @@ async function queryCommand(argv) {
9696
performanceHints,
9797
color,
9898
include,
99+
format,
99100
} = argv;
100101

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

104-
// Using --json takes precedence over --format
105-
const outputFormat = resolveFormat(argv);
106-
107105
const results = await container.resolve("runQueryFromString")(expression, {
108106
apiVersion,
109107
secret,
110108
url,
111109
timeout,
112110
typecheck,
113111
performanceHints,
114-
format: outputFormat,
112+
format,
115113
color: useColor,
116114
});
117115

@@ -130,7 +128,7 @@ async function queryCommand(argv) {
130128

131129
const output = formatQueryResponse(results, {
132130
apiVersion,
133-
format: outputFormat,
131+
format,
134132
color: useColor,
135133
});
136134

src/commands/shell.mjs

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,6 @@ import {
1616
QUERY_INFO_CHOICES,
1717
QUERY_OPTIONS,
1818
} from "../lib/options.mjs";
19-
import { resolveFormat } from "../lib/utils.mjs";
2019

2120
async function shellCommand(argv) {
2221
const { query: v4Query } = container.resolve("faunadb");
@@ -159,13 +158,10 @@ async function buildCustomEval(argv) {
159158
if (cmd.trim() === "") return cb();
160159

161160
// These are options used for querying and formatting the response
162-
const { apiVersion, color } = argv;
161+
const { apiVersion, color, format } = argv;
163162
const include = getArgvOrCtx("include", argv, ctx);
164163
const performanceHints = getArgvOrCtx("performanceHints", argv, ctx);
165164

166-
// Using --json output takes precedence over --format
167-
const outputFormat = resolveFormat({ ...argv });
168-
169165
if (apiVersion === "4") {
170166
try {
171167
esprima.parseScript(cmd);
@@ -177,7 +173,7 @@ async function buildCustomEval(argv) {
177173
let res;
178174
try {
179175
const secret = await getSecret();
180-
const { color, timeout, typecheck, url } = argv;
176+
const { color, timeout, typecheck, url, format } = argv;
181177

182178
res = await runQueryFromString(cmd, {
183179
apiVersion,
@@ -186,7 +182,7 @@ async function buildCustomEval(argv) {
186182
timeout,
187183
typecheck,
188184
performanceHints,
189-
format: outputFormat,
185+
format,
190186
});
191187

192188
// If any query info should be displayed, print to stderr.
@@ -209,7 +205,7 @@ async function buildCustomEval(argv) {
209205
const output = formatQueryResponse(res, {
210206
apiVersion,
211207
color,
212-
format: outputFormat,
208+
format,
213209
});
214210

215211
logger.stdout(output);

src/lib/docker-containers.mjs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { container } from "../config/container.mjs";
22
import { CommandError, SUPPORT_MESSAGE } from "./errors.mjs";
3-
import { colorize, Format } from "./formatting/colorize.mjs";
3+
import { colorize, Language } from "./formatting/colorize.mjs";
44

55
const IMAGE_NAME = "fauna/faunadb:latest";
66
let color = false;
@@ -413,5 +413,5 @@ async function waitForHealthCheck({
413413
*/
414414
function stderr(log) {
415415
const logger = container.resolve("logger");
416-
logger.stderr(colorize(log, { format: Format.LOG, color }));
416+
logger.stderr(colorize(log, { language: Language.LOG, color }));
417417
}

src/lib/fauna-client.mjs

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ import { container } from "../config/container.mjs";
66
import { isUnknownError } from "./errors.mjs";
77
import { faunaToCommandError } from "./fauna.mjs";
88
import { faunadbToCommandError } from "./faunadb.mjs";
9-
import { colorize, Format } from "./formatting/colorize.mjs";
9+
import { colorize, Language } from "./formatting/colorize.mjs";
1010

1111
/**
1212
* Regex to match the FQL diagnostic line.
@@ -73,7 +73,7 @@ export const runQueryFromString = (expression, argv) => {
7373
} else {
7474
const { secret, url, timeout, format, performanceHints, ...rest } = argv;
7575
let apiFormat = "decorated";
76-
if (format === Format.JSON) {
76+
if (format === Language.JSON) {
7777
apiFormat = "simple";
7878
}
7979

@@ -177,7 +177,7 @@ export const formatQuerySummary = (summary) => {
177177
if (!line.match(FQL_DIAGNOSTIC_REGEX)) {
178178
return line;
179179
}
180-
return colorize(line, { format: Format.FQL });
180+
return colorize(line, { language: Language.FQL });
181181
});
182182
return lines.join("\n");
183183
} catch (err) {
@@ -228,7 +228,7 @@ export const formatQueryInfo = (response, { apiVersion, color, include }) => {
228228
const metricsResponse = response;
229229
const colorized = colorize(
230230
{ metrics: metricsResponse.metrics },
231-
{ color, format: Format.YAML },
231+
{ color, language: Language.YAML },
232232
);
233233

234234
return `${colorized}\n`;
@@ -242,14 +242,14 @@ export const formatQueryInfo = (response, { apiVersion, color, include }) => {
242242
// strip the ansi when we're checking if the line is a diagnostic line.
243243
const colorized = colorize(queryInfoToDisplay, {
244244
color,
245-
format: Format.YAML,
245+
language: Language.YAML,
246246
})
247247
.split("\n")
248248
.map((line) => {
249249
if (!stripAnsi(line).match(FQL_DIAGNOSTIC_REGEX)) {
250250
return line;
251251
}
252-
return colorize(line, { format: Format.FQL });
252+
return colorize(line, { language: Language.FQL });
253253
})
254254
.join("\n");
255255

0 commit comments

Comments
 (0)