Search code examples
graphqlhttp-headersaws-api-gatewayaws-appsync

How can Appsync request headers by passed to a child resolver?


I have an Appsync Schema which defines a User type which itself contains a List of Notes:

type User {
  id: ID!
  name: String!
  notes: [Note]
}

type Note {
  id: ID!
  text: String!
}

In the request mapping for the User, I am able to access the headers from the request, to access the Bearer token:

{
    "version": "2018-05-29",
    "method": "GET",
    "resourcePath": $util.toJson("/prod/user/$ctx.args.userId"),
    "params":{
        "headers":{
            "Content-Type": "application/json",
            "Authorization": "Bearer $ctx.request.headers.Authorization",
        }
    }
}

This works well and the header is passed to the data source.

The resolver for the User.notes field is a Lambda resolver which itself iteratively calls a similar API GET /prod/user/{userId}/notes/{noteId}. I am able to access the Parent resolvers response data using $ctx.source.... However, I also need to be able to pass through the Authorization header (e.g. $ctx.request.headers.Authorization).

I have tried this in the User response mapping, but it does not work:

#set($results = $ctx.result.body)
#set($headers = {
        "Authorization": "Bearer $ctx.request.headers.Authorization"
    })
#set($results.headers = $headers)
$results

My question is, how can I pass the request headers from a Parent resolver to a Child resolver? Perhaps another way to ask the question would be, given I have a Bearer token on the Graphql request header, how can I ensure it is always passed to any resolvers which are called?


Solution

  • As @Myz mention in their comment, the solution was to use a Pipeline Resolver.

    In the end, I pushed the header into the $ctx.stash object (which is available to all functions within a Pipeline Resolver) - I did this using:

    $util.qr($ctx.stash.put("bearerToken", "Bearer $ctx.request.headers.Authorization"))
    

    I was then able to access this value in each of the Functions (i.e. the child resolvers) using: "$ctx.stash.bearerToken"