You are viewing the preview version of this book
Click here for the full version.

API resources

Now that we have the foundations, the next step is to start implementing the API and the resources associated to it. This part is simple: we'll want an AppSync API with logging and authorization, data sources for the resolvers, and also the IAM permissions needed.

API

The API defines the schema, the authorization modes, and the logging configuration:

resource "aws_appsync_graphql_api" "appsync" {
  name                = "social-network"
  schema              = file("schema.graphql")
  authentication_type = "AMAZON_COGNITO_USER_POOLS"
  user_pool_config {
    default_action = "ALLOW"
    user_pool_id   = aws_cognito_user_pool.pool.id
  }
  additional_authentication_provider {
    authentication_type = "AWS_IAM"
  }
  log_config {
    cloudwatch_logs_role_arn = aws_iam_role.appsync_logs.arn
    field_log_level          = "ALL"
  }
}

As we've discussed in the chapter about logging, the Log Group should be managed by Terraform instead of letting AppSync create it. This means a separate resource for the Log Group:

resource "aws_cloudwatch_log_group" "loggroup" {
  name              =
    "/aws/appsync/apis/${aws_appsync_graphql_api.appsync.id}"
  retention_in_days = 14
}

As well as permissions only to create Log Streams and events:

data "aws_iam_policy_document" "appsync_policy" {
  statement {
    actions = [
      "logs:CreateLogStream",
      "logs:PutLogEvents"
    ]
    resources = [
      "arn:aws:logs:*:*:*"
    ]
  }
}

Data sources

Next, create a data source for each DynamoDB table:

resource "aws_appsync_datasource" "ddb_user" {
  api_id           = aws_appsync_graphql_api.appsync.id
  name             = "ddb_user"
  service_role_arn = aws_iam_role.appsync.arn
  type             = "AMAZON_DYNAMODB"
  dynamodb_config {
    table_name = aws_dynamodb_table.user.name
  }
}

The other tables follow the same structure.

We'll also need a NONE data source to convert the timestamp from what is stored in the database and what AppSync expects:

resource "aws_appsync_datasource" "none" {
  api_id = aws_appsync_graphql_api.appsync.id
  name   = "none"
  type   = "NONE"
}

Finally, we'll need a data source to trigger mutations in the API:

There is more, but you've reached the end of this preview
Read this and all other chapters in full and get lifetime access to:
  • all future updates
  • full web-based access
  • PDF and Epub versions