Rastislav
Rastislav

Reputation: 439

How to resolve String field using AWS appsync javascript resolver with NONE resource

I have this appsync GraphQL schema with type

type Place {
  id: ID!
  name: String!
  nameTranslations: FieldTranslations
}

And then I have resolvers for this type and paginated type that works just fine. Now I want to add a field resolver for the "name" field, that will automatically translate the name based on the query parameter..

This is the Javascript appsync resolver

export function request(context) {
  const source = context.source;
  const lang = context.arguments.lang || "en";

  const translations = source.nameTranslations || {};
  let translatedName = source.name;

  if (translations[lang]) {
    translatedName = translations[lang];
  }

  return {
    payload: {
      translatedName,
    },
  };
}

export function response(context) {
  return context.result.translatedName;
}

Which correctly translates the name and should return the changed name. I use NONE data source for this scenario.

And following is the terraform that creates the resolver

resource "aws_appsync_resolver" "translatePlace" {
  api_id            = var.app-sync-id
  field             = "name"
  type              = "Place"
  request_template  = "{}"
  response_template = "$context.result"
  kind              = "PIPELINE"

  pipeline_config {
    functions = [
      module.translatePlace.appsync-function.function_id
    ]
  }

  depends_on = [module.translatePlace]
}

Basically it just adds request_template = "{}" and response_template = "$context.result"

But with this, I am unable to actually resolve the field value.. just keep getting errors as

{
    "data": null,
    "errors": [
        {
            "path": [
                "places",
                "places",
                0,
                "name"
            ],
            "data": null,
            "errorType": "MappingTemplate",
            "errorInfo": null,
            "locations": [
                {
                    "line": 15,
                    "column": 7,
                    "sourceName": null
                }
            ],
            "message": "Unable to convert 123Another City to Object."
},....

What is the correct mapping of the function response and the resolver after mapping? I think I almost everything but keep getting errors.

Upvotes: 0

Views: 59

Answers (1)

bmilesp
bmilesp

Reputation: 2587

You're using the VTL request_template and response_template variables.

Since you're using JS for the resolver, use the code variable instead.

Check the Example JS section here: https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/appsync_resolver#example-usage-js

Upvotes: 0

Related Questions