Search code examples
amazon-web-serviceselasticsearchgraphqlaws-appsync

simple AWS AppSync schema and resolver for ElasticSearch service


I'd like to get simple AppSync resolver for EslasticSearch service this way:

Schema:

type Query {
  searchESIndex(input: ESModelTypeInput!): ESModelRespType
}

input ESModelTypeInput {
  es_body: String
  es_index_name: String
}

type ESModelRespType {
  es_resp: String
}

So the point is to give only index name where to search and the body string that contains full stingified body or query and to return back full response of ElasticSearch as a string (for further parsing)

Resolver:

{
  "version":"2017-02-28",
  "operation":"GET",
  "path":"/$context.args.es_index_name/_search",
  "params":{
      "body": $util.toJson("$context.args.es_body")
      }
  }
}

Response template:

## i need full result as a string, but how to convert it?
$context.result

The Query would be:

query searchESIndex($esinput: ESModelTypeInput!) {
  searchESIndex(input: $esinput) {
    es_resp
  }
}

Variables:

{
    "esinput": {
        "es_index_name": "test2",
        "es_body": "{\"size\": 10}"
  }
}

Also i supposed to have similar mutation

type Mutation {
    insertToESIndex(input: ESModelTypeInput!): ESModelRespType
}

Unfortunately, all my tries were failed. Is it possible to do it? Could you help me with that?


Solution

  • I feel obligated to update my answer as @cyberwombat pointed out a better solution than I posted previously.

    You can convert your result into stringified JSON by following ways.

    Option 1:

    #set($resultMap = {})
    
    #foreach($key in $ctx.result.keySet())
        $util.qr($resultMap.put("$key", $ctx.result.get($key)))
    #end
    
    #return($util.escapeJavaScript($util.toJson($resultMap)))
    

    Option 2:

    You can convert your resolver to Pipeline and created a simple Lambda function in NodeJS to stringify the JSON object. This is how you lambda function should look like:

    exports.handler = (event, context, callback) => {
    
        const response = {
            statusCode: 200,
            body: JSON.stringify(event.input.serviceConfig).replace(/\"/g, '\\\"'),
        };
        callback(null, response)
    }; 
    

    You can now easily use the returned string in your resolver and get the stringified JSON.

    Link to my question, explanation and complete answer.