Skip to content

Commit

Permalink
feat: add support for nested json (#623)
Browse files Browse the repository at this point in the history
  • Loading branch information
Justin Shih committed Sep 7, 2022
1 parent 5e63847 commit 8f0bff0
Show file tree
Hide file tree
Showing 23 changed files with 1,421 additions and 435 deletions.

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -22,15 +22,15 @@ import {
StudioForm,
StudioView,
} from '@aws-amplify/codegen-ui';
import { createPrinter, createSourceFile, EmitHint } from 'typescript';
import { createPrinter, createSourceFile, EmitHint, NewLineKind, Node } from 'typescript';
import { AmplifyFormRenderer } from '../../amplify-ui-renderers/amplify-form-renderer';
import { AmplifyRenderer } from '../../amplify-ui-renderers/amplify-renderer';
import { AmplifyViewRenderer } from '../../amplify-ui-renderers/amplify-view-renderer';
import { ModuleKind, ReactRenderConfig, ScriptKind, ScriptTarget } from '../../react-render-config';
import { loadSchemaFromJSONFile } from './example-schema';
import { transpile } from '../../react-studio-template-renderer-helper';
import { defaultRenderConfig, transpile } from '../../react-studio-template-renderer-helper';

export const defaultCLIRenderConfig: ReactRenderConfig = {
export const defaultCLIRenderConfig = {
module: ModuleKind.ES2020,
target: ScriptTarget.ES2020,
script: ScriptKind.JSX,
Expand Down Expand Up @@ -104,3 +104,17 @@ export const renderTableJsxElement = (

return transpile(tableNode, {}).componentText;
};

export const genericPrinter = (node: Node): string => {
const file = createSourceFile(
'sampleFileName.js',
'',
defaultCLIRenderConfig.target,
false,
defaultRenderConfig.script,
);
const printer = createPrinter({
newLine: NewLineKind.LineFeed,
});
return printer.printNode(EmitHint.Unspecified, node, file);
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`nested state should generate state structure for nested keyPath 1`] = `"{ ...bio, favoriteAnimal: { ...bio?.favoriteAnimal, animalMeta: { ...bio?.favoriteAnimal?.animalMeta, family: { ...bio?.favoriteAnimal?.animalMeta?.family, genus: value } } } }"`;
exports[`nested state should generate value for 2nd level deep object 1`] = `"{ ...bio, firstName: \\"John C\\" }"`;
exports[`set field state should generate state call for nested object 1`] = `"setBio({ ...bio, favoriteAnimal: { ...bio?.favoriteAnimal, animalMeta: { ...bio?.favoriteAnimal?.animalMeta, family: { ...bio?.favoriteAnimal?.animalMeta?.family, genus: \\"hello World\\" } } } })"`;
exports[`set field state should generate state call for non-nested objects 1`] = `"setFirstName(\\"john c\\")"`;
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`should generate nested object should generate type for nested object 1`] = `
"export declare type myCreateFormInputValues = {
firstName?: ValidationFunction<string>;
isExplorer?: ValidationFunction<boolean>;
bio?: {
favoriteAnimal?: {
animalMeta?: {
family?: {
genus?: ValidationFunction<string>;
};
earliestRecord?: ValidationFunction<number>;
};
};
};
};"
`;
exports[`should generate nested object should generate type for non nested object 1`] = `
"export declare type myCreateFormInputValues = {
firstName?: ValidationFunction<string>;
isExplorer?: ValidationFunction<boolean>;
};"
`;
59 changes: 59 additions & 0 deletions packages/codegen-ui-react/lib/__tests__/forms/form-state.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
/*
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License").
You may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import { factory } from 'typescript';
import { buildNestedStateSet, setFieldState } from '../../forms/form-state';
import { genericPrinter } from '../__utils__';

describe('nested state', () => {
it('should generate state structure for nested keyPath', () => {
const state = buildNestedStateSet(
['bio', 'favoriteAnimal', 'animalMeta', 'family', 'genus'],
['bio'],
factory.createIdentifier('value'),
);
const response = genericPrinter(state);
expect(response).toMatchSnapshot();
});

it('should generate value for 2nd level deep object', () => {
const state = buildNestedStateSet(['bio', 'firstName'], ['bio'], factory.createStringLiteral('John C'));
const response = genericPrinter(state);
expect(response).toMatchSnapshot();
});

it('should throw error for 1 level deep path', () => {
expect(() => buildNestedStateSet(['firstName'], ['firstName'], factory.createStringLiteral('John C'))).toThrowError(
'keyPath needs a length larger than 1 to build nested state object',
);
});
});

describe('set field state', () => {
it('should generate state call for nested object', () => {
const fieldStateSetter = setFieldState(
'bio.favoriteAnimal.animalMeta.family.genus',
factory.createStringLiteral('hello World'),
);
const response = genericPrinter(fieldStateSetter);
expect(response).toMatchSnapshot();
});

it('should generate state call for non-nested objects', () => {
const fieldStateSetter = setFieldState('firstName', factory.createStringLiteral('john c'));
const response = genericPrinter(fieldStateSetter);
expect(response).toMatchSnapshot();
});
});
61 changes: 61 additions & 0 deletions packages/codegen-ui-react/lib/__tests__/forms/type-helper.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
/*
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License").
You may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

import { FieldConfigMetadata } from '@aws-amplify/codegen-ui';
import { generateOnValidationType } from '../../forms/type-helper';
import { genericPrinter } from '../__utils__';

describe('should generate nested object', () => {
it('should generate type for nested object', () => {
const fieldConfigs: Record<string, FieldConfigMetadata> = {
'bio.favoriteAnimal.animalMeta.family.genus': {
dataType: 'String',
validationRules: [],
},
'bio.favoriteAnimal.animalMeta.earliestRecord': {
dataType: 'AWSTimestamp',
validationRules: [],
},
firstName: {
dataType: 'String',
validationRules: [],
},
isExplorer: {
dataType: 'Boolean',
validationRules: [],
},
};
const types = generateOnValidationType('myCreateForm', fieldConfigs);
const response = genericPrinter(types);
expect(response).toMatchSnapshot();
});

it('should generate type for non nested object', () => {
const fieldConfigs: Record<string, FieldConfigMetadata> = {
firstName: {
dataType: 'String',
validationRules: [],
},
isExplorer: {
dataType: 'Boolean',
validationRules: [],
},
};
const types = generateOnValidationType('myCreateForm', fieldConfigs);
const response = genericPrinter(types);
expect(response).toMatchSnapshot();
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -8,18 +8,14 @@ exports[`form-render utils should generate before & complete types if datastore
errorMessage?: string;
}) => void;
onCancel?: () => void;
onValidate?: {
[field in keyof mySampleFormInputValues]?: (value: mySampleFormInputValues[field], validationResponse: ValidationResponse) => ValidationResponse | Promise<ValidationResponse>;
};
onValidate?: mySampleFormInputValues;
}"
`;

exports[`form-render utils should generate regular onsubmit if dataSourceType is custom 1`] = `
"{
onSubmit: (fields: Record<string, string>) => void;
onCancel?: () => void;
onValidate?: {
[field in keyof myCustomFormInputValues]?: (value: myCustomFormInputValues[field], validationResponse: ValidationResponse) => ValidationResponse | Promise<ValidationResponse>;
};
onValidate?: myCustomFormInputValues;
}"
`;
Original file line number Diff line number Diff line change
Expand Up @@ -64,5 +64,11 @@ describe('amplify form renderer tests', () => {
expect(componentText).toMatchSnapshot();
expect(declaration).toMatchSnapshot();
});

it('should render nested json fields', () => {
const { componentText, declaration } = generateWithAmplifyFormRenderer('forms/bio-nested-create', undefined);
expect(componentText).toMatchSnapshot();
expect(declaration).toMatchSnapshot();
});
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
/*
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License").
You may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

import { fetchByPath } from '../../utils/json-path-fetch';

describe('fetch by path util', () => {
const nestedObj = {
levelOne: {
levelTwo: {
levelThree: {
bingo: (value: string) => `Winner Winner ${value}!`,
},
},
},
};
it('should fetch value from nested object', () => {
const fn: Function = fetchByPath(nestedObj, 'levelOne.levelTwo.levelThree.bingo');
const result = fn('helloWorld');
expect(result).toEqual('Winner Winner helloWorld!');
});

it('should return undefined if value does not exist in nested object', () => {
const result = fetchByPath(nestedObj, 'levelOne.levelTwo.nonExistentLevel');
expect(result).toBeUndefined();
});
});
4 changes: 3 additions & 1 deletion packages/codegen-ui-react/lib/amplify-ui-renderers/form.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ import { buildOpeningElementProperties } from '../react-component-render-helper'
import { ImportCollection } from '../imports';
import { getActionIdentifier } from '../workflow';
import { buildDataStoreExpression } from '../forms';
import { onSubmitValidationRun } from '../forms/form-renderer-helper';
import { onSubmitValidationRun, buildModelFieldObject } from '../forms/form-renderer-helper';

export default class FormRenderer extends ReactComponentRenderer<BaseComponentProps> {
constructor(
Expand Down Expand Up @@ -190,6 +190,7 @@ export default class FormRenderer extends ReactComponentRenderer<BaseComponentPr
}

private getFormOnSubmitAttribute(): JsxAttribute {
const { formMetadata } = this.componentMetadata;
return factory.createJsxAttribute(
factory.createIdentifier('onSubmit'),
factory.createJsxExpression(
Expand Down Expand Up @@ -222,6 +223,7 @@ export default class FormRenderer extends ReactComponentRenderer<BaseComponentPr
[],
),
),
buildModelFieldObject(formMetadata?.fieldConfigs),
...onSubmitValidationRun,
...this.getOnSubmitDSCall(),
],
Expand Down
Loading

0 comments on commit 8f0bff0

Please sign in to comment.