Skip to content

Commit

Permalink
add validation for references fields match
Browse files Browse the repository at this point in the history
  • Loading branch information
sundersc committed Aug 3, 2023
1 parent b8f8597 commit 588df50
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ import {
registerHasManyForeignKeyMappings,
validateDisallowedDataStoreRelationships,
validateModelDirective,
validateParentReferencesFields,
validateRelatedModelDirective,
} from './utils';
import { DDBRelationalResolverGenerator } from './resolver/ddb-generator';
Expand Down Expand Up @@ -157,6 +158,8 @@ export class HasManyTransformer extends TransformerPluginBase {
const dbType = ctx.modelToDatasourceMap.get(getBaseType(config.field.type))?.dbType ?? DDB_DB_TYPE;
if (dbType === DDB_DB_TYPE) {
config.relatedTypeIndex = getRelatedTypeIndex(config, context, config.indexName);
} else if (dbType === MYSQL_DB_TYPE) {
validateParentReferencesFields(config, context);
}
ensureHasManyConnectionField(config, context);
extendTypeWithConnection(config, context);
Expand Down
29 changes: 28 additions & 1 deletion packages/amplify-graphql-relational-transformer/src/utils.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { getFieldNameFor, InvalidDirectiveError } from '@aws-amplify/graphql-transformer-core';
import { getFieldNameFor, getPrimaryKeyFields, InvalidDirectiveError } from '@aws-amplify/graphql-transformer-core';
import {
FieldMapEntry,
ResolverReferenceEntry,
Expand All @@ -23,6 +23,33 @@ import {
ManyToManyDirectiveConfiguration,
} from './types';

export const validateParentReferencesFields = (
config: HasManyDirectiveConfiguration | HasOneDirectiveConfiguration,
ctx: TransformerContextProvider,
): void => {
const { directiveName, object, references, relatedType } = config;
const enums = ctx.output.getTypeDefinitionsOfKind(Kind.ENUM_TYPE_DEFINITION) as EnumTypeDefinitionNode[];

const primaryKeys = getPrimaryKeyFields(object);
if (primaryKeys.length !== references.length) {
throw new InvalidDirectiveError(
`The number of references provided to @${directiveName} must match the number of primary keys on ${object.name.value}.`,
);
}

for (const reference of references) {
const fieldNode = relatedType.fields!.find((field) => field.name.value === reference);

if (!fieldNode) {
throw new InvalidDirectiveError(`${reference} is not a field in ${relatedType.name.value}`);
}

if (!isScalarOrEnum(fieldNode.type, enums)) {
throw new InvalidDirectiveError(`All fields provided to @${directiveName} must be scalar or enum fields.`);
}
}
};

export function getRelatedTypeIndex(
config: HasOneDirectiveConfiguration,
ctx: TransformerContextProvider,
Expand Down

0 comments on commit 588df50

Please sign in to comment.