aws-amplify / amplify-category-api

The AWS Amplify CLI is a toolchain for simplifying serverless web and mobile development. This plugin provides functionality for the API category, allowing for the creation and management of GraphQL and REST based backends for your amplify project.
https://docs.amplify.aws/
Apache License 2.0
89 stars 79 forks source link

Do some data computations with extending postDataLoad resolver #1948

Closed ggorge-etiqa closed 1 year ago

ggorge-etiqa commented 1 year ago

Amplify CLI Version

12.6.0

Question

In my model I have a field ExpDate that is an iso timestamp. I want that when I list my model a computated field isExpired is set to true if ExpDate > current timestamp. Following https://docs.amplify.aws/cli/graphql/custom-business-logic/#extend-amplify-generated-resolvers I'm assuming I can create a postDataLoad VTL for accomplish the job and do a simple if statement inside it. I'm also assuming that I need to implement this logic inside the res VTL, but I'm not sure how the req VTL should be. Any hints?

AnilMaktala commented 1 year ago

Hey @ggorge-etiqa 👋 , Thank you for your question. Does the field isExpired already exist in the model, or would you like to inject it when retrieving the list query?

ggorge-etiqa commented 1 year ago

Hi @AnilMaktala I thought that adding the field isExpired in the model as optional Boolean is not a bad idea but I'm open to suggestion. Atm I succesfully managed this behavior with a lambda datasource for the postDataLoad appsync function but I would be more happy to not call an external lambda for such small work.

ggorge-etiqa commented 1 year ago

I probably managed it to work without using a Lambda. This is the req VTL as we use a NONE_DS datasource as documented here: https://docs.aws.amazon.com/appsync/latest/devguide/resolver-mapping-template-reference-none.html

{
    "version": "2018-05-29",
    "payload": $util.toJson($context.prev.result)
}

This is my res VTL with custom logic:

## [Start] ResponseTemplate. **

#set($currentMillis = $util.time.nowEpochMilliSeconds())

#foreach($item in $ctx.result.items)
    #set($item.isExpired = false)

    #if($item.expirationDate)
        #set($expirationDateMillis = $util.time.parseISO8601ToEpochMilliSeconds($item.expirationDate))
        #if($expirationDateMillis < $currentMillis)
          #set($item.isExpired = true)
        #end    
    #else
        ## Handle missing expiration date
        $util.error("An error occurred: Missing expiration date for item: $item")
    #end

#end

$util.toJson($ctx.result)

## [End] ResponseTemplate. **

If you have any other suggestion I'm open to try, otherwise I can consider the issue closed.

AnilMaktala commented 1 year ago

Hey @ggorge-etiqa, I apologize for the delay. I have consulted with the Engineering team, and they have confirmed that this is the recommended approach to fulfill your use case.