From 2a46b1da8e64a8c27b6b1b9a121c6e02415deb05 Mon Sep 17 00:00:00 2001 From: Peter Vaiciulis Date: Sun, 15 Sep 2024 22:09:31 -0700 Subject: [PATCH] fix(graphql-default-value-transformer): @default cannot be used on composite key members --- .../package.json | 3 ++- .../src/graphql-default-value-transformer.ts | 14 ++++++++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/packages/amplify-graphql-default-value-transformer/package.json b/packages/amplify-graphql-default-value-transformer/package.json index 32bf38253d..9839b40476 100644 --- a/packages/amplify-graphql-default-value-transformer/package.json +++ b/packages/amplify-graphql-default-value-transformer/package.json @@ -75,7 +75,8 @@ "src/**/*.ts" ], "coveragePathIgnorePatterns": [ - "/__tests__/" + "/__tests__/", + "types.ts" ], "snapshotFormat": { "escapeString": true, diff --git a/packages/amplify-graphql-default-value-transformer/src/graphql-default-value-transformer.ts b/packages/amplify-graphql-default-value-transformer/src/graphql-default-value-transformer.ts index 41a0e8855b..01fd4b424f 100644 --- a/packages/amplify-graphql-default-value-transformer/src/graphql-default-value-transformer.ts +++ b/packages/amplify-graphql-default-value-transformer/src/graphql-default-value-transformer.ts @@ -20,6 +20,7 @@ import { FieldDefinitionNode, InterfaceTypeDefinitionNode, Kind, + ListValueNode, ObjectTypeDefinitionNode, StringValueNode, TypeNode, @@ -82,11 +83,24 @@ const validateNotPrimaryKey = (field: FieldDefinitionNode): void => { } }; +const validateNotCompositeKeyMember = (config: DefaultValueDirectiveConfiguration): void => { + const objectDirectives = config.object.fields?.flatMap((f) => f.directives); + const primaryKeyDirective = objectDirectives?.find((dir) => dir?.name.value === 'primaryKey'); + if (primaryKeyDirective) { + const sortKeyFields = primaryKeyDirective.arguments?.find((arg) => arg.name.value === 'sortKeyFields')?.value as ListValueNode; + const sortKeys = sortKeyFields?.values as StringValueNode[]; + if (sortKeys?.some((sortKey) => sortKey.value === config.field.name.value)) { + throw new InvalidDirectiveError('The @default directive may not be applied to composite key member fields.'); + } + } +}; + const validate = (ctx: TransformerSchemaVisitStepContextProvider, config: DefaultValueDirectiveConfiguration): void => { validateModelDirective(config); validateFieldType(ctx, config.field.type); validateDirectiveArguments(config.directive); validateNotPrimaryKey(config.field); + validateNotCompositeKeyMember(config); // Validate the default values only for the DynamoDB datasource. // For SQL, the database determines and sets the default value. We will not validate the value in transformers.