AWS appsync 查询解析器

AWS appsync query resolver

目前我的解析器是一个 lambda 函数:

import boto3
from boto3.dynamodb.conditions import Key

def lambda_handler(event, context):

  list = []
  for device in event['source']['devices'] :
      dynamodb = boto3.resource('dynamodb')
      readings  = dynamodb.Table('readings')
      response = readings.query(
          KeyConditionExpression=Key('device').eq(device['device'])
      )
      items = response['Items']
      list.extend(items)
  return list

我希望能够将其作为 dynamodb 上的 VTL 解析器。我的问题是我的 table 有一个排序键

这意味着我不能使用批处理解析器来查询一堆 ID,因为我还需要提供排序键,而且我只想要主分区键的所有结果。

你如何使用 VTL 查询一堆 ID,基本上是在 VTL 中复制我的 lambda 函数。这可能吗?

已添加架构,请原谅混乱,这是一项正在进行的工作,正在尝试很多事情。对 graphQL 还是很陌生

type Device {
    id: String
    device: String!
}

input DeviceInput {
    id: String
   device: String!
}

type DeviceReadings {
   devices: [Device]
}

type Mutation {
    createDevice(input: DeviceInput): Device
}

type PaginatedDevices {
   devices: [Device]
   readings: [Reading]
   cows: [cow]
   nextToken: String
}

type Query {
    getAllUserDevices(nextToken: String, count: Int): PaginatedDevices
    getAllDeviceReadings: DeviceReadings
    getAllUserReadings: DeviceReadings
    getAllReadings(deviceId: String!): Readings  
    getCowReadings(cowId: String!): UserCowReadings
}

type Reading {
   device: String
   time: Int
   cow: Int
   battery: String
}

type Readings {
    items: [Reading]
}

type UserCowReadings {
    devices: [Device]
    readings: [Reading]
}

type cow {
    id: Int
    device: String
    nait: String
}  

schema {
    query: Query
    mutation: Mutation
}

是的,您可以这样做,但您需要稍微调整一下架构。在那个 lambda 中,你实际上是在说 "for each device do a DynamoDB query to get the most recent readings for that device"。从概念上讲,我会说 设备 有许多 读数 。考虑到这一点,让我们制作一个模式:

type Device {
  id: ID!
  name: String
  # Get the most recent readings for this device.
  # Do a Query where "device = $ctx.source.id"
  readings(limit: Int, nextToken: String): ReadingConnection 
}

type Reading {
  # Use the source's device id in the table to fetch the real device
  # GetItem where device = $ctx.source.device (and any sort key condition)
  device: Device 
  time: Int
  cow: Int
  battery: String
}

type ReadingConnection {
  items: [Reading]
  nextToken: String
}

type DeviceConnection {
  items: [Device]
  nextToken: String
}

type Query {
  getAllDevices(limit: Int, nextToken: String): DeviceConnection
}

然后您可以对您的设备进行分页并分别对每个设备的读数进行分页:

query GetAllDevicesAndReadings {
  getAllDevices(first: 10) {
    items {
      id
      name
      readings(limit: 10) {
        time
        cow
        battery
      }
    }
  }
}

我建议使用 AppSync 控制台的解析器页面中的下拉列表来获取更多关于您可以使用解析器 VTL 执行这些 GetItems 和查询的想法。这是一个很好的起点。如果您在实施 VTL 时遇到问题,请告诉我。