Skip to content

Commit

Permalink
fix(@aws-amplify/datastore): Validate arrays of scalars in model cons…
Browse files Browse the repository at this point in the history
…tructor (aws-amplify#4508)
  • Loading branch information
manueliglesias authored and undefobj committed Dec 4, 2019
1 parent 980307b commit 8d2ba6e
Showing 1 changed file with 16 additions and 2 deletions.
18 changes: 16 additions & 2 deletions packages/datastore/src/datastore/datastore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -248,7 +248,7 @@ const createModelClass = <T extends PersistentModel>(
const fieldDefinition = modelDefinition.fields[k];

if (fieldDefinition !== undefined) {
const { type, isRequired, name } = fieldDefinition;
const { type, isRequired, name, isArray } = fieldDefinition;

if (isRequired && (v === null || v === undefined)) {
throw new Error(`Field ${name} is required`);
Expand All @@ -257,7 +257,21 @@ const createModelClass = <T extends PersistentModel>(
if (isGraphQLScalarType(type)) {
const jsType = GraphQLScalarType.getJSType(type);

if (typeof v !== jsType && v !== null) {
if (isArray) {
if (!Array.isArray(v)) {
throw new Error(
`Field ${name} should be of type ${jsType}[], ${typeof v} received. ${v}`
);
}

if ((<[]>v).some(e => typeof e !== jsType)) {
const elemTypes = (<[]>v).map(e => typeof e).join(',');

throw new Error(
`All elements in the ${name} array should be of type ${jsType}, [${elemTypes}] received. ${v}`
);
}
} else if (typeof v !== jsType && v !== null) {
throw new Error(
`Field ${name} should be of type ${jsType}, ${typeof v} received. ${v}`
);
Expand Down

0 comments on commit 8d2ba6e

Please sign in to comment.