amplify-category-api icon indicating copy to clipboard operation
amplify-category-api copied to clipboard

How to update row using increment either way set or add in amplify gen2? data client

Open jaimeardp opened this issue 1 year ago • 1 comments

Amplify CLI Version

10.8.1

Question

Environment information

System:
  OS: Windows 11 10.0.22631
  CPU: (12) x64 12th Gen Intel(R) Core(TM) i7-1255U
  Memory: 1.11 GB / 15.73 GB
Binaries:
  Node: 20.16.0 - C:\Program Files\nodejs\node.EXE
  Yarn: undefined - undefined
  npm: 10.8.1 - C:\Program Files\nodejs\npm.CMD
  pnpm: undefined - undefined
NPM Packages:
  @aws-amplify/backend: 1.0.4
  @aws-amplify/backend-cli: 1.1.1
  aws-amplify: 6.4.0
  aws-cdk: 2.149.0
  aws-cdk-lib: 2.149.0
  typescript: 5.5.3
AWS environment variables:
  AWS_NODEJS_CONNECTION_REUSE_ENABLED = 1
  AWS_SDK_LOAD_CONFIG = 1
  AWS_STS_REGIONAL_ENDPOINTS = regional

Actually, searching in documentation, I found a simple example of update, just only "replace" old value by new value.

import { generateClient } from 'aws-amplify/data';
import { type Schema } from '../amplify/data/resource';

const client = generateClient<Schema>();

const todo = {
  id: 'some_id',
  content: 'Updated content',
};

const { data: updatedTodo, errors } = await client.models.Todo.update(todo);

But my use case is a increment, because i need to update column like views or counter in post. I understand that i can first to use "client.models.Blog.get" and after to use "client.models.Blog.update". But then is needed to perfom both requests for to update one simple "Atomic counters" in DynamoDB ?

Please if you face use case, recommend me, thanks.

I hope this in amplify gen2 data client.

aws dynamodb update-item \
--table-name counter \
--key '{"pk":{"S":"abc123"}}' \
--update-expression "ADD quantity :change" \
--expression-attribute-values file://values.json

json file


{
    ":change" : { "N" : "-5" }
}

jaimeardp avatar Sep 17 '24 20:09 jaimeardp