How to Handle Many to Many relations in AppSync

query {
getGroupUsers(id: ID!) {
id
name
# bio and picture are not denormalized in the relation
bio
picture
}
}
query {
getGroupUsers(id: ID!) {
joinedAt
user {
id
name
bio
picture
}
}
}
## getGroupUsers - request mapping
#set($limit=$util.defaultIfNull($ctx.args.limit, 10))
#if($limit>100)
#set($limit=100)
#end
{
"version": "2018-05-29",
"operation": "Query",
"limit": $util.toJson($limit),
"nextToken": $util.toJson($ctx.args.nextToken),
"query" : {
"expression": "#PK = :PK and begins_with(#SK, :SK)",
"expressionNames" : {
"#PK": "PK",
"#SK": "SK"
},
"expressionValues" : {
":PK": $util.dynamodb.toStringJson("GROUP#${ctx.args.id}"),
":SK": $util.dynamodb.toStringJson("USER#")
}
}
}
## getGroupUsers - response mapping
$util.qr($ctx.stash.put("nextToken", $ctx.result.nextToken))
$util.toJson($ctx.result.items)
## getBatchUsers - request mapping
#if($ctx.prev.result.size() == 0)
#return([])
#end
#set($keys=[])
#foreach($item in $ctx.prev.result)
## the user and PK/SK is the SK from the Item received from the previous function
$util.qr($keys.add({
"PK": $util.dynamodb.toDynamoDB(${item.SK}),
"SK": $util.dynamodb.toDynamoDB(${item.SK})
}))
#end
{
"version": "2018-05-29",
"operation": "BatchGetItem",
"tables" : {
## replace this with your table's name
"table-name": {
"keys": $util.toJson($keys)
}
}
}
## getBatchUsers - response mapping
#set($items=[])
#foreach($item in $ctx.result.data.get("table-name"))
#set($groupUser=$ctx.prev.result.get($foreach.index))
$util.qr($groupUser.put("user", $item))
$util.qr($items.add($groupUser))
#end
$util.toJson($items)
## getUsers - after mapping
$util.toJson({
"nextToken": $ctx.stash.nextToken,
"items": $ctx.result
})

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store