Skip to content
v2.274.0

DynamoDbDataSource ​

An AppSync datasource backed by a DynamoDB table.

Example ​

ts
const api = new appsync.GraphqlApi(this, 'Api', {
  name: 'demo',
  definition: appsync.Definition.fromFile(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.
// Resolver Mapping Template Reference:
// https://docs.aws.amazon.com/appsync/latest/devguide/resolver-mapping-template-reference-dynamodb.html
demoDS.createResolver('QueryGetDemosResolver', {
  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('MutationAddDemoResolver', {
  typeName: 'Mutation',
  fieldName: 'addDemo',
  requestMappingTemplate: appsync.MappingTemplate.dynamoDbPutItem(
    appsync.PrimaryKey.partition('id').auto(),
    appsync.Values.projecting('input'),
  ),
  responseMappingTemplate: appsync.MappingTemplate.dynamoDbResultItem(),
});

//To enable DynamoDB read consistency with the `MappingTemplate`:
demoDS.createResolver('QueryGetDemosConsistentResolver', {
  typeName: 'Query',
  fieldName: 'getDemosConsistent',
  requestMappingTemplate: appsync.MappingTemplate.dynamoDbScanTable(true),
  responseMappingTemplate: appsync.MappingTemplate.dynamoDbResultList(),
});
python
api = appsync.GraphqlApi(self, "Api",
    name="demo",
    definition=appsync.Definition.from_file(path.join(__dirname, "schema.graphql")),
    authorization_config=appsync.AuthorizationConfig(
        default_authorization=appsync.AuthorizationMode(
            authorization_type=appsync.AuthorizationType.IAM
        )
    ),
    xray_enabled=True
)

demo_table = dynamodb.Table(self, "DemoTable",
    partition_key=dynamodb.Attribute(
        name="id",
        type=dynamodb.AttributeType.STRING
    )
)

demo_ds = api.add_dynamo_db_data_source("demoDataSource", demo_table)

# Resolver for the Query "getDemos" that scans the DynamoDb table and returns the entire list.
# Resolver Mapping Template Reference:
# https://docs.aws.amazon.com/appsync/latest/devguide/resolver-mapping-template-reference-dynamodb.html
demo_ds.create_resolver("QueryGetDemosResolver",
    type_name="Query",
    field_name="getDemos",
    request_mapping_template=appsync.MappingTemplate.dynamo_db_scan_table(),
    response_mapping_template=appsync.MappingTemplate.dynamo_db_result_list()
)

# Resolver for the Mutation "addDemo" that puts the item into the DynamoDb table.
demo_ds.create_resolver("MutationAddDemoResolver",
    type_name="Mutation",
    field_name="addDemo",
    request_mapping_template=appsync.MappingTemplate.dynamo_db_put_item(
        appsync.PrimaryKey.partition("id").auto(),
        appsync.Values.projecting("input")),
    response_mapping_template=appsync.MappingTemplate.dynamo_db_result_item()
)

# To enable DynamoDB read consistency with the `MappingTemplate`:
demo_ds.create_resolver("QueryGetDemosConsistentResolver",
    type_name="Query",
    field_name="getDemosConsistent",
    request_mapping_template=appsync.MappingTemplate.dynamo_db_scan_table(True),
    response_mapping_template=appsync.MappingTemplate.dynamo_db_result_list()
)
java
GraphqlApi api = GraphqlApi.Builder.create(this, "Api")
        .name("demo")
        .definition(Definition.fromFile(join(__dirname, "schema.graphql")))
        .authorizationConfig(AuthorizationConfig.builder()
                .defaultAuthorization(AuthorizationMode.builder()
                        .authorizationType(AuthorizationType.IAM)
                        .build())
                .build())
        .xrayEnabled(true)
        .build();

Table demoTable = Table.Builder.create(this, "DemoTable")
        .partitionKey(Attribute.builder()
                .name("id")
                .type(AttributeType.STRING)
                .build())
        .build();

DynamoDbDataSource demoDS = api.addDynamoDbDataSource("demoDataSource", demoTable);

// Resolver for the Query "getDemos" that scans the DynamoDb table and returns the entire list.
// Resolver Mapping Template Reference:
// https://docs.aws.amazon.com/appsync/latest/devguide/resolver-mapping-template-reference-dynamodb.html
demoDS.createResolver("QueryGetDemosResolver", BaseResolverProps.builder()
        .typeName("Query")
        .fieldName("getDemos")
        .requestMappingTemplate(MappingTemplate.dynamoDbScanTable())
        .responseMappingTemplate(MappingTemplate.dynamoDbResultList())
        .build());

// Resolver for the Mutation "addDemo" that puts the item into the DynamoDb table.
demoDS.createResolver("MutationAddDemoResolver", BaseResolverProps.builder()
        .typeName("Mutation")
        .fieldName("addDemo")
        .requestMappingTemplate(MappingTemplate.dynamoDbPutItem(PrimaryKey.partition("id").auto(), Values.projecting("input")))
        .responseMappingTemplate(MappingTemplate.dynamoDbResultItem())
        .build());

//To enable DynamoDB read consistency with the `MappingTemplate`:
demoDS.createResolver("QueryGetDemosConsistentResolver", BaseResolverProps.builder()
        .typeName("Query")
        .fieldName("getDemosConsistent")
        .requestMappingTemplate(MappingTemplate.dynamoDbScanTable(true))
        .responseMappingTemplate(MappingTemplate.dynamoDbResultList())
        .build());
csharp
// Install: dotnet add package Amazon.CDK.Lib
var api = new GraphqlApi(this, "Api", new GraphqlApiProps {
    Name = "demo",
    Definition = Definition.FromFile(Join(__dirname, "schema.graphql")),
    AuthorizationConfig = new AuthorizationConfig {
        DefaultAuthorization = new AuthorizationMode {
            AuthorizationType = AuthorizationType.IAM
        }
    },
    XrayEnabled = true
});

var demoTable = new Table(this, "DemoTable", new TableProps {
    PartitionKey = new Attribute {
        Name = "id",
        Type = AttributeType.STRING
    }
});

var demoDS = api.AddDynamoDbDataSource("demoDataSource", demoTable);

// Resolver for the Query "getDemos" that scans the DynamoDb table and returns the entire list.
// Resolver Mapping Template Reference:
// https://docs.aws.amazon.com/appsync/latest/devguide/resolver-mapping-template-reference-dynamodb.html
demoDS.CreateResolver("QueryGetDemosResolver", new BaseResolverProps {
    TypeName = "Query",
    FieldName = "getDemos",
    RequestMappingTemplate = MappingTemplate.DynamoDbScanTable(),
    ResponseMappingTemplate = MappingTemplate.DynamoDbResultList()
});

// Resolver for the Mutation "addDemo" that puts the item into the DynamoDb table.
demoDS.CreateResolver("MutationAddDemoResolver", new BaseResolverProps {
    TypeName = "Mutation",
    FieldName = "addDemo",
    RequestMappingTemplate = MappingTemplate.DynamoDbPutItem(PrimaryKey.Partition("id").Auto(), Values.Projecting("input")),
    ResponseMappingTemplate = MappingTemplate.DynamoDbResultItem()
});

//To enable DynamoDB read consistency with the `MappingTemplate`:
demoDS.CreateResolver("QueryGetDemosConsistentResolver", new BaseResolverProps {
    TypeName = "Query",
    FieldName = "getDemosConsistent",
    RequestMappingTemplate = MappingTemplate.DynamoDbScanTable(true),
    ResponseMappingTemplate = MappingTemplate.DynamoDbResultList()
});
go
// Install: go get github.com/aws/aws-cdk-go/awscdk/v2
api := appsync.NewGraphqlApi(this, jsii.String("Api"), &GraphqlApiProps{
	Name: jsii.String("demo"),
	Definition: appsync.Definition_FromFile(path.join(__dirname, jsii.String("schema.graphql"))),
	AuthorizationConfig: &AuthorizationConfig{
		DefaultAuthorization: &AuthorizationMode{
			AuthorizationType: appsync.AuthorizationType_IAM,
		},
	},
	XrayEnabled: jsii.Boolean(true),
})

demoTable := dynamodb.NewTable(this, jsii.String("DemoTable"), &TableProps{
	PartitionKey: &Attribute{
		Name: jsii.String("id"),
		Type: dynamodb.AttributeType_STRING,
	},
})

demoDS := api.AddDynamoDbDataSource(jsii.String("demoDataSource"), demoTable)

// Resolver for the Query "getDemos" that scans the DynamoDb table and returns the entire list.
// Resolver Mapping Template Reference:
// https://docs.aws.amazon.com/appsync/latest/devguide/resolver-mapping-template-reference-dynamodb.html
demoDS.CreateResolver(jsii.String("QueryGetDemosResolver"), &BaseResolverProps{
	TypeName: jsii.String("Query"),
	FieldName: jsii.String("getDemos"),
	RequestMappingTemplate: appsync.MappingTemplate_DynamoDbScanTable(),
	ResponseMappingTemplate: appsync.MappingTemplate_DynamoDbResultList(),
})

// Resolver for the Mutation "addDemo" that puts the item into the DynamoDb table.
demoDS.CreateResolver(jsii.String("MutationAddDemoResolver"), &BaseResolverProps{
	TypeName: jsii.String("Mutation"),
	FieldName: jsii.String("addDemo"),
	RequestMappingTemplate: appsync.MappingTemplate_DynamoDbPutItem(appsync.PrimaryKey_Partition(jsii.String("id")).Auto(), appsync.Values_Projecting(jsii.String("input"))),
	ResponseMappingTemplate: appsync.MappingTemplate_DynamoDbResultItem(),
})

//To enable DynamoDB read consistency with the `MappingTemplate`:
demoDS.CreateResolver(jsii.String("QueryGetDemosConsistentResolver"), &BaseResolverProps{
	TypeName: jsii.String("Query"),
	FieldName: jsii.String("getDemosConsistent"),
	RequestMappingTemplate: appsync.MappingTemplate_*DynamoDbScanTable(jsii.Boolean(true)),
	ResponseMappingTemplate: appsync.MappingTemplate_*DynamoDbResultList(),
})

Initializer ​

ts
new DynamoDbDataSource(scope: Construct, id: string, props: DynamoDbDataSourceProps)
python
DynamoDbDataSource(scope: Construct, id: str, props: DynamoDbDataSourceProps)
java
new DynamoDbDataSource(Construct scope, String id, DynamoDbDataSourceProps props)
csharp
new DynamoDbDataSource(Construct scope, string id, DynamoDbDataSourceProps props)
go
NewDynamoDbDataSource(Scope Construct, Id *string, Props DynamoDbDataSourceProps)

Construct Props ​

The API to attach this data source to.
descriptionoptionalstringdescriptionoptionalstrdescriptionoptionalStringDescriptionoptionalstringDescriptionoptional*string= None#
the description of the data source.
metricsConfigoptionalDataSourceMetricsConfigmetrics_configoptionalDataSourceMetricsConfigmetricsConfigoptionalDataSourceMetricsConfigMetricsConfigoptionalDataSourceMetricsConfigMetricsConfigoptionalDataSourceMetricsConfig#
Whether to enable enhanced metrics of the data source Value will be ignored, if `enhancedMetricsConfig.dataSourceLevelMetricsBehavior` on AppSync GraphqlApi construct is set to `FULL_REQUEST_DATA_SOURCE_METRICS`.

Default: no metrics configuration

nameoptionalstringnameoptionalstrnameoptionalStringNameoptionalstringNameoptional*string#
The name of the data source.

Default: id of data source

readOnlyAccessoptionalbooleanread_only_accessoptionalboolreadOnlyAccessoptionalBooleanReadOnlyAccessoptionalboolReadOnlyAccessoptional*bool= false#
Specify whether this DS is read only or has read and write permissions to the DynamoDB table.
serviceRoleoptionalIRoleservice_roleoptionalIRoleserviceRoleoptionalIRoleServiceRoleoptionalIRoleServiceRoleoptionalIRole#
The IAM service role to be assumed by AppSync to interact with the data source.

Default: Create a new role

tableITabletableITabletableITableTableITableTableITablerequired#
The DynamoDB table backing this data source.
useCallerCredentialsoptionalbooleanuse_caller_credentialsoptionalbooluseCallerCredentialsoptionalBooleanUseCallerCredentialsoptionalboolUseCallerCredentialsoptional*bool= false#
use credentials of caller to access DynamoDB.

Properties ​

the underlying CFN data source resource.
grantPrincipalIPrincipalgrant_principalIPrincipalgrantPrincipalIPrincipalGrantPrincipalIPrincipalGrantPrincipalIPrincipalrequired#
the principal of the data source to be IGrantable.
namestringnamestrnameStringNamestringName*stringrequired#
the name of the data source.
nodeNodenodeNodenodeNodeNodeNodeNodeNoderequired#
The tree node.
PROPERTY_INJECTION_IDstringproperty_injection_idstrPROPERTY_INJECTION_IDStringPROPERTY_INJECTION_IDstringPROPERTY_INJECTION_ID*stringrequiredstatic#
Uniquely identifies this class.

Methods ​

createFunction(id: string, props: BaseAppsyncFunctionProps): AppsyncFunctiondef create_function(self, id: str, props: BaseAppsyncFunctionProps) -> AppsyncFunctionpublic AppsyncFunction createFunction(String id, BaseAppsyncFunctionProps props)public AppsyncFunction CreateFunction(string id, BaseAppsyncFunctionProps props)func CreateFunction(Id *string, Props BaseAppsyncFunctionProps) AppsyncFunction#
creates a new appsync function for this datasource and API using the given properties.
createResolver(id: string, props: BaseResolverProps): Resolverdef create_resolver(self, id: str, props: BaseResolverProps) -> Resolverpublic Resolver createResolver(String id, BaseResolverProps props)public Resolver CreateResolver(string id, BaseResolverProps props)func CreateResolver(Id *string, Props BaseResolverProps) Resolver#
creates a new resolver for this datasource and API using the given properties.
isConstruct(x: any): boolean@staticmethod def is_construct(x: Any) -> boolpublic static Boolean isConstruct(Object x)public static bool IsConstruct(object x)func IsConstruct(X interface{}) *boolstatic#
Checks if `x` is a construct.
notes · 1 parameter · returns

Use this method instead of instanceof to properly detect Construct instances, even when the construct library is symlinked.

Explanation: in JavaScript, multiple copies of the constructs library on disk are seen as independent, completely different libraries. As a consequence, the class Construct in each copy of the constructs library is seen as a different class, and an instance of one class will not test as instanceof the other class. npm install will not create installations like this, but users may manually symlink construct libraries together or use a monorepo tool: in those cases, multiple copies of the constructs library can be accidentally installed, and instanceof will behave unpredictably. It is safest to avoid using instanceof, and using this type-testing method instead.

Parameters

  • xxxxX — Any object.

Returns: true if x is an object created from a class which extends Construct.

toString(): stringdef to_string(self, ) -> strpublic String toString()public string ToString()func ToString() *string#
Returns a string representation of this construct.
with(...mixins: IMixin[]): IConstructdef with(self, mixins: IMixin) -> IConstructpublic IConstruct with(IMixin mixins)public IConstruct With(IMixin mixins)func With(Mixins IMixin) IConstruct#
Applies one or more mixins to this construct.

Mixins are applied in order. The list of constructs is captured at the start of the call, so constructs added by a mixin will not be visited. Use multiple with() calls if subsequent mixins should apply to added constructs.

1 parameter · returns

Parameters

  • mixinsmixinsmixinsmixinsMixins — The mixins to apply.

Returns: This construct for chaining