【问题标题】:Appsync - How to return response from multiple functions in pipleline resolversAppsync - 如何从管道解析器中的多个函数返回响应
【发布时间】:2019-12-27 07:39:46
【问题描述】:
input CarInput{ 
    name: String
    brand: String
}

type Car{   
    id: ID  
    name: String    
    brand: String
}

type Vehicle{   
    id: ID  
    carId: Id
}    

type CustomResponse{
    createdCar : Car
    allCars: [Car]
}

type Mutation {
    createCar(input: CarInput): CustomResponse
}

createCar

的附加管道解析器

映射模板之前

{}

1 - CreateCarFunction

请求映射模板

{
  "version" : "2017-02-28",
  "operation": "Invoke",
  "payload":{ 
  "body":$util.toJson($context.args.input),
  "resource":"/car",
  "httpmethod":"POST"
  }
}

响应映射模板

$context.result.body

2 - CreateVehicleFunction

请求映射模板

{
  "version" : "2017-02-28",
  "operation": "Invoke",
  "payload":{ 
  "body":$util.toJson($ctx.prev.result.id),
  "resource":"/vehicle",
  "httpmethod":"POST"
  }
}

响应映射模板

$context.result.body

3 - GetCarsFunction

请求映射模板

{
  "version" : "2017-02-28",
  "operation": "Invoke",
  "payload": {  
  "body":"",
  "resource":"/getCars" ,
  "httpmethod":"GET"
  }
}

响应映射模板

$context.result.body

映射后模板

 $util.toJson($ctx.result)

数据源是Lamda。我会从 CreateCarFunctionCreateVehicleFunctionGetCarsFunction 得到三种不同的响应。

mutation{createCar(input:
{
 name: "A6"
 brand: "Audi"
})
 {
   createdCar  
   {
     id
     name
     brand
   }

   allCars
   {
     id
     name
     brand
   }   
 }

我想要这样的回应

{
  "data": {
    "createCar": {
      "createdCar  ": {
                        id : "2"
                        name : "A6"
                        brand : "Audi"
                      },
      "allCars":  [
                     {
                        id : "1"
                        name : "S"
                        brand : "Benz"
                     },
                     {
                        id : "2"
                        name : "A6"
                        brand : "Audi"
                     }
                 ]

          }
}

所以我需要 CreateCarFunctionGetCarsFunction 的响应,以便将 CustomResponse 类型填充为输出。我如何做到这一点?

【问题讨论】:

    标签: aws-appsync


    【解决方案1】:

    感谢您提供此问题的所有相关详细信息。您可以通过将输出(在响应映射模板中)添加到 $ctx.stash 来将数据从一个函数传递到下一个函数。 $ctx.stash 是一个可变对象,在管道解析器的整个生命周期中都将持续存在。

    将每个函数的响应映射模板修改为类似

    创建汽车函数

    $util.qr($ctx.stash.put("createdCar", $ctx.result.body))
    $context.result.body
    

    GetCarsFunction

    $util.qr($ctx.stash.put("allCars", $ctx.result.body))
    $context.result.body
    

    (第一行将结果添加到存储中。第二行像以前一样返回请求的正文。)

    然后在你的映射模板之后,你可以反序列化结果

    $util.toJson($ctx.stash)
    

    【讨论】:

    • 最终使用$util.toJson($ctx.stash) 效果很好!
    猜你喜欢
    • 2021-04-19
    • 2021-04-27
    • 1970-01-01
    • 2017-11-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-18
    • 2021-11-28
    • 1970-01-01
    相关资源
    最近更新 更多