| Interface | Description |
|---|---|
| AddFieldOptions |
(experimental) The options to add a field to an Intermediate Type.
|
| ApiKeyConfig |
(experimental) Configuration for API Key authorization in AppSync.
|
| AppsyncFunctionAttributes |
(experimental) The attributes for imported AppSync Functions.
|
| AppsyncFunctionProps |
(experimental) the CDK properties for AppSync Functions.
|
| AuthorizationConfig |
(experimental) Configuration of the API authorization modes.
|
| AuthorizationMode |
(experimental) Interface to specify default or additional authorization(s).
|
| AwsIamConfig |
(experimental) The authorization config in case the HTTP endpoint requires authorization.
|
| BackedDataSourceProps |
(experimental) properties for an AppSync datasource backed by a resource.
|
| BaseAppsyncFunctionProps |
(experimental) the base properties for AppSync Functions.
|
| BaseDataSourceProps |
(experimental) Base properties for an AppSync datasource.
|
| BaseResolverProps |
(experimental) Basic properties for an AppSync resolver.
|
| BaseTypeOptions |
(experimental) Base options for GraphQL Types.
|
| CfnApiCacheProps |
Properties for defining a `AWS::AppSync::ApiCache`.
|
| CfnApiKeyProps |
Properties for defining a `AWS::AppSync::ApiKey`.
|
| CfnDataSource.AuthorizationConfigProperty | |
| CfnDataSource.AwsIamConfigProperty | |
| CfnDataSource.DeltaSyncConfigProperty | |
| CfnDataSource.DynamoDBConfigProperty | |
| CfnDataSource.ElasticsearchConfigProperty | |
| CfnDataSource.HttpConfigProperty | |
| CfnDataSource.LambdaConfigProperty | |
| CfnDataSource.RdsHttpEndpointConfigProperty | |
| CfnDataSource.RelationalDatabaseConfigProperty | |
| CfnDataSourceProps |
Properties for defining a `AWS::AppSync::DataSource`.
|
| CfnFunctionConfiguration.LambdaConflictHandlerConfigProperty | |
| CfnFunctionConfiguration.SyncConfigProperty | |
| CfnFunctionConfigurationProps |
Properties for defining a `AWS::AppSync::FunctionConfiguration`.
|
| CfnGraphQLApi.AdditionalAuthenticationProviderProperty | |
| CfnGraphQLApi.CognitoUserPoolConfigProperty | |
| CfnGraphQLApi.LambdaAuthorizerConfigProperty | |
| CfnGraphQLApi.LogConfigProperty | |
| CfnGraphQLApi.OpenIDConnectConfigProperty | |
| CfnGraphQLApi.UserPoolConfigProperty | |
| CfnGraphQLApiProps |
Properties for defining a `AWS::AppSync::GraphQLApi`.
|
| CfnGraphQLSchemaProps |
Properties for defining a `AWS::AppSync::GraphQLSchema`.
|
| CfnResolver.CachingConfigProperty | |
| CfnResolver.LambdaConflictHandlerConfigProperty | |
| CfnResolver.PipelineConfigProperty | |
| CfnResolver.SyncConfigProperty | |
| CfnResolverProps |
Properties for defining a `AWS::AppSync::Resolver`.
|
| DataSourceOptions |
(experimental) Optional configuration for data sources.
|
| DynamoDbDataSourceProps |
(experimental) Properties for an AppSync DynamoDB datasource.
|
| EnumTypeOptions |
(experimental) Properties for configuring an Enum Type.
|
| ExtendedDataSourceProps |
(experimental) props used by implementations of BaseDataSource to provide configuration.
|
| ExtendedResolverProps |
(experimental) Additional property for an AppSync resolver for data source reference.
|
| FieldOptions |
(experimental) Properties for configuring a field.
|
| GraphqlApiAttributes |
(experimental) Attributes for GraphQL imports.
|
| GraphqlApiProps |
(experimental) Properties for an AppSync GraphQL API.
|
| GraphqlTypeOptions |
(experimental) Options for GraphQL Types.
|
| HttpDataSourceOptions |
(experimental) Optional configuration for Http data sources.
|
| HttpDataSourceProps |
(experimental) Properties for an AppSync http datasource.
|
| IAppsyncFunction |
(experimental) Interface for AppSync Functions.
|
| IAppsyncFunction.Jsii$Default |
Internal default implementation for
IAppsyncFunction. |
| IField |
(experimental) A Graphql Field.
|
| IField.Jsii$Default |
Internal default implementation for
IField. |
| IGraphqlApi |
(experimental) Interface for GraphQL.
|
| IGraphqlApi.Jsii$Default |
Internal default implementation for
IGraphqlApi. |
| IIntermediateType |
(experimental) Intermediate Types are types that includes a certain set of fields that define the entirety of your schema.
|
| IIntermediateType.Jsii$Default |
Internal default implementation for
IIntermediateType. |
| IntermediateTypeOptions |
(experimental) Properties for configuring an Intermediate Type.
|
| LambdaDataSourceProps |
(experimental) Properties for an AppSync Lambda datasource.
|
| LogConfig |
(experimental) Logging configuration for AppSync.
|
| NoneDataSourceProps |
(experimental) Properties for an AppSync dummy datasource.
|
| ObjectTypeOptions |
(experimental) Properties for configuring an Object Type.
|
| OpenIdConnectConfig |
(experimental) Configuration for OpenID Connect authorization in AppSync.
|
| RdsDataSourceProps |
(experimental) Properties for an AppSync RDS datasource.
|
| ResolvableFieldOptions |
(experimental) Properties for configuring a resolvable field.
|
| ResolverProps |
(experimental) Additional property for an AppSync resolver for GraphQL API reference.
|
| SchemaOptions |
(experimental) The options for configuring a schema.
|
| UnionTypeOptions |
(experimental) Properties for configuring an Union Type.
|
| UserPoolConfig |
(experimental) Configuration for Cognito user-pools in AppSync.
|
| Enum | Description |
|---|---|
| AuthorizationType |
(experimental) enum with all possible values for AppSync authorization type.
|
| FieldLogLevel |
(experimental) log-level for fields in AppSync.
|
| Type |
(experimental) Enum containing the Types that can be used to define ObjectTypes.
|
| UserPoolDefaultAction |
(experimental) enum with all possible values for Cognito user-pool default actions.
|
---
All classes with the
Cfnprefix in this module (CFN Resources) are always stable and safe to use.
The APIs of higher level constructs in this module are experimental and under active development. They are subject to non-backward compatible changes or removal in any future version. These are not subject to the Semantic Versioning model and breaking changes will be announced in the release notes. This means that while you may use them, you may need to update your source code when upgrading to a newer version of this package.
The @aws-cdk/aws-appsync package contains constructs for building flexible
APIs that use GraphQL.
Example of a GraphQL API with AWS_IAM authorization resolving into a DynamoDb
backend data source.
GraphQL schema file schema.graphql:
type demo {
id: String!
version: String!
}
type Query {
getDemos: [ demo! ]
}
input DemoInput {
version: String!
}
type Mutation {
addDemo(input: DemoInput!): demo
}
CDK stack file app-stack.ts:
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
import software.amazon.awscdk.services.appsync.*;
import software.amazon.awscdk.services.dynamodb.*;
GraphqlApi api = new GraphqlApi(stack, "Api", new GraphqlApiProps()
.name("demo")
.schema(appsync.Schema.fromAsset(join(__dirname, "schema.graphql")))
.authorizationConfig(new AuthorizationConfig()
.defaultAuthorization(new AuthorizationMode()
.authorizationType(appsync.AuthorizationType.getIAM())))
.xrayEnabled(true));
Table demoTable = new Table(stack, "DemoTable", new TableProps()
.partitionKey(new Attribute()
.name("id")
.type(db.AttributeType.getSTRING())));
DynamoDbDataSource demoDS = api.addDynamoDbDataSource("demoDataSource", demoTable);
// Resolver for the Query "getDemos" that scans the DynamoDb table and returns the entire list.
demoDS.createResolver(new BaseResolverProps()
.typeName("Query")
.fieldName("getDemos")
.requestMappingTemplate(appsync.MappingTemplate.dynamoDbScanTable())
.responseMappingTemplate(appsync.MappingTemplate.dynamoDbResultList()));
// Resolver for the Mutation "addDemo" that puts the item into the DynamoDb table.
demoDS.createResolver(new BaseResolverProps()
.typeName("Mutation")
.fieldName("addDemo")
.requestMappingTemplate(appsync.MappingTemplate.dynamoDbPutItem(appsync.PrimaryKey.partition('id').auto(), appsync.Values.projecting("input")))
.responseMappingTemplate(appsync.MappingTemplate.dynamoDbResultItem()));
AppSync provides a data source for executing SQL commands against Amazon Aurora Serverless clusters. You can use AppSync resolvers to execute SQL statements against the Data API with GraphQL queries, mutations, and subscriptions.
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
// Create username and password secret for DB Cluster
Object secret = DatabaseSecret.Builder.create(stack, "AuroraSecret")
.username("clusteradmin")
.build();
// The VPC to place the cluster in
Object vpc = new Vpc(stack, "AuroraVpc");
// Create the serverless cluster, provide all values needed to customise the database.
Object cluster = ServerlessCluster.Builder.create(stack, "AuroraCluster")
.engine(rds.DatabaseClusterEngine.getAURORA_MYSQL())
.vpc(vpc)
.credentials(Map.of("username", "clusteradmin"))
.clusterIdentifier("db-endpoint-test")
.defaultDatabaseName("demos")
.build();
// Build a data source for AppSync to access the database.
Object rdsDS = api.addRdsDataSource("rds", cluster, secret, "demos");
// Set up a resolver for an RDS query.
rdsDS.createResolver(Map.of(
"typeName", "Query",
"fieldName", "getDemosRds",
"requestMappingTemplate", MappingTemplate.fromString("\n {\n \"version\": \"2018-05-29\",\n \"statements\": [\n \"SELECT * FROM demos\"\n ]\n }\n "),
"responseMappingTemplate", MappingTemplate.fromString("\n $util.rds.toJsonObject($ctx.result)\n ")));
// Set up a resolver for an RDS mutation.
rdsDS.createResolver(Map.of(
"typeName", "Mutation",
"fieldName", "addDemoRds",
"requestMappingTemplate", MappingTemplate.fromString("\n {\n \"version\": \"2018-05-29\",\n \"statements\": [\n \"INSERT INTO demos VALUES (:id, :version)\",\n \"SELECT * WHERE id = :id\"\n ],\n \"variableMap\": {\n \":id\": $util.toJson($util.autoId()),\n \":version\": $util.toJson($ctx.args.version)\n }\n }\n "),
"responseMappingTemplate", MappingTemplate.fromString("\n $util.rds.toJsonObject($ctx.result)\n ")));
GraphQL schema file schema.graphql:
type job {
id: String!
version: String!
}
input DemoInput {
version: String!
}
type Mutation {
callStepFunction(input: DemoInput!): job
}
GraphQL request mapping template request.vtl:
{
"version": "2018-05-29",
"method": "POST",
"resourcePath": "/",
"params": {
"headers": {
"content-type": "application/x-amz-json-1.0",
"x-amz-target":"AWSStepFunctions.StartExecution"
},
"body": {
"stateMachineArn": "<your step functions arn>",
"input": "{ \"id\": \"$context.arguments.id\" }"
}
}
}
GraphQL response mapping template response.vtl:
{
"id": "${context.result.id}"
}
CDK stack file app-stack.ts:
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
import software.amazon.awscdk.services.appsync.*;
GraphqlApi api = new GraphqlApi(scope, "api", new GraphqlApiProps()
.name("api")
.schema(appsync.Schema.fromFile(join(__dirname, "schema.graphql"))));
HttpDataSource httpDs = api.addHttpDataSource("ds", "https://states.amazonaws.com", new HttpDataSourceOptions()
.name("httpDsWithStepF")
.description("from appsync to StepFunctions Workflow")
.authorizationConfig(new AwsIamConfig()
.signingRegion("us-east-1")
.signingServiceName("states")));
httpDs.createResolver(new BaseResolverProps()
.typeName("Mutation")
.fieldName("callStepFunction")
.requestMappingTemplate(MappingTemplate.fromFile("request.vtl"))
.responseMappingTemplate(MappingTemplate.fromFile("response.vtl")));
Every GraphQL Api needs a schema to define the Api. CDK offers appsync.Schema
for static convenience methods for various types of schema declaration: code-first
or schema-first.
When declaring your GraphQL Api, CDK defaults to a code-first approach if the
schema property is not configured.
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
Object api = GraphqlApi.Builder.create(stack, "api").name("myApi").build();
CDK will declare a Schema class that will give your Api access functions to
define your schema code-first: addType, addObjectType, addToSchema, etc.
You can also declare your Schema class outside of your CDK stack, to define
your schema externally.
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
Object schema = new Schema();
schema.addObjectType("demo", Map.of(
"definition", Map.of("id", appsync.GraphqlType.id())));
Object api = GraphqlApi.Builder.create(stack, "api")
.name("myApi")
.schema(schema)
.build();
See the code-first schema section for more details.
You can define your GraphQL Schema from a file on disk. For convenience, use
the appsync.Schema.fromAsset to specify the file representing your schema.
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
Object api = appsync.GraphqlApi(stack, "api", Map.of(
"name", "myApi",
"schema", appsync.Schema.fromAsset(join(__dirname, "schema.graphl"))));
Any GraphQL Api that has been created outside the stack can be imported from
another stack into your CDK app. Utilizing the fromXxx function, you have
the ability to add data sources and resolvers through a IGraphqlApi interface.
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
Object importedApi = appsync.GraphqlApi.fromGraphqlApiAttributes(stack, "IApi", Map.of(
"graphqlApiId", api.getApiId(),
"graphqlArn", api.getArn()));
importedApi.addDynamoDbDataSource("TableDataSource", table);
If you don't specify graphqlArn in fromXxxAttributes, CDK will autogenerate
the expected arn for the imported api, given the apiId. For creating data
sources and resolvers, an apiId is sufficient.
When using AWS_IAM as the authorization type for GraphQL API, an IAM Role
with correct permissions must be used for access to API.
When configuring permissions, you can specify specific resources to only be
accessible by IAM authorization. For example, if you want to only allow mutability
for IAM authorized access you would configure the following.
In schema.graphql:
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
type Mutation {
updateExample(...): ...@aws_iam
In IAM:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"appsync:GraphQL"
],
"Resource": [
"arn:aws:appsync:REGION:ACCOUNT_ID:apis/GRAPHQL_ID/types/Mutation/fields/updateExample"
]
}
]
}
See documentation for more details.
To make this easier, CDK provides grant API.
Use the grant function for more granular authorization.
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
Object role = Role.Builder.create(stack, "Role")
.assumedBy(new ServicePrincipal("lambda.amazonaws.com"))
.build();
Object api = GraphqlApi.Builder.create(stack, "API")
.definition(definition)
.build();
api.grant(role, appsync.IamResource.custom("types/Mutation/fields/updateExample"), "appsync:GraphQL");
In order to use the grant functions, you need to use the class IamResource.
IamResource.custom(...arns) permits custom ARNs and requires an argument.IamResouce.ofType(type, ...fields) permits ARNs for types and their fields.IamResource.all() permits ALL resources.
Alternatively, you can use more generic grant functions to accomplish the same usage.
These include:
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
// For generic types
api.grantMutation(role, "updateExample");
// For custom types and granular design
api.grant(role, appsync.IamResource.ofType("Mutation", "updateExample"), "appsync:GraphQL");
AppSync Functions are local functions that perform certain operations onto a backend data source. Developers can compose operations (Functions) and execute them in sequence with Pipeline Resolvers.
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
Object appsyncFunction = AppsyncFunction.Builder.create(stack, "function")
.name("appsync_function")
.api(api)
.dataSource(apiDataSource)
.requestMappingTemplate(appsync.MappingTemplate.fromFile("request.vtl"))
.responseMappingTemplate(appsync.MappingTemplate.fromFile("response.vtl"))
.build();
AppSync Functions are used in tandem with pipeline resolvers to compose multiple operations.
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
Object pipelineResolver = Resolver.Builder.create(stack, "pipeline")
.name("pipeline_resolver")
.api(api)
.dataSource(apiDataSource)
.requestMappingTemplate(appsync.MappingTemplate.fromFile("beforeRequest.vtl"))
.pipelineConfig(asList(appsyncFunction))
.responseMappingTemplate(appsync.MappingTemplate.fromFile("afterResponse.vtl"))
.build();
Learn more about Pipeline Resolvers and AppSync Functions here.
CDK offers the ability to generate your schema in a code-first approach. A code-first approach offers a developer workflow with:
The code-first approach allows for dynamic schema generation. You can generate your schema based on variables and templates to reduce code duplication.
To showcase the code-first approach. Let's try to model the following schema segment.
interface Node {
id: String
}
type Query {
allFilms(after: String, first: Int, before: String, last: Int): FilmConnection
}
type FilmNode implements Node {
filmName: String
}
type FilmConnection {
edges: [FilmEdge]
films: [Film]
totalCount: Int
}
type FilmEdge {
node: Film
cursor: String
}
Above we see a schema that allows for generating paginated responses. For example,
we can query allFilms(first: 100) since FilmConnection acts as an intermediary
for holding FilmEdges we can write a resolver to return the first 100 films.
In a separate file, we can declare our scalar types: scalar-types.ts.
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826 import software.amazon.awscdk.services.appsync.GraphqlType; Object string = appsync.GraphqlType.string(); Object int = appsync.GraphqlType.int();
In another separate file, we can declare our object types and related functions.
We will call this file object-types.ts and we will have created it in a way that
allows us to generate other XxxConnection and XxxEdges in the future.
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
Object pluralize = require("pluralize");
import scalar.types.ts.*;
import software.amazon.awscdk.services.appsync.*;
Map<String, Object> args = Map.of(
"after", scalar.getString(),
"first", scalar.getInt(),
"before", scalar.getString(),
"last", scalar.getInt());
InterfaceType Node = InterfaceType.Builder.create("Node")Map.of(
"definition", Map.of("id", scalar.getString()));
Object FilmNode = implementInterface.Builder.create("FilmNode")
.interfaceTypes(asList(Node))
.definition(Map.of("filmName", scalar.getString()))
.build();
public void generateEdgeAndConnection(ObjectType base) {
ObjectType edge = new ObjectType(String.format("%sEdge", base.getName()), new ObjectTypeOptions()
.definition(Map.of("node", base.attribute(), "cursor", scalar.getString())));
ObjectType connection = new ObjectType(String.format("%sConnection", base.getName()), new ObjectTypeOptions()
.definition(Map.of(
"edges", edges.attribute(Map.of("isList", true)),
pluralize(base.getName()), base.attribute(new BaseTypeOptions().isList(true)),
"totalCount", scalar.getInt())));return Map.of("edge", edge, "connection", connection)
}
Finally, we will go to our cdk-stack and combine everything together
to generate our schema.
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
import software.amazon.awscdk.services.appsync.*;
import object.types.*;
GraphqlApi api = new GraphqlApi(stack, "Api", new GraphqlApiProps()
.name("demo"));
this.objectTypes = asList(schema.getNode(), schema.getFilm());
Object filmConnections = schema.generateEdgeAndConnection(schema.getFilm());
api.addQuery("allFilms", new ResolvableField(new ResolvableFieldOptions()
.returnType(filmConnections.connection.attribute())
.args(schema.getArgs())
.dataSource(dummyDataSource)
.requestMappingTemplate(dummyRequest)
.responseMappingTemplate(dummyResponse)));
this.objectTypes.map((t) => api.addType(t));
Object.keys(filmConnections).forEach((key) => api.addType(filmConnections[key]));
Notice how we can utilize the generateEdgeAndConnection function to generate
Object Types. In the future, if we wanted to create more Object Types, we can simply
create the base Object Type (i.e. Film) and from there we can generate its respective
Connections and Edges.
Check out a more in-depth example here.
One of the benefits of GraphQL is its strongly typed nature. We define the types within an object, query, mutation, interface, etc. as GraphQL Types.
GraphQL Types are the building blocks of types, whether they are scalar, objects, interfaces, etc. GraphQL Types can be:
demo from the example above)
More concretely, GraphQL Types are simply the types appended to variables.
Referencing the object type Demo in the previous example, the GraphQL Types
is String! and is applied to both the names id and version.
Directives are attached to a field or type and affect the execution of queries,
mutations, and types. With AppSync, we use Directives to configure authorization.
CDK provides static functions to add directives to your Schema.
Directive.iam() sets a type or field's authorization to be validated through IamDirective.apiKey() sets a type or field's authorization to be validated through a Api KeyDirective.oidc() sets a type or field's authorization to be validated through OpenID ConnectDirective.cognito(...groups: string[]) sets a type or field's authorization to be validated
through Cognito User Pools
groups the name of the cognito groups to give accessTo learn more about authorization and directives, read these docs here.
While GraphqlType is a base implementation for GraphQL fields, we have abstractions
on top of GraphqlType that provide finer grain support.
Field extends GraphqlType and will allow you to define arguments. Interface Types are not resolvable and this class will allow you to define arguments,
but not its resolvers.
For example, if we want to create the following type:
type Node {
test(argument: string): String
}
The CDK code required would be:
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
Object field = Field.Builder.create()
.returnType(appsync.GraphqlType.string())
.args(Map.of(
"argument", appsync.GraphqlType.string()))
.build();
Object type = InterfaceType.Builder.create("Node")
.definition(Map.of("test", field))
.build();
ResolvableField extends Field and will allow you to define arguments and its resolvers.
Object Types can have fields that resolve and perform operations on
your backend.
You can also create resolvable fields for object types.
type Info {
node(id: String): String
}
The CDK code required would be:
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
Object info = ObjectType.Builder.create("Info")
.definition(Map.of(
"node", ResolvableField.Builder.create()
.returnType(appsync.GraphqlType.string())
.args(Map.of(
"id", appsync.GraphqlType.string()))
.dataSource(api.addNoneDataSource("none"))
.requestMappingTemplate(dummyRequest)
.responseMappingTemplate(dummyResponse)
.build()))
.build();
To nest resolvers, we can also create top level query types that call upon other types. Building off the previous example, if we want the following graphql type definition:
type Query {
get(argument: string): Info
}
The CDK code required would be:
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
Object query = ObjectType.Builder.create("Query")
.definition(Map.of(
"get", ResolvableField.Builder.create()
.returnType(appsync.GraphqlType.string())
.args(Map.of(
"argument", appsync.GraphqlType.string()))
.dataSource(api.addNoneDataSource("none"))
.requestMappingTemplate(dummyRequest)
.responseMappingTemplate(dummyResponse)
.build()))
.build();
Learn more about fields and resolvers here.
Intermediate Types are defined by Graphql Types and Fields. They have a set of defined fields, where each field corresponds to another type in the system. Intermediate Types will be the meat of your GraphQL Schema as they are the types defined by you.
Intermediate Types include:
Interface Types are abstract types that define the implementation of other intermediate types. They are useful for eliminating duplication and can be used to generate Object Types with less work.
You can create Interface Types externally.
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
Object node = InterfaceType.Builder.create("Node")
.definition(Map.of(
"id", appsync.GraphqlType.string(Map.of("isRequired", true))))
.build();
To learn more about Interface Types, read the docs here.
Object Types are types that you declare. For example, in the code-first example
the demo variable is an Object Type. Object Types are defined by
GraphQL Types and are only usable when linked to a GraphQL Api.
You can create Object Types in three ways:
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
Object api = GraphqlApi.Builder.create(stack, "Api")
.name("demo")
.build();
Object demo = ObjectType.Builder.create("Demo")
.defintion(Map.of(
"id", appsync.GraphqlType.string(Map.of("isRequired", true)),
"version", appsync.GraphqlType.string(Map.of("isRequired", true))))
.build();
api.addType(object);
This method allows for reusability and modularity, ideal for larger projects. For example, imagine moving all Object Type definition outside the stack.
scalar-types.ts - a file for scalar type definitions
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
Object required_string = appsync.GraphqlType.string(Map.of("isRequired", true));
object-types.ts - a file for object type definitions
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
import scalar.types.required_string;
Object demo = ObjectType.Builder.create("Demo")
.defintion(Map.of(
"id", required_string,
"version", required_string))
.build();
cdk-stack.ts - a file containing our cdk stack
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826 import object.types.demo; api.addType(demo);
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
Object node = InterfaceType.Builder.create("Node")
.definition(Map.of(
"id", appsync.GraphqlType.string(Map.of("isRequired", true))))
.build();
Object demo = ObjectType.Builder.create("Demo")
.interfaceTypes(asList(node))
.defintion(Map.of(
"version", appsync.GraphqlType.string(Map.of("isRequired", true))))
.build();
This method allows for reusability and modularity, ideal for reducing code duplication.
To learn more about Object Types, read the docs here.
Enum Types are a special type of Intermediate Type. They restrict a particular set of allowed values for other Intermediate Types.
enum Episode {
NEWHOPE
EMPIRE
JEDI
}
This means that wherever we use the type Episode in our schema, we expect it to be exactly one of NEWHOPE, EMPIRE, or JEDI.
The above GraphQL Enumeration Type can be expressed in CDK as the following:
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
Object episode = EnumType.Builder.create("Episode")
.definition(asList("NEWHOPE", "EMPIRE", "JEDI"))
.build();
api.addType(episode);
To learn more about Enum Types, read the docs here.
Input Types are special types of Intermediate Types. They give users an easy way to pass complex objects for top level Mutation and Queries.
input Review {
stars: Int!
commentary: String
}
The above GraphQL Input Type can be expressed in CDK as the following:
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
Object review = InputType.Builder.create("Review")
.definition(Map.of(
"stars", GraphqlType.int(Map.of("isRequired", true)),
"commentary", GraphqlType.string()))
.build();
api.addType(review);
To learn more about Input Types, read the docs here.
Union Types are a special type of Intermediate Type. They are similar to Interface Types, but they cannot specify any common fields between types.
Note: the fields of a union type need to be Object Types. In other words, you
can't create a union type out of interfaces, other unions, or inputs.
union Search = Human | Droid | Starship
The above GraphQL Union Type encompasses the Object Types of Human, Droid and Starship. It can be expressed in CDK as the following:
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
Object string = appsync.GraphqlType.string();
Object human = ObjectType.Builder.create("Human").definition(Map.of("name", string)).build();
Object droid = ObjectType.Builder.create("Droid").definition(Map.of("name", string)).build();
Object starship = ObjectType.Builder.create("Starship").definition(Map.of("name", string)).build();
Object search = UnionType.Builder.create("Search")
.definition(asList(human, droid, starship))
.build();
api.addType(search);
To learn more about Union Types, read the docs here.
Every schema requires a top level Query type. By default, the schema will look
for the Object Type named Query. The top level Query is the only exposed
type that users can access to perform GET operations on your Api.
To add fields for these queries, we can simply run the addQuery function to add
to the schema's Query type.
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
Object string = appsync.GraphqlType.string();
Object int = appsync.GraphqlType.int();
api.addQuery("allFilms", ResolvableField.Builder.create()
.returnType(filmConnection.attribute())
.args(Map.of("after", string, "first", int, "before", string, "last", int))
.dataSource(api.addNoneDataSource("none"))
.requestMappingTemplate(dummyRequest)
.responseMappingTemplate(dummyResponse)
.build());
To learn more about top level operations, check out the docs here.
Every schema can have a top level Mutation type. By default, the schema will look
for the ObjectType named Mutation. The top level Mutation Type is the only exposed
type that users can access to perform mutable operations on your Api.
To add fields for these mutations, we can simply run the addMutation function to add
to the schema's Mutation type.
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
Object string = appsync.GraphqlType.string();
Object int = appsync.GraphqlType.int();
api.addMutation("addFilm", ResolvableField.Builder.create()
.returnType(film.attribute())
.args(Map.of("name", string, "film_number", int))
.dataSource(api.addNoneDataSource("none"))
.requestMappingTemplate(dummyRequest)
.responseMappingTemplate(dummyResponse)
.build());
To learn more about top level operations, check out the docs here.
Every schema can have a top level Subscription type. The top level Subscription Type
is the only exposed type that users can access to invoke a response to a mutation. Subscriptions
notify users when a mutation specific mutation is called. This means you can make any data source
real time by specify a GraphQL Schema directive on a mutation.
Note: The AWS AppSync client SDK automatically handles subscription connection management.
To add fields for these subscriptions, we can simply run the addSubscription function to add
to the schema's Subscription type.
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
api.addSubscription("addedFilm", ResolvableField.Builder.create()
.returnType(film.attribute())
.args(Map.of("id", appsync.GraphqlType.id(Map.of("isRequired", true))))
.directive(asList(appsync.Directive.subscribe("addFilm")))
.build());
To learn more about top level operations, check out the docs here.
Copyright © 2021. All rights reserved.