#✅ - Incrementing Article Views

5 messages · Page 1 of 1 (latest)

slender gale
#

I have done this before using a lambda function while using Gen 1

Is it possible now to increment a field for example, article view count which is an INT without using a Lambda function?

For example, I already have the id of the article on hand, I click on the article card, getArticleByID api is called, user is redirected, to idnividual article page to view the entire article
( I want the views of the article to increment before the article data is fitched or while not sure how gen2 works now )

slender gale
#

👋

sharp yarrow
#

Hi @slender gale , for your use case, to increment the view count before fetching the article, you could create a custom mutation specifically for handling view count increments and also return the article from that mutation instead.

https://docs.amplify.aws/react/build-a-backend/data/custom-business-logic/#pageMain

You can use either a Lambda function resolve the mutation or an AppSync JS resolver which gives you access to some neat DynamoDB helper utilities, one of which is an increment function.

import { util } from '@aws-appsync/utils';
import * as ddb from '@aws-appsync/utils/dynamodb';

export function request(ctx) {
  const { id, ...rest } = ctx.args;
  const values = Object.entries(rest).reduce((obj, [key, value]) => {
    obj[key] = value ?? ddb.operations.remove();
    return obj;
  }, {});

  return ddb.update({
    key: { id },
    update: { ...values, views: ddb.operations.increment(1) },
  });
}

export function response(ctx) {
  const { error, result } = ctx;
  if (error) {
    util.appendError(error.message, error.type);
  }
  return result;

The above code is a modified example from the one in the AppSync docs for JS resolvers. Also worth checking out:

https://docs.aws.amazon.com/appsync/latest/devguide/tutorial-dynamodb-resolvers-js.html#configure-updatepost

sleek oxideBOT
#

✅ - Incrementing Article Views