'AppSync GraphQL Skip Field if Not Owner
I'm querying for a list of objects but want to filter out some of the fields if the object is not owned by the caller.
I've tried multiple different approaches but I'm not quite there yet.
I know of the @include or @skip directive.. So for instance if I have the following model :
type Blog @model @auth(rules: [{allow:owner}{allow:private}])
{
id: ID!
name: String @auth (rules: [{allow:owner}])
posts: [Post] @hasMany
}
I'd like to query for a list of all "Blogs" but if the user is not the "Owner" then @skip the name field in the response.
query MyQuery ($isOwner:Boolean = (owner == ${user}){
listBlogs {
items {
id
name (@include:$isOwner)
owner
}
}
}
This is obviously bad code as it doesn't like the $isOwner:Boolean ... But I think I'm close. Now I think I may need something in the VTL code. This is the autogenerated code but I'm not with VTL. But I'm guessing this is where I need to put some bit of code so I can use it in the GraphQL query above...
## [Start] List Request. **
#set( $args = $util.defaultIfNull($ctx.stash.transformedArgs, $ctx.args) )
#set( $limit = $util.defaultIfNull($args.limit, 100) )
#set( $ListRequest = {
"version": "2018-05-29",
"limit": $limit
} )
#if( $args.nextToken )
#set( $ListRequest.nextToken = $args.nextToken )
#end
#if( !$util.isNullOrEmpty($ctx.stash.authFilter) )
#set( $filter = $ctx.stash.authFilter )
#if( !$util.isNullOrEmpty($args.filter) )
#set( $filter = {
"and": [$filter, $args.filter]
} )
#end
#else
#if( !$util.isNullOrEmpty($args.filter) )
#set( $filter = $args.filter )
#end
#end
#if( !$util.isNullOrEmpty($filter) )
#set( $filterExpression = $util.parseJson($util.transform.toDynamoDBFilterExpression($filter)) )
#if( !$util.isNullOrBlank($filterExpression.expression) )
#if( $filterExpression.expressionValues.size() == 0 )
$util.qr($filterExpression.remove("expressionValues"))
#end
#set( $ListRequest.filter = $filterExpression )
#end
#end
#if( !$util.isNull($ctx.stash.modelQueryExpression) && !$util.isNullOrEmpty($ctx.stash.modelQueryExpression.expression) )
$util.qr($ListRequest.put("operation", "Query"))
$util.qr($ListRequest.put("query", $ctx.stash.modelQueryExpression))
#if( !$util.isNull($args.sortDirection) && $args.sortDirection == "DESC" )
#set( $ListRequest.scanIndexForward = false )
#else
#set( $ListRequest.scanIndexForward = true )
#end
#else
$util.qr($ListRequest.put("operation", "Scan"))
#end
#if( !$util.isNull($ctx.stash.metadata.index) )
#set( $ListRequest.IndexName = $ctx.stash.metadata.index )
#end
$util.toJson($ListRequest)
## [End] List Request. **
Am I on the right track? What would be the VTL and/or GraphQL code? Somehow I need to get the $context.identity I think into the VTL using a #set in the VTL code I think? Then use it in the GraphQL?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
