Skip to content

Commit 319cb65

Browse files
committed
feat(package/cli): add mutation-query-param-names generator
Added mutation-query-param-names.ts to generate MutationParamNames and QueryParamNames. This module creates runtime objects that store argument names for each mutation and query field which makes possible to convert between params and args.
1 parent ca1f37f commit 319cb65

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed

packages/cli/src/generate/index.ts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ import * as deps from '../deps';
2323
import { formatPrettier } from '../prettier';
2424

2525
import { generateMutationQueryTypes } from './mutation-query-types';
26+
import { generateMutationQueryParamNames } from './mutation-query-param-names';
2627

2728
const {
2829
isEnumType,
@@ -875,6 +876,8 @@ export async function generate(
875876
*/
876877
877878
${generateMutationQueryTypes(generatedSchema, scalarsEnumsHash)}
879+
880+
${generateMutationQueryParamNames(generatedSchema)}
878881
`);
879882

880883
const imports = [
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
import { type Schema } from 'gqty';
2+
3+
/**
4+
* Builds and returns TypeScript code for `MutationParamNames` and `QueryParamNames` objects,
5+
* each containing the argument names for every field that actually has arguments.
6+
*
7+
* @param generatedSchema - GQty's generated schema object (`query`, `mutation`, etc.)
8+
* @returns A string of TypeScript code with the two objects declared.
9+
*/
10+
export function generateMutationQueryParamNames(
11+
generatedSchema: Schema
12+
): string {
13+
let code = '';
14+
15+
// Handle "mutation" and "query"
16+
(['mutation', 'query'] as const).forEach((opName) => {
17+
const opFields = generatedSchema[opName];
18+
if (!opFields) return;
19+
20+
// Collect property lines, e.g. "userCreate: ['values', 'organizationId'...]"
21+
const lines: string[] = [];
22+
23+
for (const fieldName of Object.keys(opFields)) {
24+
if (fieldName === '__typename') continue;
25+
26+
const field = opFields[fieldName];
27+
if (!field.__args) continue;
28+
29+
const argNamesInOrder = Object.keys(field.__args);
30+
31+
if (argNamesInOrder.length) {
32+
const arr = argNamesInOrder.map((arg) => `"${arg}"`).join(', ');
33+
lines.push(` ${fieldName}: [${arr}]`);
34+
}
35+
}
36+
37+
if (!lines.length) return;
38+
39+
// E.g. "export const MutationParamNames = { userCreate: [...], ... };"
40+
const capitalized = opName.charAt(0).toUpperCase() + opName.slice(1);
41+
code += `export const ${capitalized}ParamNames = {\n${lines.join(',\n')}\n};\n`;
42+
});
43+
44+
return code;
45+
}

0 commit comments

Comments
 (0)