AWS AppSync 构造库
AWS CDK v1在2023-06-01上达到了支持结束. 此软件包不再更新,用户应该迁移到 AWS CDK v2.
关于如何移徙的更多信息,请参见: 移动到 AWS CDK v2 指南。 。 。 .
这个 @aws-cdk/aws-appsync 软件包中包含用于灵活建筑的构造
使用 GraphQL 的 API .
import * as appsync from '@aws-cdk/aws-appsync';
示例
迪纳摩DB
图QL API 示例 AWS_IAM 授权 进入迪纳摩Db
后端数据源.
GraphQL 计划文件 schema.graphql数字 :
type demo {
id: String!
version: String!
}
type Query {
getDemos: [ demo! ]
}
input DemoInput {
version: String!
}
type Mutation {
addDemo(input: DemoInput!): demo
}
CDK 堆栈文件 app-stack.ts数字 :
const api = new appsync.GraphqlApi(this, 'Api', {
name: 'demo',
schema: appsync.Schema.fromAsset(path.join(__dirname, 'schema.graphql')),
authorizationConfig: {
defaultAuthorization: {
authorizationType: appsync.AuthorizationType.IAM,
},
},
xrayEnabled: true,
});
const demoTable = new dynamodb.Table(this, 'DemoTable', {
partitionKey: {
name: 'id',
type: dynamodb.AttributeType.STRING,
},
});
const demoDS = api.addDynamoDbDataSource('demoDataSource', demoTable);
// Resolver for the Query "getDemos" that scans the DynamoDb table and returns the entire list.
demoDS.createResolver({
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({
typeName: 'Mutation',
fieldName: 'addDemo',
requestMappingTemplate: appsync.MappingTemplate.dynamoDbPutItem(
appsync.PrimaryKey.partition('id').auto(),
appsync.Values.projecting('input'),
),
responseMappingTemplate: appsync.MappingTemplate.dynamoDbResultItem(),
});
无服务器的Aurora
AppSync 为针对Amazon Aurora执行SQL命令提供数据源 无服务器集群. 您可以使用 AppSync 解析器执行 SQL 语句 与 GraphQL 查询、 突变和订阅的 Data API 对齐.
// Create username and password secret for DB Cluster
const secret = new rds.DatabaseSecret(this, 'AuroraSecret', {
username: 'clusteradmin',
});
// The VPC to place the cluster in
const vpc = new ec2.Vpc(this, 'AuroraVpc');
// Create the serverless cluster, provide all values needed to customise the database.
const cluster = new rds.ServerlessCluster(this, 'AuroraCluster', {
engine: rds.DatabaseClusterEngine.AURORA_MYSQL,
vpc,
credentials: { username: 'clusteradmin' },
clusterIdentifier: 'db-endpoint-test',
defaultDatabaseName: 'demos',
});
// Build a data source for AppSync to access the database.
declare const api: appsync.GraphqlApi;
const rdsDS = api.addRdsDataSource('rds', cluster, secret, 'demos');
// Set up a resolver for an RDS query.
rdsDS.createResolver({
typeName: 'Query',
fieldName: 'getDemosRds',
requestMappingTemplate: appsync.MappingTemplate.fromString(`
{
"version": "2018-05-29",
"statements": [
"SELECT * FROM demos"
]
}
`),
responseMappingTemplate: appsync.MappingTemplate.fromString(`
$utils.toJson($utils.rds.toJsonObject($ctx.result)[0])
`),
});
// Set up a resolver for an RDS mutation.
rdsDS.createResolver({
typeName: 'Mutation',
fieldName: 'addDemoRds',
requestMappingTemplate: appsync.MappingTemplate.fromString(`
{
"version": "2018-05-29",
"statements": [
"INSERT INTO demos VALUES (:id, :version)",
"SELECT * WHERE id = :id"
],
"variableMap": {
":id": $util.toJson($util.autoId()),
":version": $util.toJson($ctx.args.version)
}
}
`),
responseMappingTemplate: appsync.MappingTemplate.fromString(`
$utils.toJson($utils.rds.toJsonObject($ctx.result)[1][0])
`),
});
HTTP 终点
GraphQL 计划文件 schema.graphql数字 :
type job {
id: String!
version: String!
}
input DemoInput {
version: String!
}
type Mutation {
callStepFunction(input: DemoInput!): job
}
GraphQL 请求绘图模板 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\" }"
}
}
}
图QL 响应映射模板 response.vtl数字 :
{
"id": "${context.result.id}"
}
CDK 堆栈文件 app-stack.ts数字 :
const api = new appsync.GraphqlApi(this, 'api', {
name: 'api',
schema: appsync.Schema.fromAsset(path.join(__dirname, 'schema.graphql')),
});
const httpDs = api.addHttpDataSource(
'ds',
'https://states.amazonaws.com',
{
name: 'httpDsWithStepF',
description: 'from appsync to StepFunctions Workflow',
authorizationConfig: {
signingRegion: 'us-east-1',
signingServiceName: 'states',
}
}
);
httpDs.createResolver({
typeName: 'Mutation',
fieldName: 'callStepFunction',
requestMappingTemplate: appsync.MappingTemplate.fromFile('request.vtl'),
responseMappingTemplate: appsync.MappingTemplate.fromFile('response.vtl'),
});
亚马逊 OpenSearch 服务
AppSync 已建立支持 Amazon OpenSearch Service( 继承到 Amazon) Elasticsearch Service),来自通过您的 AWS 账户提供的域. 你们可以 使用 AppSync 解析器执行 GraphQL 操作,例如查询、突变和 订阅.
import * as opensearch from '@aws-cdk/aws-opensearchservice';
const user = new iam.User(this, 'User');
const domain = new opensearch.Domain(this, 'Domain', {
version: opensearch.EngineVersion.OPENSEARCH_1_2,
removalPolicy: RemovalPolicy.DESTROY,
fineGrainedAccessControl: { masterUserArn: user.userArn },
encryptionAtRest: { enabled: true },
nodeToNodeEncryption: true,
enforceHttps: true,
});
declare const api: appsync.GraphqlApi;
const ds = api.addOpenSearchDataSource('ds', domain);
ds.createResolver({
typeName: 'Query',
fieldName: 'getTests',
requestMappingTemplate: appsync.MappingTemplate.fromString(JSON.stringify({
version: '2017-02-28',
operation: 'GET',
path: '/id/post/_search',
params: {
headers: {},
queryString: {},
body: { from: 0, size: 50 },
},
})),
responseMappingTemplate: appsync.MappingTemplate.fromString(`[
#foreach($entry in $context.result.hits.hits)
#if( $velocityCount > 1 ) , #end
$utils.toJson($entry.get("_source"))
#end
]`),
});
自定义域名
对于很多用途,您可能想要将自定义域名与您的域名关联 图QL API. 这可以在API创建期间完成.
import * as acm from '@aws-cdk/aws-certificatemanager';
import * as route53 from '@aws-cdk/aws-route53';
const myDomainName = 'api.example.com';
const certificate = new acm.Certificate(this, 'cert', { domainName: myDomainName });
const api = new appsync.GraphqlApi(this, 'api', {
name: 'myApi',
domainName: {
certificate,
domainName: myDomainName,
},
});
// hosted zone and route53 features
declare const hostedZoneId: string;
declare const zoneName = 'example.com';
// hosted zone for adding appsync domain
const zone = route53.HostedZone.fromHostedZoneAttributes(this, `HostedZone`, {
hostedZoneId,
zoneName,
});
// create a cname to the appsync domain. will map to something like xxxx.cloudfront.net
new route53.CnameRecord(this, `CnameApiRecord`, {
recordName: 'api',
zone,
domainName: myDomainName,
});
司马
每个图QL Api 需要一个计划来定义 Api。 CDK 提议 appsync.Schema
用于各类化学申报的静态方便方法:代码-第一
或先计划.
代码一
在声明您的 GraphQL Api 时, CDK 默认为代码第一方法, 如果
schema 未配置属性.
const api = new appsync.GraphqlApi(this, 'api', { name: 'myApi' });
CDK 将声明 Schema 类,该类将给您的 Api 访问功能
定义您的方案代码: addType, (中文(简体) ), addToSchema等 (中文(简体) ).
也可以宣布为 Schema cDK 堆栈外的类,以定义
你的外在计划.
const schema = new appsync.Schema();
schema.addType(new appsync.ObjectType('demo', {
definition: { id: appsync.GraphqlType.id() },
}));
const api = new appsync.GraphqlApi(this, 'api', {
name: 'myApi',
schema,
});
见 代码第一计划 详细情况.
司马一等座
您可以从磁盘上的文件定义您的图形QL Schema 。 为方便起见
页:1 appsync.Schema.fromAsset 以指定代表您的计划的文件.
const api = new appsync.GraphqlApi(this, 'api', {
name: 'myApi',
schema: appsync.Schema.fromAsset(path.join(__dirname, 'schema.graphl')),
});
进口
任意图形QL 堆栈外已创建的 Api 可以导入自
另一个堆入您的 CDK 应用程序。 利用 fromXxx 函数,您有
通过数据源和解析器 IGraphqlApi 接口.
declare const api: appsync.GraphqlApi;
declare const table: dynamodb.Table;
const importedApi = appsync.GraphqlApi.fromGraphqlApiAttributes(this, 'IApi', {
graphqlApiId: api.apiId,
graphqlApiArn: api.arn,
});
importedApi.addDynamoDbDataSource('TableDataSource', table);
如果你不说明 graphqlArn 内 fromXxxAttributes,CDK 将自动生成
预想数 arn 用于导入的 api,考虑到 apiId。用于创建数据
来源和解决者,a apiId 足够了.
授权
GraphQL API有多种授权类型,以适应不同的 访问使用案例。 它们是:
- API 密钥( R)
AuthorizationType.API_KEY(中文(简体) ) - 亚马逊·科尼托用户池(英语:Amazon Cognto Users pools (
AuthorizationType.USER_POOL(中文(简体) ) - 打开ID 连接( O)
AuthorizationType.OPENID_CONNECT(中文(简体) ) - AWS 身份和访问管理
AuthorizationType.AWS_IAM(中文(简体) ) - AWS 兰布达( Lambda)
AuthorizationType.AWS_LAMBDA(中文(简体) )
这些类型可以在单个API中同时使用,允许不同类型的客户端使用 访问数据。 当指定授权类型时,也可以指定相应的类型 授权模式以完成定义您的授权 。 例如, 这是一个 GraphQL API aWS蓝巴达授权.
import * as lambda from '@aws-cdk/aws-lambda';
declare const authFunction: lambda.Function;
new appsync.GraphqlApi(this, 'api', {
name: 'api',
schema: appsync.Schema.fromAsset(path.join(__dirname, 'appsync.test.graphql')),
authorizationConfig: {
defaultAuthorization: {
authorizationType: appsync.AuthorizationType.LAMBDA,
lambdaAuthorizerConfig: {
handler: authFunction,
// can also specify `resultsCacheTtl` and `validationRegex`.
},
},
},
});
权限
使用时 AWS_IAM 作为IAM角色GraphQL API的授权类型
访问 API 必须使用正确的权限.
配置权限时,您可以指定特定资源仅为
无障碍 IAM 授权。 例如,如果只允许可变性
页:1 IAM 您将配置以下授权访问 .
单位 schema.graphql数字 :
type Mutation {
updateExample(...): ...
@aws_iam
}
单位 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"
]
}
]
}
见 文档 更多细节.
为方便起见,CDK提供 grant API (英语).
使用 grant 函数用于更多的颗粒式授权.
const role = new iam.Role(this, 'Role', {
assumedBy: new iam.ServicePrincipal('lambda.amazonaws.com'),
});
declare const api: appsync.GraphqlApi;
api.grant(role, appsync.IamResource.custom('types/Mutation/fields/updateExample'), 'appsync:GraphQL');
资源
为了使用 grant 函数,需要使用类 IamResource。 。 。 .
-
IamResource.custom(...arns)允许自定义 ARN 并需要一个参数. -
IamResouce.ofType(type, ...fields)允许ARN用于类型及其字段. -
IamResource.all()允许所有资源.
通用权限
或者,您可以使用更通用的 grant 用于实现相同用途的函数.
其中包括:
- 混合(用于允许进入突变场)
- 授权查询( 用于授权访问查询字段)
- 赠款订阅(用于授权访问订阅栏)
declare const api: appsync.GraphqlApi;
declare const role: iam.Role;
// For generic types
api.grantMutation(role, 'updateExample');
// For custom types and granular design
api.grant(role, appsync.IamResource.ofType('Mutation', 'updateExample'), 'appsync:GraphQL');
管道解析器和 AppSync 函数
AppSync 函数是本地函数,可以执行某些操作到 a 后端数据源. 开发者可以组成操作(功能)并执行 以管道解析器排列.
declare const api: appsync.GraphqlApi;
const appsyncFunction = new appsync.AppsyncFunction(this, 'function', {
name: 'appsync_function',
api,
dataSource: api.addNoneDataSource('none'),
requestMappingTemplate: appsync.MappingTemplate.fromFile('request.vtl'),
responseMappingTemplate: appsync.MappingTemplate.fromFile('response.vtl'),
});
AppSync 函数与管道解析器同步使用,以组成多个函数 操作.
declare const api: appsync.GraphqlApi;
declare const appsyncFunction: appsync.AppsyncFunction;
const pipelineResolver = new appsync.Resolver(this, 'pipeline', {
api,
dataSource: api.addNoneDataSource('none'),
typeName: 'typeName',
fieldName: 'fieldName',
requestMappingTemplate: appsync.MappingTemplate.fromFile('beforeRequest.vtl'),
pipelineConfig: [appsyncFunction],
responseMappingTemplate: appsync.MappingTemplate.fromFile('afterResponse.vtl'),
});
更多了解管道解析器和 AppSync 函数 这里。 。 。 .
代码- 第一司
CDK提供了以代码第一方式生成您的计划的能力. 代码第一方法提供了一个开发者的工作流程,其内容如下:
- 模块化: 将计划类型定义组织到不同的文件中
- 可续用性: 简化下锅炉板/重复码
- 一致性: 解析器和计划定义将永远同步
密码第一方法允许 动态 出谋划策 您可以根据变量和模板生成您的方案,以减少代码重复.
代码首例
展示代码第一的方法。 让我们尝试模拟以下的"计划"段.
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
}
上面我们可以看到一个可以产生分解反应的图案。 譬如说,
我们可以查询 allFilms(first: 100) 自此以来 FilmConnection 作为中间人
用于持有 FilmEdges 我们可以写一个解答器 以归还前100部电影.
在单独的文件中,我们可以声明我们的对象类型和相关功能.
我们会调用这个文件 object-types.ts 我们必以它的方式创造它
允许我们生成其它 XxxConnection 财务报告和审定财务报表 XxxEdges 未来.
import * as appsync from '@aws-cdk/aws-appsync';
const pluralize = require('pluralize');
export const args = {
after: appsync.GraphqlType.string(),
first: appsync.GraphqlType.int(),
before: appsync.GraphqlType.string(),
last: appsync.GraphqlType.int(),
};
export const Node = new appsync.InterfaceType('Node', {
definition: { id: appsync.GraphqlType.string() }
});
export const FilmNode = new appsync.ObjectType('FilmNode', {
interfaceTypes: [Node],
definition: { filmName: appsync.GraphqlType.string() }
});
export function generateEdgeAndConnection(base: appsync.ObjectType) {
const edge = new appsync.ObjectType(`${base.name}Edge`, {
definition: { node: base.attribute(), cursor: appsync.GraphqlType.string() }
});
const connection = new appsync.ObjectType(`${base.name}Connection`, {
definition: {
edges: edge.attribute({ isList: true }),
[pluralize(base.name)]: base.attribute({ isList: true }),
totalCount: appsync.GraphqlType.int(),
}
});
return { edge: edge, connection: connection };
}
最后,我们将去我们的 cdk-stack 将一切融为一体
生成我们的计划.
declare const dummyRequest: appsync.MappingTemplate;
declare const dummyResponse: appsync.MappingTemplate;
const api = new appsync.GraphqlApi(this, 'Api', {
name: 'demo',
});
const objectTypes = [ Node, FilmNode ];
const filmConnections = generateEdgeAndConnection(FilmNode);
api.addQuery('allFilms', new appsync.ResolvableField({
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);
注意我们如何利用 generateEdgeAndConnection 函数生成
对象类型。 将来,如果我们想创造更多的对象类型,我们可以简单地
创建基本对象类型( 即电影) , 从此我们可以生成相应的对象类型
Connections 财务报告和审定财务报表 Edges。 。 。 .
检查一个更深入的例子 这里。 。 。 .
图QL 类型
GraphQL的好处之一是其强烈的打字性质. 我们定义 对象、查询、变异、界面等类型 图QL 类型。 。 。 .
图QL 类型是类型的组成部分, 无论它们是斯卡尔,对象, 接口等。 GraphQL 类型可以是:
- 斯卡尔类型: Id, Itt, String, AWSDate等 互联网档案馆的存檔,存档日期2013-10-02.
- 对象类型: 生成的类型(即:.
demo从上文的例子来看) - 接口类型: 定义其他 中间类型
更具体地说,图QL 类型仅仅是变量所附加的类型.
引用对象类型 Demo 在前一个示例中,图QL类型
实值 String! 并适用于两个名字 id 财务报告和审定财务报表 version。 。 。 .
指令
Directives 附于某一字段或类型并影响查询的执行,
变异,和类型。 用AppSync,我们使用 Directives 以配置授权.
CDK 提供了静态函数,用于向您的 Schema 添加指令 .
Directive.iam()设置要通过IamDirective.apiKey()设置类型或字段的授权,以便通过Api KeyDirective.oidc()设置要通过OpenID ConnectDirective.cognito(...groups: string[])设置要验证的类型或字段的授权 结束Cognito User Poolsgroups提供访问的认知团体名称
为了了解更多授权和指令,请阅读这些文件 这里。 。 。 .
战地和可解决战地
虽然 GraphqlType 是 GraphQL 字段的基础执行, 我们有抽象
顶上 GraphqlType 提供更精细的谷类支持.
外地
Field 扩展 GraphqlType 并允许您定义参数. 接口类型 无法解析, 此类将允许您定义参数,
但不是它的解决者.
例如,如果我们想要创建以下类型:
type Node {
test(argument: string): String
}
所需的CDK代码是:
const field = new appsync.Field({
returnType: appsync.GraphqlType.string(),
args: {
argument: appsync.GraphqlType.string(),
},
});
const type = new appsync.InterfaceType('Node', {
definition: { test: field },
});
可解决字段
ResolvableField 扩展 Field 以便你们确定各种争论及其解决者.
对象类型 可以在
你的后门.
也可以为对象类型创建可解字段.
type Info {
node(id: String): String
}
所需的CDK代码是:
declare const api: appsync.GraphqlApi;
declare const dummyRequest: appsync.MappingTemplate;
declare const dummyResponse: appsync.MappingTemplate;
const info = new appsync.ObjectType('Info', {
definition: {
node: new appsync.ResolvableField({
returnType: appsync.GraphqlType.string(),
args: {
id: appsync.GraphqlType.string(),
},
dataSource: api.addNoneDataSource('none'),
requestMappingTemplate: dummyRequest,
responseMappingTemplate: dummyResponse,
}),
},
});
对于巢穴解析器,我们也可以创建调用顶级查询类型 其他类型。 以上一个例子为基础, 如果我们想要下图ql 类型定义 :
type Query {
get(argument: string): Info
}
所需的CDK代码是:
declare const api: appsync.GraphqlApi;
declare const dummyRequest: appsync.MappingTemplate;
declare const dummyResponse: appsync.MappingTemplate;
const query = new appsync.ObjectType('Query', {
definition: {
get: new appsync.ResolvableField({
returnType: appsync.GraphqlType.string(),
args: {
argument: appsync.GraphqlType.string(),
},
dataSource: api.addNoneDataSource('none'),
requestMappingTemplate: dummyRequest,
responseMappingTemplate: dummyResponse,
}),
},
});
更多地了解田地和解决者 这里。 。 。 .
中间类型
中间类型由Graphql类型和字段定义. 他们有一套定义 字段,其中每个字段对应系统内的另一类型。 中级 类型将是您的 GraphQL Schema 的肉, 因为它们是您定义的类型 .
中级类型包括:
接口类型
接口类型 属于定义其他 中间型. 它们有助于消除重复,可以使用 生成工作较少的对象类型.
您可以创建接口类型 外部。 。 。 .
const node = new appsync.InterfaceType('Node', {
definition: {
id: appsync.GraphqlType.string({ isRequired: true }),
},
});
要多了解一点 接口类型,阅读文档 这里。 。 。 .
对象类型
对象类型 是您宣布的类型。 例如,在 代码第一例
页:1 demo 变量是一个 对象类型。 。 。 . 对象类型 定义由
GraphQL 类型,仅在与 GraphQL Api 链接时才可用 .
您可以以两种方式创建对象类型:
-
可创建对象类型 外部。 。 。 .
const api = new appsync.GraphqlApi(this, 'Api', { name: 'demo', }); const demo = new appsync.ObjectType('Demo', { definition: { id: appsync.GraphqlType.string({ isRequired: true }), version: appsync.GraphqlType.string({ isRequired: true }), }, }); api.addType(demo);这种方法允许再使用和模块化,对于更大的项目来说是理想的. 例如,设想将所有对象类型定义移出堆栈外.
object-types.ts- 对象类型定义的文件import * as appsync from '@aws-cdk/aws-appsync'; export const demo = new appsync.ObjectType('Demo', { definition: { id: appsync.GraphqlType.string({ isRequired: true }), version: appsync.GraphqlType.string({ isRequired: true }), }, });cdk-stack.ts- 包含我们cdk堆栈的文件declare const api: appsync.GraphqlApi; api.addType(demo); -
可创建对象类型 外部 从接口类型.
const node = new appsync.InterfaceType('Node', { definition: { id: appsync.GraphqlType.string({ isRequired: true }), }, }); const demo = new appsync.ObjectType('Demo', { interfaceTypes: [ node ], definition: { version: appsync.GraphqlType.string({ isRequired: true }), }, });这种方法允许重用和模块化,理想的减少代码重复.
要多了解一点 对象类型,阅读文档 这里。 。 。 .
元素类型
元素类型 是一种特殊类型的中间类型。 他们限制一个特定的 其他中间类型的允许值.
enum Episode {
NEWHOPE
EMPIRE
JEDI
}
这就是说,无论我们使用 我们的计划中的"Episode"类型, 我们期望它 是NEWOPE,EMPIRE,或JEDI中的一个.
以上图QL编号类型可以用CDK表示如下:
declare const api: appsync.GraphqlApi;
const episode = new appsync.EnumType('Episode', {
definition: [
'NEWHOPE',
'EMPIRE',
'JEDI',
],
});
api.addType(episode);
要多了解一点 元素类型,阅读文档 这里。 。 。 .
输入类型
输入类型 属于特殊类型的中级类型。 他们给用户一个 用于顶级突变和查询的简单方法.
input Review {
stars: Int!
commentary: String
}
以上图QL输入类型可以用CDK表示如下:
declare const api: appsync.GraphqlApi;
const review = new appsync.InputType('Review', {
definition: {
stars: appsync.GraphqlType.int({ isRequired: true }),
commentary: appsync.GraphqlType.string(),
},
});
api.addType(review);
要多了解一点 输入类型,阅读文档 这里。 。 。 .
联盟类型
联盟类型 是一种特殊类型的中间类型。 它们与 界面类型,但无法指定类型之间的任何共同字段.
说明: 工会类型的领域需要 Object Types换句话说,你
无法从界面、其他联盟或投入中创建工会类型.
union Search = Human | Droid | Starship
上面的GraphQL Union Type包含人类,机器人和星舰等对象类型. 这个 可在CDK中表示如下:
declare const api: appsync.GraphqlApi;
const string = appsync.GraphqlType.string();
const human = new appsync.ObjectType('Human', { definition: { name: string } });
const droid = new appsync.ObjectType('Droid', { definition: { name: string } });
const starship = new appsync.ObjectType('Starship', { definition: { name: string } }););
const search = new appsync.UnionType('Search', {
definition: [ human, droid, starship ],
});
api.addType(search);
要多了解一点 联盟类型,阅读文档 这里。 。 。 .
查询
每个计划都需要一个顶级查询类型. 默认, 计划会看
联 合 国 Object Type 名称 Query上层 Query 这是 仅限 已曝光
用户可以访问的履行类型 GET 操作您的 Api .
要添加这些查询的字段,我们可以简单地运行 addQuery 要添加的函数
给计划 Query 类型.
declare const api: appsync.GraphqlApi;
declare const filmConnection: appsync.InterfaceType;
declare const dummyRequest: appsync.MappingTemplate;
declare const dummyResponse: appsync.MappingTemplate;
const string = appsync.GraphqlType.string();
const int = appsync.GraphqlType.int();
api.addQuery('allFilms', new appsync.ResolvableField({
returnType: filmConnection.attribute(),
args: { after: string, first: int, before: string, last: int},
dataSource: api.addNoneDataSource('none'),
requestMappingTemplate: dummyRequest,
responseMappingTemplate: dummyResponse,
}));
要了解更多顶级操作, 请查看文档 这里。 。 。 .
变异
每个计划 能够 具有顶级突变类型. 默认, 计划会看
联 合 国 ObjectType 名称 Mutation上层 Mutation 类型是唯一暴露
用户可以访问的履行类型 mutable 操作您的 Api .
为了增加这些突变的字段,我们可以简单地运行 addMutation 要添加的函数
给计划 Mutation 类型.
declare const api: appsync.GraphqlApi;
declare const filmNode: appsync.ObjectType;
declare const dummyRequest: appsync.MappingTemplate;
declare const dummyResponse: appsync.MappingTemplate;
const string = appsync.GraphqlType.string();
const int = appsync.GraphqlType.int();
api.addMutation('addFilm', new appsync.ResolvableField({
returnType: filmNode.attribute(),
args: { name: string, film_number: int },
dataSource: api.addNoneDataSource('none'),
requestMappingTemplate: dummyRequest,
responseMappingTemplate: dummyResponse,
}));
要了解更多顶级操作, 请查看文档 这里。 。 。 .
订阅
每个计划 能够 有顶级订阅类型。 顶层 Subscription 类型
是用户唯一可以访问的曝光类型,以引用对突变的反应. Subscriptions
当调用突变特定突变时通知用户。 这意味着你可以制作任何数据源
实时指定关于突变的 GraphQL Schema 指令.
说明: AWS AppSync客户端SDK自动处理订阅连接管理.
为这些订阅添加字段,我们可以简单地运行 addSubscription 要添加的函数
给计划 Subscription 类型.
declare const api: appsync.GraphqlApi;
declare const film: appsync.InterfaceType;
api.addSubscription('addedFilm', new appsync.Field({
returnType: film.attribute(),
args: { id: appsync.GraphqlType.id({ isRequired: true }) },
directives: [appsync.Directive.subscribe('addFilm')],
}));
要了解更多顶级操作, 请查看文档 这里。 。 。 .