Building a resolver to modify a DynamoDB item via AppSync using the AWS Cloud Development Kit (CDK)

After successfully creating a resolver to add an item in the table using the code provided below, I am now seeking assistance for replicating the same functionality for an update operation.

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(),
    });

If anyone has any tips or guidance on how to achieve the same functionality for updates, I would greatly appreciate it. Thank you!

Answer №1

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(),
});

Answer №2

It appears that DynamoDB offers an operation called UpdateItem, which is not currently implemented in CDK from my understanding. My concern with using appsync.Values.projecting is that when executing a PutItem, if I am not aware of all the fields in the table, existing fields may be lost.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Autocomplete feature in Angular not showing search results

I am currently using ng-prime's <p-autocomplete> to display values by searching in the back-end. Below is the HTML code I have implemented: <p-autoComplete [(ngModel)]="agent" [suggestions]="filteredAgents" name="agents" (completeMethod)="f ...

Leveraging event listeners in conjunction with React's useEffect function

Check out the code example on Code Sandbox here Hey there, I'm trying to implement a feature where clicking a button inside a container displays a box. I've set up an event listener so that when you move your mouse outside the container, the box ...

Prevent a React component from unnecessarily re-rendering after a property has been set

I am working on a react component that displays a streaming page similar to the one shown in this image. Here is a snippet of the code : const [currentStream, setCurrentStream] = useState<IStream>(); const [currentStreams] = useCollectionData<ISt ...

Adding a QR code on top of an image in a PDF using TypeScript

Incorporating TypeScript and PdfMakeWrapper library, I am creating PDFs on a website integrated with svg images and QR codes. Below is a snippet of the code in question: async generatePDF(ID_PRODUCT: string) { PdfMakeWrapper.setFonts(pdfFonts); ...

Using Angular2's component templateUrl with a npm package

Seeking advice on the best way to reference templateUrl in a commonly used npm module. I want to avoid including node_modules in the path, as the directory could potentially be renamed. Is there an alternative method that still works effectively? For exam ...

The combination of a reactive form and the latest object may result in a potential null or undefined

Is it possible to update a FormArray based on the values of two other controls? After thorough checks, TypeScript is indicating issues with 'st' and 'sp'. The object is potentially null. Can someone identify the errors in this code ...

The 'cookies' property is not found on the 'Request' type

Currently, I am attempting to access a cookie within a NestJS controller. I have been referencing the documentation found at https://docs.nestjs.com/techniques/cookies#use-with-express-default Below is my implementation: import { Controller, Get, Render, ...

Observer function simulated by SinonStub

I am currently testing express middleware using sinon.js My goal is to verify that it sends a specific JSON response and prevents the request from moving on to the next middleware or request handler. const middleware = (req: Request, res: Response, nex ...

What is the best way to position Scroll near a mat row in Angular?

With over 20 records loaded into an Angular Material table, I am experiencing an issue where clicking on the last row causes the scroll position to jump to the top of the page. I would like the scroll position to be set near the clicked row instead. Is th ...

The Mongoose getter function is triggering error TS2590 by generating a union type that is too intricate to be displayed

I've come across the TS2590: Expression produces a union type that is too complex to represent error while trying to compile TypeScript. The issue seems to be connected to the id's getter function idFromString, as removing the id getter prevents ...

Error message: WebStorm shows that the argument type {providedIn: "root"} cannot be assigned to the parameter type {providedIn: Type<any> | "root" | null} and InjectableProvider

Transitioning my app from Angular v5 to v6 has presented me with a TypeScript error when trying to define providedIn in my providers. The argument type {providedIn: "root"} cannot be assigned to the parameter type {providedIn: Type | "root" | null} & ...

Ensure the inferred type is asserted in TypeScript

Is there a more elegant approach to assert the type TypeScript inferred for a specific variable? Currently, I am using the following method: function assertType<T>(value: T) { /* no op */ } assertType<SomeType>(someValue); This technique prov ...

What are the steps for customizing the interface in TypeScript?

After fixing a type error related to adding custom functions to the gun chain by including bind():any within IGunChainReference in @types/gun/index.ts, I am wondering how to transfer this modification to one of my project files. I have not been able to fi ...

Before accessing the page, please ensure to make a double request

Encountered a weird issue, While inspecting the network tab in Chrome devtools, I noticed that my Vue app is making double requests to the same endpoint :/ Here's a snippet of my code: In the router section, I have a beforeEach function. When I navig ...

Looking to execute multiple programs simultaneously within the prestart script in the package.json file, and bypass any exit error codes

I need to run yarn tsc and yarn lint during every yarn start to identify any code errors. This is how my scripts property is set up: "scripts": { "start": "expo start", "android": "expo start --android" ...

Sequelize v5 & Typescript Model Loader

Having previous experience with Sequelize for projects (v4), I am now venturing into starting a new project using Sequelize v5 & Typescript. I have been following Sequelize's documentation on how to define Models at: https://sequelize.org/master/ ...

Retrieving user input from one component to be used in another component in Angular

I'm currently working on a structure that involves a navbar component and a form component https://i.stack.imgur.com/nPRLO.png Initially, I have a navbar component where I load user data using an ID stored in the session. In the right side component ...

Developing an exportable value service type in TypeScript for AngularJS

I have been working on creating a valuable service using typescript that involves a basic switch case statement based on values from the collection provided below [{ book_id: 1, year_published: 2000 }, { book_id: 2, year_publish ...

The Express request parameter ID throws an error due to the index expression not being of type 'number', causing the element to implicitly have an 'any' type

Is there a way to assign a type to an ID request parameter? It appears that the types of Express treat request params as any. This is the code snippet where I am trying to access the ID from the request: const repository: Repository = { ...reposit ...

Error Encountered with Next.js 13.4.1 when using styled-components Button in React Server-Side Rendering

I am currently working on a React project using Next.js version 13.4.1 and styled-components. One problem I'm facing is with a custom Button component that I've created: import React from 'react'; import styled from 'styled-compone ...