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

feat: handle parent relationship without belongsTo for GraphQL #1055

Merged
merged 4 commits into from
Aug 1, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
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

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -1074,6 +1074,18 @@ describe('amplify form renderer tests', () => {
expect(componentText).toMatchSnapshot();
expect(declaration).toMatchSnapshot();
});

it('should treat relationship as bidirectional without belongsTo', () => {
const { componentText, declaration } = generateWithAmplifyFormRenderer(
'forms/relationships/update-comment-no-belongsTo',
'datastore/relationships/has-many-comment-no-belongsTo',
{ ...defaultCLIRenderConfig, ...rendererConfigWithGraphQL },
{ isNonModelSupported: true, isRelationshipSupported: true },
);

expect(componentText).toMatchSnapshot();
expect(declaration).toMatchSnapshot();
});
});

describe('NoApi form tests', () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -744,13 +744,13 @@ export const buildUpdateDatastoreQuery = (
NodeFlags.Const,
),
),
// Add logic to pull related relationship models off record
...relatedModelStatements,
factory.createExpressionStatement(
factory.createCallExpression(getSetNameIdentifier(`${lowerCaseDataTypeName}Record`), undefined, [
factory.createIdentifier('record'),
]),
),
// Add logic to pull related relationship models off record
...relatedModelStatements,
],
true,
),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1287,6 +1287,78 @@ export const buildGetRelationshipModels = (
);
return [lazyLoadLinkedDataStatement, setLinkedDataStateStatement];
}

if (dataApi === 'GraphQL' && fieldConfigMetaData.relationship && !isModelDataType(fieldConfigMetaData)) {
const relatedModelName = lowerCaseFirst(fieldConfigMetaData.relationship.relatedModelName);
const queryCall = wrapInParenthesizedExpression(
getGraphqlCallExpression(ActionType.GET, fieldConfigMetaData.relationship.relatedModelName, importCollection, {
inputs: [
factory.createPropertyAssignment(
factory.createIdentifier('id'),
factory.createIdentifier(`${fieldName}Record`),
),
],
}),
['data', getGraphqlQueryForModel(ActionType.GET, fieldConfigMetaData.relationship.relatedModelName)],
);

return [
factory.createVariableStatement(
undefined,
factory.createVariableDeclarationList(
[
factory.createVariableDeclaration(
factory.createIdentifier(`${fieldName}Record`),
undefined,
undefined,
factory.createConditionalExpression(
factory.createIdentifier('record'),
factory.createToken(SyntaxKind.QuestionToken),
factory.createPropertyAccessExpression(
factory.createIdentifier('record'),
factory.createIdentifier(fieldName),
),
factory.createToken(SyntaxKind.ColonToken),
factory.createIdentifier('undefined'),
),
),
],
NodeFlags.Const,
),
),
factory.createVariableStatement(
undefined,
factory.createVariableDeclarationList(
[
factory.createVariableDeclaration(
factory.createIdentifier(`${relatedModelName}Record`),
undefined,
undefined,
factory.createConditionalExpression(
factory.createIdentifier(`${fieldName}Record`),
factory.createToken(SyntaxKind.QuestionToken),
queryCall,
factory.createToken(SyntaxKind.ColonToken),
factory.createIdentifier('undefined'),
),
),
],
NodeFlags.Const,
),
),
factory.createExpressionStatement(
factory.createCallExpression(getSetNameIdentifier(fieldName), undefined, [
factory.createIdentifier(`${fieldName}Record`),
]),
),
factory.createExpressionStatement(
factory.createCallExpression(getSetNameIdentifier(`${fieldName}Records`), undefined, [
factory.createArrayLiteralExpression([factory.createIdentifier(`${relatedModelName}Record`)]),
]),
),
];
}

