Skip to content

Commit

Permalink
wip: alt type tagged not inferring from fieldName
Browse files Browse the repository at this point in the history
  • Loading branch information
svidgen committed Jul 12, 2023
1 parent 0314257 commit 1c37267
Show file tree
Hide file tree
Showing 6 changed files with 117 additions and 32 deletions.
1 change: 1 addition & 0 deletions packages/amplify-codegen/src/commands/statements.js
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ async function generateStatements(context, forceDownloadSchema, maxDepth, withou
// default typenameIntrospection to true when not set
typenameIntrospection:
cfg.amplifyExtension.typenameIntrospection === undefined ? true : !!cfg.amplifyExtension.typenameIntrospection,
includeMetaData: true
});
if (!generatedOps) {
context.print.warning('No GraphQL statements are generated. Check if the introspection schema has GraphQL operations defined.');
Expand Down
35 changes: 26 additions & 9 deletions packages/amplify-codegen/src/utils/GraphQLStatementsFormatter.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
const prettier = require('prettier');
const {
interfaceNameFromOperation,
interfaceVariablesNameFromOperation
} = require('@aws-amplify/graphql-types-generator/lib/typescript/codeGeneration');

const CODEGEN_WARNING = 'this is an auto generated file. This will be overwritten';
const LINE_DELIMITOR = '\n';
Expand Down Expand Up @@ -52,7 +56,7 @@ class GraphQLStatementsFormatter {

formatGraphQL(statements) {
const headerBuffer = this.headerComments.map(comment => `# ${comment}`).join(LINE_DELIMITOR);
const statementsBuffer = statements ? [...statements.values()].join(LINE_DELIMITOR) : '';
const statementsBuffer = statements ? [...statements.values()].map(s => s.graphql).join(LINE_DELIMITOR) : '';
const formattedOutput = [headerBuffer, LINE_DELIMITOR, statementsBuffer].join(LINE_DELIMITOR);
return formattedOutput;
}
Expand All @@ -62,9 +66,10 @@ class GraphQLStatementsFormatter {
const headerBuffer = this.headerComments.map(comment => `// ${comment}`).join(LINE_DELIMITOR);
const formattedStatements = [];
if (statements) {
for (const [key, value] of statements) {
const typeTag = this.buildTypeTag(key);
formattedStatements.push(`export const ${key} = /* GraphQL */ \`${value}\`${typeTag}`);
console.log('STATEMENTS', { statements });
for (const [key, {graphql, operationName, operationType}] of statements) {
const typeTag = this.buildTypeTag(operationName, operationType);
formattedStatements.push(`export const ${key} = /* GraphQL */ \`${graphql}\`${typeTag}`);
}
}
const formattedOutput = [lintOverridesBuffer, headerBuffer, LINE_DELIMITOR, this.typeDefs, LINE_DELIMITOR, ...formattedStatements].join(
Expand All @@ -73,13 +78,25 @@ class GraphQLStatementsFormatter {
return formattedOutput;
}

buildTypeTag(name) {
if (!this.opTypeName) return '';
buildTypeTag(operationName, operationType) {
if (this.language !== 'typescript') return '';
if (!operationType) return '';

const titleCasedName = `${name[0].toUpperCase()}${name.slice(1)}`;
const variablesTypeName = `APITypes.${titleCasedName}${this.opTypeName}Variables`;
const resultTypeName = `APITypes.${titleCasedName}${this.opTypeName}`;
// const titleCasedName = `${name[0].toUpperCase()}${name.slice(1)}`;

const resultTypeName = `APITypes.${interfaceNameFromOperation({
operationName,
operationType,
// operationName: titleCasedName,
// operationType: this.opTypeName,
})}`;

const variablesTypeName = `APITypes.${interfaceVariablesNameFromOperation({
operationName,
operationType,
// operationName: titleCasedName,
// operationType: this.opTypeName,
})}`;

return ` as Generated${this.opTypeName}<
${variablesTypeName},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,8 @@ const { GraphQLStatementsFormatter } = require('../../src/utils');

describe('GraphQL statements Formatter', () => {
const statements = new Map();
statements.set(
'getTodo',
`

const graphql = `
query GetProject($id: ID!) {
getProject(id: $id) {
id
Expand All @@ -13,7 +12,16 @@ describe('GraphQL statements Formatter', () => {
updatedAt
}
}
`,
`;

statements.set(
'getProject',
{
graphql,
operationName: 'GetProject',
operationType: 'query',
fieldName: 'getProject'
},
);

it('Generates formatted output for JS frontend', () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ exports[`GraphQL statements Formatter Generates formatted output for Flow fronte
"// @flow
// this is an auto generated file. This will be overwritten
export const getTodo = /* GraphQL */ \`
export const getProject = /* GraphQL */ \`
query GetProject($id: ID!) {
getProject(id: $id) {
id
Expand Down Expand Up @@ -49,7 +49,7 @@ exports[`GraphQL statements Formatter Generates formatted output for JS frontend
"/* eslint-disable */
// this is an auto generated file. This will be overwritten
export const getTodo = /* GraphQL */ \`
export const getProject = /* GraphQL */ \`
query GetProject($id: ID!) {
getProject(id: $id) {
id
Expand All @@ -73,7 +73,7 @@ type GeneratedQuery<InputType, OutputType> = string & {
__generatedQueryOutput: OutputType;
};
export const getTodo = /* GraphQL */ \`
export const getProject = /* GraphQL */ \`
query GetProject($id: ID!) {
getProject(id: $id) {
id
Expand All @@ -82,6 +82,9 @@ export const getTodo = /* GraphQL */ \`
updatedAt
}
}
\` as GeneratedQuery<APITypes.GetTodoQueryVariables, APITypes.GetTodoQuery>;
\` as GeneratedQuery<
APITypes.GetProjectQueryVariables,
APITypes.GetProjectQuery
>;
"
`;
80 changes: 66 additions & 14 deletions packages/graphql-docs-generator/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,15 @@ import { buildSchema } from './generator/utils/loading';
import { getTemplatePartials, getOperationPartial, getExternalFragmentPartial } from './generator/utils/templates';
export { buildSchema } from './generator/utils/loading';

export function generateGraphQLDocuments(
export function generateGraphQLDocuments<INCLUDE_META extends boolean>(
schema: string,
options: { maxDepth?: number; useExternalFragmentForS3Object?: boolean; typenameIntrospection?: boolean },
): GeneratedOperations {
options: {
maxDepth?: number;
useExternalFragmentForS3Object?: boolean;
typenameIntrospection?: boolean;
includeMetaData?: INCLUDE_META;
},
): GeneratedOperations<MapValueType<INCLUDE_META>> {
const opts = {
maxDepth: 2,
useExternalFragmentForS3Object: true,
Expand All @@ -25,16 +30,17 @@ export function generateGraphQLDocuments(
registerHelpers();

const allOperations = {
queries: new Map<string, string>(),
mutations: new Map<string, string>(),
subscriptions: new Map<string, string>(),
queries: new Map<string, MapValueType<INCLUDE_META>>(),
mutations: new Map<string, MapValueType<INCLUDE_META>>(),
subscriptions: new Map<string, MapValueType<INCLUDE_META>>(),
fragments: new Map<string, string>(),
};

['queries', 'mutations', 'subscriptions'].forEach(op => {
const ops = gqlOperations[op];
console.log({ ops });
if (ops.length) {
const renderedOperations = renderOperations(gqlOperations[op]);
const renderedOperations = renderOperations(gqlOperations[op], options.includeMetaData);
allOperations[op] = renderedOperations;
}
});
Expand All @@ -47,26 +53,72 @@ export function generateGraphQLDocuments(
return allOperations;
}

type GeneratedOperations = {
queries: Map<string, string>;
mutations: Map<string, string>;
subscriptions: Map<string, string>;
type GraphQLWithMeta = {
/**
* The generated graphql string.
*/
graphql: string;

/**
* E.g., `GetMyModel` or `ListMyModels`.
*
* This is used for generating type names.
*
* `undefined` for fragments.
*/
operationName: string | undefined;

/**
* `undefined` for fragments.
*/
operationType: "query" | "mutation" | "subscription" | undefined;

/**
* E.g., `getMyModel` or `listMyModels`.
*
* It's the name of the operation that lives under Queries, Mutations, or Subscriptions
* in the schema and is generally used as the key + variable name referring to the query.
*/
fieldName: string;
}

type GeneratedOperations<T> = {
queries: Map<string, T>;
mutations: Map<string, T>;
subscriptions: Map<string, T>;
fragments: Map<string, string>;
};

function renderOperations(operations: Array<GQLTemplateOp>): Map<string, string> {
const renderedOperations = new Map<string, string>();
type MapValueType<INCLUDE_META extends boolean> = INCLUDE_META extends true ? GraphQLWithMeta : string;

function renderOperations<
INCLUDE_META extends boolean,
>(operations: Array<GQLTemplateOp>, includeMetaData: INCLUDE_META): Map<string, MapValueType<INCLUDE_META>> {
const renderedOperations = new Map<string, MapValueType<INCLUDE_META>>();
if (operations?.length) {
operations.forEach(op => {
const name = op.fieldName || op.name;
const gql = renderOperation(op);
renderedOperations.set(name, gql);
if (includeMetaData) {
renderedOperations.set(name, {
graphql: gql,
operationName: op.name,
operationType: op.type,
fieldName: op.fieldName
} as any);
} else {
renderedOperations.set(name, gql as any);
}
});
}

return renderedOperations;
}

function isMetaIncluded(includeMetaData: boolean, operationsMap: any): operationsMap is GraphQLWithMeta {
return includeMetaData === true;
}

function renderOperation(operation: GQLTemplateOp): string {
// TODO: cleanup
// console.log('rendering operation', operation);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -165,14 +165,18 @@ export function interfaceNameFromOperation({ operationName, operationType }: { o
}
}

export function interfaceVariablesNameFromOperation({ operationName, operationType }: { operationName: string; operationType: string }) {
return `${interfaceNameFromOperation({ operationName, operationType })}Variables`;
}

export function interfaceVariablesDeclarationForOperation(
generator: CodeGenerator,
{ operationName, operationType, variables }: LegacyOperation,
) {
if (!variables || variables.length < 1) {
return;
}
const interfaceName = `${interfaceNameFromOperation({ operationName, operationType })}Variables`;
const interfaceName = interfaceVariablesNameFromOperation({operationName, operationType});

interfaceDeclaration(
generator,
Expand Down

0 comments on commit 1c37267

Please sign in to comment.