4

I have an existing GraphQL API that exposes a schema like this:

type AType {
    id: Int!
    name: String!
    children: [BType]
}

type BType {
    id: Int!
    name: String!
}

type Query {
    a(id: ID): A
    as: [A]
}

plus some other omitted scalar fields in both. There are a couple of such API endpoints and I want to aggregate them all under a single AppSync instance, so that the front can query one endpoint with a single schema for all the data they need.

What I would like to do is if the front sends a query

as {
    id,
    name,
    children {
      id,
      name
    }
}

it would get relayed exactly to my existing GraphQL endpoint. The AWS examples linked on the AppSync page talk about GraphQL endpoints but the only linked code example is this, and it shows a resolver like this:

#**
Make an arbitrary HTTP call when this field is listed in a query selection set.
The "relativePath" is the resource path relative to the root URL provided when you
created the HTTP data source. Pass a "params" object to forward headers, body,
and query parameters to the HTTP endpoint.
*#
#if($context.identity.sub == $context.args.userId) 
#set($payload = "query ListOrders {
  listOrders(
    userId: ""$context.args.userId""
    orderDateTimeStatus: {
        le : {
            orderDateTime: ""$context.args.orderDateTime""
        }
    }
    limit: 10
    
  ) {
    items {
      userId
      status
      orderDateTime
      details
      orderId
    }
    nextToken
  }
}")

{
    "version": "2018-05-29",
    "method": "POST",
    "resourcePath": "/graphql",
    "params":{
        "body": {
            "query": "$util.escapeJavaScript($payload)"
        },
        "headers":{
            "Content-Type": "application/json",
            "x-access-token" : "$context.request.headers.x-access-token"

        }
    }
}
#else 
  $utils.unauthorized() 
#end

This uses only the arguments passed into the query, not the query structure. If front requests a subset of fields of A, I only want to make a request for that subset of fields, not a request for all that then gets cut down by AppSync. Also it doesn't even contain nested objects -- would I have to fetch all the children every time just so that they get later ignored by AppSync?

Assume there are 4-5 microservices that have their own GraphQL endpoints that have different queries in their schemas. I'd like to map the requests 1-1 to them. How would I write such a resolver? AppSync doesn't really have a good playground environment where I could debug the resolver so I can't just look at the $ctx object and reverse-engineer the structure of the original query (AFAIK).

I found this question that asks just that, but the solution there doesn't work as intended, as mentioned by the author, and it seems to be dead.

V0ldek
  • 9,623
  • 1
  • 26
  • 57

0 Answers0