创建解析程序以通过 AppSync 更新 dynamoDB 项目 - AWS CDK

Yas*_*ara 1 amazon-dynamodb typescript aws-appsync aws-cdk

因此,我创建了一个解析器来使用以下代码在表中创建一个项目。

const configSettingsDS = api.addDynamoDbDataSource('configSettingsDynamoTable', configurationSettingsTable);

    configSettingsDS.createResolver({
        typeName:'Mutation',
        fieldName: 'createConfigSettings',
        requestMappingTemplate: appsync.MappingTemplate.dynamoDbPutItem(
            appsync.PrimaryKey.partition('id').auto(),
            appsync.Values.projecting('configSettings')),
        responseMappingTemplate: appsync.MappingTemplate.dynamoDbResultItem(),
    });
Run Code Online (Sandbox Code Playgroud)

我似乎找不到一个可以在更新操作中复制相同内容的方法。任何帮助表示赞赏。谢谢

tom*_*een 5

更新解析器的工作方式几乎与创建解析器相同。在 DynamoDB 中,两者的操作都是PutItem,因此应用相同的映射模板。您需要将第一个参数从 更改appsync.PrimaryKey.partion('id').auto()appsync.PrimaryKey.partion('id').is('<PATH_TO_YOUR_ID>')

id 可以是作为输入传递的对象的一部分。虽然我更喜欢将它分开,所以 id 不是输入对象的一部分。这是这两种变体的一个非常基本的示例。

graphql 架构:

// 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 seperately
    updateB(id: ID!, InputB)
}
Run Code Online (Sandbox Code Playgroud)

解析器代码:

// 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 seperately
    updateB(id: ID!, InputB)
}
Run Code Online (Sandbox Code Playgroud)

我只需要为我的项目解决同样的问题。以下是我如何设置的一些片段:

graphql 架构的一部分:

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
}

Run Code Online (Sandbox Code Playgroud)

cdk中对应的解析器:

// 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(),
});
Run Code Online (Sandbox Code Playgroud)