amazon-web-servicesaws-cdkaws-appsyncaws-cdk-typescriptaws-appsync-resolver

AWS CDK - Appsync Javascript Resolver Validation with DynamoDB datasource


I'm unfamiliar with best practice of validation/error handling in Appsync with Javascript resolvers (I'm using DynamoDB data source). I can't return an object with an error message currently in the request without it throwing an error saying I need an "operation"... I'm a bit confused because you'd think there is a way to not incur a cost of hitting DynamoDB if validation fails, and I cannot find documentation for this.

export function request(ctx: Context) {
  const cognitoSub = (ctx.identity as AppSyncIdentityCognito)?.claims?.sub;
  const { firstName, lastName, country } = ctx.arguments || {};

  if (!cognitoSub) {
    return { error: 'User is not authenticated - Missing Cognito Sub.' };
  }

  if (!firstName || firstName.trim() === '') {
    return { error: 'Validation failed - First name is required.' };
  }

  if (!lastName || lastName.trim() === '') {
    return { error: 'Validation failed - Last name is required.' };
  }
  // Create an object with the validated values
  const attributes: UserAttributes = {};
  if (firstName) attributes.firstName = firstName;
  if (lastName) attributes.lastName = lastName;
  if (country) attributes.country = country;

  // If validation passes, proceed with the UpdateItem operation
  return {
    operation: 'UpdateItem',
    key: util.dynamodb.toMapValues({
      'PK': `USER#${cognitoSub}`,
      'SK': 'PROFILE#v1'
    }),
    attributeValues: util.dynamodb.toMapValues(attributes),
    returnValues: 'ALL_NEW'
  };
}

I've tried throwing an error or simply returning an object early with an error message in request but it does not take it unless "operation" is present. If Operation is present it will try to query DynamoDB, and if you give it a fake operation name it will return an error saying the operation is not valid.


Solution

  • Use the error utility helpers on the built-in util object to let AppSync know a validation error has occurred:

    if (!cognitoSub) {
        util.error('User is not authenticated - Missing Cognito Sub.');
        return;
    }
    

    Type definitions are available in the @aws-appsync/utils package to help with development.