如何定义AppSync Schema与Resolver,使GraphQL扫描DynamoDB返回键值对config_value?
Got it! Let's break down exactly how to set up your AppSync Schema and Resolvers to return the config_value as key-value pairs from your DynamoDB collection. I'll cover two common scenarios: returning the nested object directly as JSON, and converting it into a list of structured key-value pairs if that's what you prefer.
Step 1: Define the AppSync GraphQL Schema
First, we need to define types that match your data structure. Here are two options based on how you want the config_value returned:
Option 1: Return config_value as a JSON Object
This keeps the original nested structure intact and is the simplest approach:
# Define the main Config type matching your DynamoDB item type Config { config_name: String! config_value: JSON! # AppSync's built-in JSON scalar handles nested objects } # Define your Query operations type Query { # Fetch a single config by name (e.g., COLOR_PALETTE) getConfig(configName: String!): Config # Scan all configs in the DynamoDB table listAllConfigs: [Config] } # Ensure the JSON scalar is available (AppSync includes this by default) scalar JSON
Option 2: Return config_value as a List of Key-Value Pairs
If you want explicitly structured key-value entries instead of a raw JSON object, define a KeyValue type:
type KeyValue { key: String! value: String! } type Config { config_name: String! config_value: [KeyValue]! # Array of key-value pairs } type Query { getConfig(configName: String!): Config listAllConfigs: [Config] }
Step 2: Configure DynamoDB Resolvers
Now let's set up the VTL (Velocity Template Language) resolvers for each query. I'll assume your DynamoDB table uses config_name as the primary key, and config_value is stored as a stringified JSON (a common practice). If it's stored as a DynamoDB Map (M type), I'll note the adjustment needed.
Resolver for getConfig (Single Item Query)
Request Template
This template fetches a single item by config_name:
{ "version": "2017-02-28", "operation": "GetItem", "key": { "config_name": { "S": "${ctx.args.configName}" } } }
Response Template (Option 1: JSON Object)
Parse the stringified config_value into a JSON object and return it:
# If config_value is stored as a stringified JSON (S type) $util.toJson({ "config_name": $ctx.result.config_name.S, "config_value": $util.parseJson($ctx.result.config_value.S) }) # If config_value is stored as a DynamoDB Map (M type), use this instead: # $util.toJson({ # "config_name": $ctx.result.config_name.S, # "config_value": $util.dynamodb.toJsonObject($ctx.result.config_value) # })
Response Template (Option 2: Key-Value List)
Convert the nested object into an array of KeyValue entries:
# Parse the stored config_value into a JSON object #set($configValueObj = $util.parseJson($ctx.result.config_value.S)) #set($keyValuePairs = []) # Loop through each key-value entry in the object #foreach($entry in $configValueObj.entrySet()) #set($kv = { "key": $entry.key, "value": $entry.value }) #set($discard = $keyValuePairs.add($kv)) #end # Format and return the final result $util.toJson({ "config_name": $ctx.result.config_name.S, "config_value": $keyValuePairs })
Resolver for listAllConfigs (Scan Operation)
Request Template
This template scans the entire DynamoDB table:
{ "version": "2017-02-28", "operation": "Scan" }
Response Template (Option 1: JSON Object)
Map over all scanned items and parse each config_value:
# If config_value is stored as stringified JSON $util.toJson($ctx.result.items.map(item => ({ config_name: item.config_name.S, config_value: $util.parseJson(item.config_value.S) }))) # If config_value is a DynamoDB Map, use: # $util.toJson($ctx.result.items.map(item => ({ # config_name: item.config_name.S, # config_value: $util.dynamodb.toJsonObject(item.config_value) # })))
Response Template (Option 2: Key-Value List)
Process each item to convert config_value into key-value pairs:
#set($finalResults = []) #foreach($item in $ctx.result.items) #set($configValueObj = $util.parseJson($item.config_value.S)) #set($keyValuePairs = []) #foreach($entry in $configValueObj.entrySet()) #set($kv = { "key": $entry.key, "value": $entry.value }) #set($discard = $keyValuePairs.add($kv)) #end #set($configItem = { "config_name": $item.config_name.S, "config_value": $keyValuePairs }) #set($discard = $finalResults.add($configItem)) #end $util.toJson($finalResults)
Quick Notes
- Storage Type Check: Double-check how
config_valueis stored in DynamoDB. If you used the AWS SDK's DocumentClient, it might be stored as a Map (Mtype) instead of a string — adjust the response template accordingly using$util.dynamodb.toJsonObject. - JSON Scalar: AppSync includes the
JSONscalar by default, but if you run into issues, you can explicitly define it in your schema as shown.
内容的提问来源于stack exchange,提问作者Randima Lahiru