return [
factory.createVariableStatement(
undefined,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import { extractModelAndKeys, getDisplayValueObjectName, getDisplayValueScalar }
import { getElementAccessExpression } from './invalid-variable-helpers';
import { getSetNameIdentifier, capitalizeFirstLetter } from '../../helpers';
import { getDecoratedLabel } from './label-decorator';
import { DataApiKind } from '../../react-render-config';

function getOnChangeAttribute({
setStateName,
Expand Down Expand Up @@ -130,6 +131,7 @@ export const renderArrayFieldComponent = (
inputField: JsxChild,
labelDecorator?: LabelDecorator,
isRequired?: boolean,
dataApi: DataApiKind = 'DataStore',
) => {
const fieldConfig = fieldConfigs[fieldName];
const { sanitizedFieldName, dataType, componentType } = fieldConfig;
Expand Down Expand Up @@ -239,7 +241,9 @@ export const renderArrayFieldComponent = (
],
undefined,
factory.createToken(SyntaxKind.EqualsGreaterThanToken),
getDisplayValueScalar(fieldName, scalarModel, scalarKey),
dataApi === 'GraphQL' && !isModelDataType(fieldConfig)
? getDisplayValueScalar(fieldName, fieldName, scalarKey)
: getDisplayValueScalar(fieldName, scalarModel, scalarKey),
);
}

Expand Down Expand Up @@ -348,7 +352,9 @@ export const renderArrayFieldComponent = (
[
factory.createExpressionStatement(
factory.createCallExpression(setFieldValueIdentifier, undefined, [
getDisplayValueScalar(fieldName, scalarModel, scalarKey),
dataApi === 'GraphQL'
? getDisplayValueScalar(fieldName, fieldName, scalarKey)
: getDisplayValueScalar(fieldName, scalarModel, scalarKey),
]),
),
factory.createExpressionStatement(
Expand Down
9 changes: 7 additions & 2 deletions packages/codegen-ui-react/lib/forms/react-form-renderer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -654,7 +654,6 @@ export abstract class ReactFormTemplateRenderer extends StudioTemplateRenderer<
if (!(this.renderConfig.apiConfiguration?.dataApi === 'GraphQL')) {
this.importCollection.addMappedImport(ImportValue.USE_DATA_STORE_BINDING);

// @rotp: check if this is needed for collection
statements.push(
...[...relatedModelNames].map((relatedModelName) =>
buildRelationshipQuery(relatedModelName, this.importCollection, dataApi),
Expand Down Expand Up @@ -690,7 +689,13 @@ export abstract class ReactFormTemplateRenderer extends StudioTemplateRenderer<
}

if (hasAutoComplete && dataApi === 'GraphQL') {
statements.push(...getFetchRelatedRecordsCallbacks(formMetadata.fieldConfigs, this.importCollection));
statements.push(
...getFetchRelatedRecordsCallbacks(
formMetadata.fieldConfigs,
this.importCollection,
this.renderConfig.apiConfiguration?.dataApi,
),
);
}

return statements;
Expand Down
10 changes: 9 additions & 1 deletion packages/codegen-ui-react/lib/react-component-renderer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,15 @@ export class ReactComponentRenderer<TPropIn> extends ComponentRendererBase<
this.importCollection.addImport(ImportSource.UI_REACT, 'Text');
this.importCollection.addImport(ImportSource.UI_REACT, 'useTheme');

return renderArrayFieldComponent(this.component.name, label, fieldConfigs, element, labelDecorator, isRequired);
return renderArrayFieldComponent(
this.component.name,
label,
fieldConfigs,
element,
labelDecorator,
isRequired,
this.importCollection.rendererConfig?.apiConfiguration?.dataApi,
);
}
}

Expand Down
47 changes: 29 additions & 18 deletions packages/codegen-ui-react/lib/utils/graphql.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,8 @@ import { ImportCollection, ImportValue } from '../imports';
import { capitalizeFirstLetter, getSetNameIdentifier, lowerCaseFirst } from '../helpers';
import { isBoundProperty, isConcatenatedProperty } from '../react-component-render-helper';
import { Primitive } from '../primitive';
import { DataStoreRenderConfig, GraphqlRenderConfig, NoApiRenderConfig } from '../react-render-config';
import { DataApiKind, DataStoreRenderConfig, GraphqlRenderConfig, NoApiRenderConfig } from '../react-render-config';
import { isModelDataType } from '../forms/form-renderer-helper/render-checkers';

export enum ActionType {
CREATE = 'create',
Expand Down Expand Up @@ -216,6 +217,7 @@ export const getFetchRelatedRecords = (relatedModelName: string) =>
export const getFetchRelatedRecordsCallbacks = (
fieldConfigs: Record<string, FieldConfigMetadata>,
importCollection: ImportCollection,
dataApi: DataApiKind = 'DataStore',
) => {
return Object.entries(fieldConfigs).reduce<Statement[]>(
(acc, [name, { sanitizedFieldName, relationship, valueMappings, componentType }]) => {
Expand Down Expand Up @@ -470,27 +472,36 @@ export const getFetchRelatedRecordsCallbacks = (
],
undefined,
factory.createToken(SyntaxKind.EqualsGreaterThanToken),
factory.createPrefixUnaryExpression(
SyntaxKind.ExclamationToken,
factory.createCallExpression(
factory.createPropertyAccessExpression(
factory.createIdentifier(`${fieldName}IdSet`),
factory.createIdentifier('has'),
),
undefined,
[
factory.createCallChain(
dataApi === 'GraphQL' && !isModelDataType(fieldConfigs[fieldName])
? factory.createBinaryExpression(
factory.createIdentifier(fieldName),
factory.createToken(SyntaxKind.ExclamationEqualsEqualsToken),
factory.createPropertyAccessExpression(
factory.createIdentifier('item'),
factory.createIdentifier('id'),
),
)
: factory.createPrefixUnaryExpression(
SyntaxKind.ExclamationToken,
factory.createCallExpression(
factory.createPropertyAccessExpression(
factory.createIdentifier('getIDValue'),
factory.createIdentifier(fieldName),
factory.createIdentifier(`${fieldName}IdSet`),
factory.createIdentifier('has'),
),
factory.createToken(SyntaxKind.QuestionDotToken),
undefined,
[factory.createIdentifier('item')],
[
factory.createCallChain(
factory.createPropertyAccessExpression(
factory.createIdentifier('getIDValue'),
factory.createIdentifier(fieldName),
),
factory.createToken(SyntaxKind.QuestionDotToken),
undefined,
[factory.createIdentifier('item')],
),
],
),
],
),
),
),
),
],
),
Expand Down
Loading