When it comes to the update resolver in DynamoDB, it operates similarly to the create resolver using the PutItem
operation. This means that the same mapping template can be applied for both operations. The only change required is adjusting the first parameter from
appsync.PrimaryKey.partion('id').auto()
to
appsync.PrimaryKey.partion('id').is('<PATH_TO_YOUR_ID>')
.
While the id can be included as part of the input object, some prefer to keep it separate to avoid having the id within the input object. Here's a basic example illustrating both approaches:
graphql schema:
// Input A includes ID
input InputA {
id: ID!
name: String!
}
// Input B does not include an ID
input InputB {
name: String!
}
type Mutation {
// Id is part of input
updateA(input: InputA)
// Id needs to be provided separately
updateB(id: ID!, InputB)
}
resolver code:
// Configure the resolver where ID is part of the input
const resolverA = datasource.createResolver({
typeName: `Mutation`,
fieldName: `updateA`,
requestMappingTemplate: appsync.MappingTemplate.dynamoDbPutItem(
appsync.PrimaryKey.partition('id').is('input.id'),
appsync.Values.projecting('input'),
),
responseMappingTemplate: appsync.MappingTemplate.dynamoDbResultItem(),
});
// Configure the resolver where ID is provided as a separate input parameter.
const resolverB = datasource.createResolver({
typeName: `Mutation`,
fieldName: `updateB`,
requestMappingTemplate: appsync.MappingTemplate.dynamoDbPutItem(
appsync.PrimaryKey.partition('id').is('id'),
appsync.Values.projecting('input'),
),
responseMappingTemplate: appsync.MappingTemplate.dynamoDbResultItem(),
});
In a recent project, I encountered and addressed a similar issue. Here are snippets depicting how I tackled this:
Part of the graphql schema:
input Label {
id: ID!
name: String!
imageUrl: String
}
input LabelInput {
name: String!
imageUrl: String
}
type Mutation {
createLabel(input: LabelInput!): Label
updateLabel(id: ID!, input: LabelInput!): Label
}
Corresponding resolvers in cdk:
datasource.createResolver({
typeName: `Mutation`,
fieldName: `createLabel`,
requestMappingTemplate: appsync.MappingTemplate.dynamoDbPutItem(
appsync.PrimaryKey.partition('id').auto(),
appsync.Values.projecting('input'),
),
responseMappingTemplate: appsync.MappingTemplate.dynamoDbResultItem(),
});
datasource.createResolver({
typeName: 'Mutation',
fieldName: `updateLabel`,
requestMappingTemplate: appsync.MappingTemplate.dynamoDbPutItem(
appsync.PrimaryKey.partition('id').is('id'),
appsync.Values.projecting('input'),
),
responseMappingTemplate: appsync.MappingTemplate.dynamoDbResultItem(),
});