5

I used AWS Amplify to create an GraphQL API. In DynamoDB the fields createdAt, updatedAt and owner are created automatically. Out of the box I have no way of getting the values for this fields. Now when I add those fields to the annotated schema, I will be able to get the values but the everybody with write-permissions can just overwrite them which is annoying for the time fields and a security risk for the owner field.

So how do I get those values?

This is an AWS-Amplify specific question. It's not about how to do this with generic GraphQL. It's very specifically about how to do this with AWS-Amplify's API module and their (sadly very limited) directives (https://aws-amplify.github.io/docs/js/api#using-graphql-transformers).

Muhammet Can
  • 1,304
  • 2
  • 16
  • 30
Philip Claren
  • 2,705
  • 3
  • 24
  • 33

3 Answers3

4

You should override create resolver like this:

Instead of:

## [Start] Prepare DynamoDB PutItem Request. **
$util.qr($context.args.input.put("createdAt", $util.defaultIfNull($ctx.args.input.createdAt, $util.time.nowISO8601())))
$util.qr($context.args.input.put("updatedAt", $util.defaultIfNull($ctx.args.input.updatedAt, $util.time.nowISO8601())))

You should:

## [Start] Prepare DynamoDB PutItem Request. **
$util.qr($context.args.input.put("createdAt", $util.time.nowISO8601()))
$util.qr($context.args.input.put("updatedAt", $util.time.nowISO8601()))

In update resolver

Instead of:

## Automatically set the updatedAt timestamp. **
$util.qr($context.args.input.put("updatedAt", $util.defaultIfNull($ctx.args.input.updatedAt, $util.time.nowISO8601())))

You should:

## Automatically set the updatedAt timestamp. **
$util.qr($context.args.input.put("updatedAt", $util.time.nowISO8601()))

aws-amplify-overriding-auto-generated

P.S. Place the new resolvers in /resolvers folder. Not in /build/resolvers

Community
  • 1
  • 1
0

In order to get this data you would have to have some sort of corresponding type & query in the Schema.

I know you mentioned you would not like to have them in the Schema for reasons like a security risk but in reality any field you have available in your schema is open for editing for anyone with access to the API.

My suggestion would be to let your developers working on the project use a new environment using the new Multi Environment support from the Amplify CLI in order to have a separate API that is not exposed in production to prevent issues with breaking changes to your main Schema.

Nader Dabit
  • 52,483
  • 13
  • 107
  • 91
-1

Create two graphql interfaces, one is public and exposes just the queries, mutations, and subscriptions you want to expose to the app/users. This is where all your business logic goes, written into the resolvers to ensure fields such as timestamps are not overwritten.

The second is more comprehensive and is only exposed to and only used by your public graphql interface.

This is how Yoga/Prisma work together.

Chris Geirman
  • 9,474
  • 5
  • 37
  • 70