Skip to content

Commit

Permalink
fix: parse values for non-model arrays
Browse files Browse the repository at this point in the history
  • Loading branch information
Hein Jeong authored and hein-j committed Jan 3, 2023
1 parent 47b179b commit ffb68b7
Show file tree
Hide file tree
Showing 10 changed files with 946 additions and 90 deletions.

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import {
Statement,
VariableStatement,
ExpressionStatement,
PropertyAssignment,
} from 'typescript';
import { getSetNameIdentifier, lowerCaseFirst } from '../../helpers';
import { getDisplayValueObjectName } from './model-values';
Expand Down Expand Up @@ -198,10 +199,15 @@ export const buildDataStoreExpression = (
const thisModelPrimaryKeys = dataSchema.models[modelName].primaryKeys;
const hasManyDataStoreStatements: (VariableStatement | ExpressionStatement)[] = [];
const hasManyRelationshipFields: string[] = [];
const nonModelArrayFields: string[] = [];
const savedModelName = lowerCaseFirst(modelName);

Object.entries(fieldConfigs).forEach((fieldConfig) => {
const [fieldName, fieldConfigMetaData] = fieldConfig;
const { dataType, isArray } = fieldConfigMetaData;
if (isArray && dataType && typeof dataType === 'object' && 'nonModel' in dataType) {
nonModelArrayFields.push(fieldName);
}
if (fieldConfigMetaData.relationship?.type === 'HAS_MANY') {
hasManyRelationshipFields.push(fieldName);

Expand Down Expand Up @@ -250,6 +256,68 @@ export const buildDataStoreExpression = (
);
}

const propertyAssignments: PropertyAssignment[] = [];

hasManyRelationshipFields.forEach((field) => {
// CPKProjects: undefined
propertyAssignments.push(
factory.createPropertyAssignment(factory.createIdentifier(field), factory.createIdentifier('undefined')),
);
});

nonModelArrayFields.forEach((field) => {
// nonModelFieldArray: modelFields.nonModelFieldArray.map(s => JSON.parse(s))
propertyAssignments.push(
factory.createPropertyAssignment(
factory.createIdentifier(field),
factory.createCallExpression(
factory.createPropertyAccessExpression(
factory.createPropertyAccessExpression(
factory.createIdentifier('modelFields'),
factory.createIdentifier(field),
),
factory.createIdentifier('map'),
),
undefined,
[
factory.createArrowFunction(
undefined,
undefined,
[
factory.createParameterDeclaration(
undefined,
undefined,
undefined,
factory.createIdentifier('s'),
undefined,
undefined,
undefined,
),
],
undefined,
factory.createToken(SyntaxKind.EqualsGreaterThanToken),
factory.createCallExpression(
factory.createPropertyAccessExpression(
factory.createIdentifier('JSON'),
factory.createIdentifier('parse'),
),
undefined,
[factory.createIdentifier('s')],
),
),
],
),
),
);
});

const modelFieldsObject = propertyAssignments.length
? factory.createObjectLiteralExpression(
[factory.createSpreadAssignment(factory.createIdentifier('modelFields')), ...propertyAssignments],
true,
)
: factory.createIdentifier('modelFields');

const genericSaveStatement = hasManyRelationshipFields.length
? [
factory.createVariableStatement(
Expand All @@ -269,23 +337,7 @@ export const buildDataStoreExpression = (
undefined,
[
factory.createNewExpression(factory.createIdentifier(importedModelName), undefined, [
// {
// ...modelFields,
// CPKClasses: undefined,
// CPKProjects: undefined
// }
factory.createObjectLiteralExpression(
[
factory.createSpreadAssignment(factory.createIdentifier('modelFields')),
...hasManyRelationshipFields.map((field) =>
factory.createPropertyAssignment(
factory.createIdentifier(field),
factory.createIdentifier('undefined'),
),
),
],
true,
),
modelFieldsObject,
]),
],
),
Expand All @@ -307,7 +359,7 @@ export const buildDataStoreExpression = (
undefined,
[
factory.createNewExpression(factory.createIdentifier(importedModelName), undefined, [
factory.createIdentifier('modelFields'),
modelFieldsObject,
]),
],
),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@
See the License for the specific language governing permissions and
limitations under the License.
*/
import { factory, NodeFlags, ObjectLiteralElementLike, SyntaxKind } from 'typescript';
import { FieldConfigMetadata, isNonModelDataType } from '@aws-amplify/codegen-ui';
import { factory, NodeFlags, ObjectLiteralElementLike } from 'typescript';
import { FieldConfigMetadata } from '@aws-amplify/codegen-ui';

/**
* builds modelFields object which is used to validate, onSubmit, onSuccess/onError
Expand All @@ -38,7 +38,7 @@ export const buildModelFieldObject = (
const fieldSet = new Set<string>();
const fields = Object.keys(fieldConfigs).reduce<ObjectLiteralElementLike[]>((acc, value) => {
const fieldName = value.split('.')[0];
const { sanitizedFieldName, dataType } = fieldConfigs[value];
const { sanitizedFieldName } = fieldConfigs[value];
const renderedFieldName = sanitizedFieldName || fieldName;
if (!fieldSet.has(renderedFieldName)) {
let assignment: ObjectLiteralElementLike = factory.createShorthandPropertyAssignment(
Expand All @@ -56,23 +56,6 @@ export const buildModelFieldObject = (
);
}

/*
Empty string value for not required url field fails to save at datastore
let modelFields = {
url: url || undefined,
}
*/
if ((dataType === 'AWSURL' || isNonModelDataType(dataType)) && !shouldBeConst) {
assignment = factory.createPropertyAssignment(
factory.createStringLiteral(fieldName),
factory.createBinaryExpression(
factory.createIdentifier(renderedFieldName),
factory.createToken(SyntaxKind.BarBarToken),
factory.createIdentifier('undefined'),
),
);
}

acc.push(assignment);
fieldSet.add(renderedFieldName);
}
Expand Down
9 changes: 9 additions & 0 deletions packages/codegen-ui/example-schemas/datastore/post.json
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,15 @@
"isRequired": false,
"attributes": []
},
"nonModelFieldArray": {
"name": "nonModelFieldArray",
"isArray": true,
"type": {
"nonModel": "CustomType"
},
"isRequired": false,
"attributes": []
},
"createdAt": {
"name": "createdAt",
"isArray": false,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,13 @@ describe('CreateForms', () => {
getTextAreaByLabel('Non model field').type(JSON.stringify({ StringVal: 'myValue' }), {
parseSpecialCharSequences: false,
});

getArrayFieldButtonByLabel('Non model field array').click();
getTextAreaByLabel('Non model field array').type(JSON.stringify({ StringVal: 'index1StringValue' }), {
parseSpecialCharSequences: false,
});
clickAddToArray();

getInputByLabel('Aws phone').type('714-234-4829');
cy.get('select').select('San francisco');

Expand Down Expand Up @@ -196,6 +203,7 @@ describe('CreateForms', () => {
expect(record.awsIPAddress).to.equal('192.0.2.146');
expect(record.awsJson.myKey).to.equal('myValue');
expect(record.nonModelField.StringVal).to.equal('myValue');
expect(record.nonModelFieldArray[0].StringVal).to.equal('index1StringValue');
expect(record.awsPhone).to.equal('714-234-4829');
expect(record.enum).to.equal('SAN_FRANCISCO');
expect(record.stringArray[0]).to.equal('String1');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ const initializeAllSupportedFormFieldsTestData = async ({
awsIPAddress: '123.12.34.56',
boolean: true,
awsJson: JSON.stringify({ myKey: 'myValue' }),
nonModelField: JSON.stringify({ StringVal: 'myValue' }),
nonModelField: { StringVal: 'myValue' },
awsPhone: '713 343 5938',
enum: 'NEW_YORK',
HasOneUser: connectedUser,
Expand Down

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ const {
CompositeToy,
CompositeVet,
CompositeDogCompositeVet,
CustomType,
} = initSchema(schema);

export {
Expand All @@ -77,4 +78,5 @@ export {
CompositeToy,
CompositeVet,
CompositeDogCompositeVet,
CustomType,
};
Original file line number Diff line number Diff line change
Expand Up @@ -741,6 +741,15 @@ export const schema = {
isRequired: false,
attributes: [],
},
nonModelFieldArray: {
name: 'nonModelFieldArray',
isArray: true,
type: {
nonModel: 'CustomType',
},
isRequired: false,
attributes: [],
},
HasOneUser: {
name: 'HasOneUser',
isArray: false,
Expand Down
9 changes: 9 additions & 0 deletions packages/test-generator/lib/models/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -743,6 +743,15 @@ export default {
isRequired: false,
attributes: [],
},
nonModelFieldArray: {
name: 'nonModelFieldArray',
isArray: true,
type: {
nonModel: 'CustomType',
},
isRequired: false,
attributes: [],
},
HasOneUser: {
name: 'HasOneUser',
isArray: false,
Expand Down

0 comments on commit ffb68b7

Please sign in to comment.