Package: cdklabs.appsync-utils
AWS CDK AppSync UtilitiesThis package contains various utilities for definining GraphQl Apis via AppSync using theaws-cdk.Code First Schema DefinitionCodeFirstSchemaoffers the ability to generate your schema in a code-first
approach. A code-first approach offers a developer workflow with:modularity: organizing schema type definitions into different filesreusability: removing boilerplate/repetitive codeconsistency: resolvers and schema definition will always be syncedThe code-first approach allows fordynamicschema generation. You can
generate your schema based on variables and templates to reduce code
duplication.import{GraphqlApi}from'@aws-cdk/aws-appsync-alpha';import{CodeFirstSchema}from'awscdk-appsync-utils';constschema=newCodeFirstSchema();constapi=newGraphqlApi(this,'api',{name:'myApi',schema});schema.addType(newObjectType('demo',{definition:{id:GraphqlType.id()},}));Code-First ExampleTo 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 queryallFilms(first: 100)sinceFilmConnectionacts as an intermediary
for holdingFilmEdgeswe can write a resolver to return the first 100 films.In a separate file, we can declare our object types and related functions.
We will call this fileobject-types.tsand we will have created it in a way that
allows us to generate otherXxxConnectionandXxxEdgesin the future.import{GraphqlType,InterfaceType,ObjectType}from'awscdk-appsync-utils';constpluralize=require('pluralize');exportconstargs={after:GraphqlType.string(),first:GraphqlType.int(),before:GraphqlType.string(),last:GraphqlType.int(),};exportconstNode=newInterfaceType('Node',{definition:{id:GraphqlType.string()}});exportconstFilmNode=newObjectType('FilmNode',{interfaceTypes:[Node],definition:{filmName:GraphqlType.string()}});exportfunctiongenerateEdgeAndConnection(base:ObjectType){constedge=newObjectType(`${base.name}Edge`,{definition:{node:base.attribute(),cursor:GraphqlType.string()}});constconnection=newObjectType(`${base.name}Connection`,{definition:{edges:edge.attribute({isList:true}),[pluralize(base.name)]:base.attribute({isList:true}),totalCount:GraphqlType.int(),}});return{edge:edge,connection:connection};}Finally, we will go to ourcdk-stackand combine everything together
to generate our schema.declareconstdummyRequest:appsync.MappingTemplate;declareconstdummyResponse:appsync.MappingTemplate;constapi=newappsync.GraphqlApi(this,'Api',{name:'demo',});constobjectTypes=[Node,FilmNode];constfilmConnections=generateEdgeAndConnection(FilmNode);api.addQuery('allFilms',newResolvableField({returnType:filmConnections.connection.attribute(),args:args,dataSource:api.addNoneDataSource('none'),requestMappingTemplate:dummyRequest,responseMappingTemplate:dummyResponse,}));api.addType(Node);api.addType(FilmNode);api.addType(filmConnections.edge);api.addType(filmConnections.connection);Notice how we can utilize thegenerateEdgeAndConnectionfunction 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 respectiveConnectionsandEdges.Check out a more in-depth examplehere.GraphQL TypesOne of the benefits of GraphQL is its strongly typed nature. We define the
types within an object, query, mutation, interface, etc. asGraphQL Types.GraphQL Types are the building blocks of types, whether they are scalar, objects,
interfaces, etc. GraphQL Types can be:Scalar Types: Id, Int, String, AWSDate, etc.Object Types: types that you generate (i.e.demofrom the example above)Interface Types: abstract types that define the base implementation of other
Intermediate TypesMore concretely, GraphQL Types are simply the types appended to variables.
Referencing the object typeDemoin the previous example, the GraphQL Types
isString!and is applied to both the namesidandversion.DirectivesDirectivesare attached to a field or type and affect the execution of queries,
mutations, and types. With AppSync, we useDirectivesto configure authorization.
Appsync utils provide static functions to add directives to your CodeFirstSchema.Directive.iam()sets a type or field's authorization to be validated throughIamDirective.apiKey()sets a type or field's authorization to be validated through aApi KeyDirective.oidc()sets a type or field's authorization to be validated throughOpenID ConnectDirective.cognito(...groups: string[])sets a type or field's authorization to be validated
throughCognito User Poolsgroupsthe name of the cognito groups to give accessTo learn more about authorization and directives, read these docshere.Field and Resolvable FieldsWhileGraphqlTypeis a base implementation for GraphQL fields, we have abstractions
on top ofGraphqlTypethat provide finer grain support.FieldFieldextendsGraphqlTypeand will allow you to define arguments.Interface Typesare 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:import{Field,GraphqlType,InterfaceType}from'awscdk-appsync-utils';constfield=newField({returnType:GraphqlType.string(),args:{argument:GraphqlType.string(),},});consttype=newInterfaceType('Node',{definition:{test:field},});Resolvable FieldsResolvableFieldextendsFieldand will allow you to define arguments and its resolvers.Object Typescan 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:declareconstapi:appsync.GraphqlApi;declareconstdummyRequest:appsync.MappingTemplate;declareconstdummyResponse:appsync.MappingTemplate;constinfo=newObjectType('Info',{definition:{node:newResolvableField({returnType:GraphqlType.string(),args:{id:GraphqlType.string(),},dataSource:api.addNoneDataSource('none'),requestMappingTemplate:dummyRequest,responseMappingTemplate:dummyResponse,}),},});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:declareconstapi:appsync.GraphqlApi;declareconstdummyRequest:appsync.MappingTemplate;declareconstdummyResponse:appsync.MappingTemplate;constquery=newObjectType('Query',{definition:{get:newResolvableField({returnType:GraphqlType.string(),args:{argument:GraphqlType.string(),},dataSource:api.addNoneDataSource('none'),requestMappingTemplate:dummyRequest,responseMappingTemplate:dummyResponse,}),},});Learn more about fields and resolvershere.Intermediate TypesIntermediate 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 TypesObject TypesEnum TypesInput TypesUnion TypesInterface TypesInterface Typesare 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 Typesexternally.constnode=newInterfaceType('Node',{definition:{id:GraphqlType.string({isRequired:true}),},});To learn more aboutInterface Types, read the docshere.Object TypesObject Typesare types that you declare. For example, in thecode-first examplethedemovariable is anObject Type.Object Typesare defined by
GraphQL Types and are only usable when linked to a GraphQL Api.You can create Object Types in two ways:Object Types can be createdexternally.constschema=newCodeFirstSchema();constapi=newappsync.GraphqlApi(this,'Api',{name:'demo',schema,});constdemo=newObjectType('Demo',{definition:{id:GraphqlType.string({isRequired:true}),version:GraphqlType.string({isRequired:true}),},});schema.addType(demo);This method allows for reusability and modularity, ideal for larger projects.
For example, imagine moving all Object Type definition outside the stack.object-types.ts- a file for object type definitionsimport{ObjectType,GraphqlType}from'awscdk-appsync-utils';exportconstdemo=newObjectType('Demo',{definition:{id:GraphqlType.string({isRequired:true}),version:GraphqlType.string({isRequired:true}),},});cdk-stack.ts- a file containing our cdk stackdeclareconstschema:CodeFirstSchema;schema.addType(demo);Object Types can be createdexternallyfrom an Interface Type.constnode=newInterfaceType('Node',{definition:{id:GraphqlType.string({isRequired:true}),},});constdemo=newObjectType('Demo',{interfaceTypes:[node],definition:{version:GraphqlType.string({isRequired:true}),},});This method allows for reusability and modularity, ideal for reducing code duplication.To learn more aboutObject Types, read the docshere.Enum TypesEnum Typesare 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:declareconstapi:GraphqlApi;constepisode=newEnumType('Episode',{definition:['NEWHOPE','EMPIRE','JEDI',],});api.addType(episode);To learn more aboutEnum Types, read the docshere.Input TypesInput Typesare 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:declareconstapi:appsync.GraphqlApi;constreview=newInputType('Review',{definition:{stars:GraphqlType.int({isRequired:true}),commentary:GraphqlType.string(),},});api.addType(review);To learn more aboutInput Types, read the docshere.Union TypesUnion Typesare 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 beObject Types. In other words, you
can't create a union type out of interfaces, other unions, or inputs.union Search = Human | Droid | StarshipThe above GraphQL Union Type encompasses the Object Types of Human, Droid and Starship. It
can be expressed in CDK as the following:declareconstapi:appsync.GraphqlApi;conststring=GraphqlType.string();consthuman=newObjectType('Human',{definition:{name:string}});constdroid=newObjectType('Droid',{definition:{name:string}});conststarship=newObjectType('Starship',{definition:{name:string}}););constsearch=newUnionType('Search',{definition:[human,droid,starship],});api.addType(search);To learn more aboutUnion Types, read the docshere.QueryEvery schema requires a top level Query type. By default, the schema will look
for theObject TypenamedQuery. The top levelQueryis theonlyexposed
type that users can access to performGEToperations on your Api.To add fields for these queries, we can simply run theaddQueryfunction to add
to the schema'sQuerytype.declareconstapi:appsync.GraphqlApi;declareconstfilmConnection:InterfaceType;declareconstdummyRequest:appsync.MappingTemplate;declareconstdummyResponse:appsync.MappingTemplate;conststring=GraphqlType.string();constint=GraphqlType.int();api.addQuery('allFilms',newResolvableField({returnType:filmConnection.attribute(),args:{after:string,first:int,before:string,last:int},dataSource:api.addNoneDataSource('none'),requestMappingTemplate:dummyRequest,responseMappingTemplate:dummyResponse,}));To learn more about top level operations, check out the docshere.MutationEvery schemacanhave a top level Mutation type. By default, the schema will look
for theObjectTypenamedMutation. The top levelMutationType is the only exposed
type that users can access to performmutableoperations on your Api.To add fields for these mutations, we can simply run theaddMutationfunction to add
to the schema'sMutationtype.declareconstapi:appsync.GraphqlApi;declareconstfilmNode:ObjectType;declareconstdummyRequest:appsync.MappingTemplate;declareconstdummyResponse:appsync.MappingTemplate;conststring=GraphqlType.string();constint=GraphqlType.int();api.addMutation('addFilm',newResolvableField({returnType:filmNode.attribute(),args:{name:string,film_number:int},dataSource:api.addNoneDataSource('none'),requestMappingTemplate:dummyRequest,responseMappingTemplate:dummyResponse,}));To learn more about top level operations, check out the docshere.SubscriptionEvery schemacanhave a top level Subscription type. The top levelSubscriptionType
is the only exposed type that users can access to invoke a response to a mutation.Subscriptionsnotify 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 theaddSubscriptionfunction to add
to the schema'sSubscriptiontype.declareconstapi:appsync.GraphqlApi;declareconstfilm:InterfaceType;api.addSubscription('addedFilm',newField({returnType:film.attribute(),args:{id:GraphqlType.id({isRequired:true})},directives:[Directive.subscribe('addFilm')],}));To learn more about top level operations, check out the docshere.Merge Source API to Merged API Using A Custom ResourceThe SourceApiAssociationMergeOperation construct provides the ability to merge a source api to a Merged Api
and invoke a merge within a Cloudformation custom resource. If the merge operation fails with a conflict, the
Cloudformation update will fail and rollback the changes to the source API in the stack.import*ascdkfrom'aws-cdk-lib';constsourceApi1ToMerge=newappsync.GraphqlApi(this,'FirstSourceAPI',{name:'FirstSourceAPI',definition:appsync.Definition.fromFile(path.join(__dirname,'appsync.merged-api-1.graphql')),});constsourceApi2ToMerge=newappsync.GraphqlApi(this,'SecondSourceAPI',{name:'SecondSourceAPI',definition:appsync.Definition.fromFile(path.join(__dirname,'appsync.merged-api-2.graphql')),});constremoteMergedApi=appsync.GraphqlApi.fromGraphqlApiAttributes(this,'ImportedMergedApi',{graphqlApiId:'MyApiId',graphqlApiArn:'MyApiArn',});constremoteExecutionRole=iam.Role.fromRoleArn(this,'ExecutionRole','arn:aws:iam::ACCOUNT:role/MyExistingRole');constassociation1=newappsync.SourceApiAssociation(this,'SourceApiAssociation1',{sourceApi:sourceApi1ToMerge,mergedApi:remoteMergedApi,mergeType:appsync.MergeType.MANUAL_MERGE,mergedApiExecutionRole:remoteExecutionRole,});constassociation2=newappsync.SourceApiAssociation(this,'SourceApiAssociation2',{sourceApi:sourceApi2ToMerge,mergedApi:remoteMergedApi,mergeType:appsync.MergeType.MANUAL_MERGE,mergedApiExecutionRole:remoteExecutionRole,});//Theversionidcanbeanyidentifierdefinedbythedeveloper.Changingtheversionidentifierallowsyoutocontrol//whetheramergeoperationwilltakeplaceduringdeployment.SourceApiAssociationMergeOperation(this,'MergeOperation1',{sourceApiAssociation:association1,versionIdentifier:'1',});//Optionally,youcanaddthealwaysMergeOnStackUpdateflaginsteadwhichwillensurethatthemergeoperationoccurs//duringeverystackupdate,regardlessiftherewasachangeornot.Notethatthismayleadtomergeoperationsthat//donotactuallychangetheMergedAPI.SourceApiAssociationMergeOperation(this,'MergeOperation2',{sourceApiAssociation:association2,alwaysMergeOnStackUpdate:true,});ContributingThis library leans towards high level and experimental features for appsync cdk users. If you have an idea for additional utilities please create an issue describing the feature.SeeCONTRIBUTINGfor more information.LicenseThis project is licensed under the Apache-2.0 License.