Skip to content

A custom transformer of the amplify-cli. It can control accessibility of auto generated fields.

License

Notifications You must be signed in to change notification settings

hirochachacha/graphql-auto-transformer

Repository files navigation

graphql-auto-transformer

A custom transformer of the amplify-cli. It can control accessibility of auto generated fields.

directive @auto(creatable: Boolean = false, updatable: Boolean = false) on FIELD_DEFINITION

Motivation

If you are familiar with amplify-cli, you know several fields of object are generated by some directives. For example, @model generates createdAt and updatedAt, @versioned generates version, @auth generates owner and so on. Currently, the official way to access these fields from GraphQL API is to define these types as nullable types.

type Post @model {
  id: ID!
  text: String
  createdAt: AWSDateTime
}

However above solution isn't ideal because users can modify createdAt at any time.

input CreatePostInput {
  id: ID
  text: String
  createdAt: AWSDateTime
}

input UpdatePostInput {
  id: ID!
  text: String
  createdAt: AWSDateTime
}

We want to strip createdAt field from CreatePostInput and UpdatePostInput.

What is worse, we cannot use nullable type as a part of a database index. So, we should write:

type Post
  @model
  @key(name: "byUser", fields: ["userId", "createdAt"]) {
    id: ID!
    userId: ID!
    text: String
    createdAt: AWSDateTime!
}

Predictabley, the result is bad. aws-amplify/amplify-cli#1657

Usage

1. Install package

npm install graphql-auto-transformer -D

or

yarn add graphql-auto-transformer -D

2. Setup custom transformer

Edit amplify/backend/api/<YOUR_API>/transform.conf.json and append "./graphql-auto-transformer" to transformers field.

    "transformers": [
      "graphql-auto-transformer"
    ]

3. Use @auto directive

Append @auto to target fields.

type Post @model {
  id: ID!
  text: String
  createdAt: AWSDateTime! @auto
}

generates:

input CreatePostInput {
  id: ID
  text: String
}

input UpdatePostInput {
  id: ID!
  text: String
}

If you want to allow optional creation/update like id field, use creatable and updatable parameter.

type Post @model {
  id: ID!
  text: String
  createdAt: AWSDateTime! @auto(creatable: true)
}

generates:

input CreatePostInput {
  id: ID
  text: String
  createdAt: AWSDateTime
}

input UpdatePostInput {
  id: ID!
  text: String
}

License

Fork of graphql-versioned-transformer

Apache-2.0

Copyright 2017 - 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.

Copyright 2020 - 2020 Hiroshi Ioka. All Rights Reserved.

About

A custom transformer of the amplify-cli. It can control accessibility of auto generated fields.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published