mutation to create relations on AWS AppSync - amazon-web-services

I have been trying to run a mutation to create relations to two separate Types with not much success.
** SCHEMA **
(I have used "Create Resources" to create tables in DynamoDB)
type Comment {
eventId: ID!
commentId: String!
content: String
}
type CommentConnection {
items: [Comment]
nextToken: String
}
input CreateCommentInput {
eventId: ID!
commentId: String!
content: String
}
input CreateEventInput {
id: ID!
name: String
where: String
when: String
description: String
}
input DeleteCommentInput {
eventId: ID!
}
input DeleteEventInput {
id: ID!
}
type Event {
id: ID!
name: String
where: String
when: String
description: String
comments(limit: Int, nextToken: String): CommentConnection
}
type EventConnection {
items: [Event]
nextToken: String
}
type Mutation {
createEvent(input: CreateEventInput!): Event
updateEvent(input: UpdateEventInput!): Event
deleteEvent(input: DeleteEventInput!): Event
createComment(input: CreateCommentInput!): Comment
updateComment(input: UpdateCommentInput!): Comment
deleteComment(input: DeleteCommentInput!): Comment
commentOnEvent(input: commentOnEventInput!): Comment
}
type Query {
fetchEvent(id: ID!): Event
getEvent(id: ID!): Event
listEvents(first: Int, after: String): EventConnection
getComment(eventId: ID!): Comment
listComments(first: Int, after: String): CommentConnection
}
type Subscription {
onCreateEvent(
id: ID,
name: String,
where: String,
when: String,
description: String
): Event
#aws_subscribe(mutations: ["createEvent"])
onUpdateEvent(
id: ID,
name: String,
where: String,
when: String,
description: String
): Event
#aws_subscribe(mutations: ["updateEvent"])
onDeleteEvent(
id: ID,
name: String,
where: String,
when: String,
description: String
): Event
#aws_subscribe(mutations: ["deleteEvent"])
onCreateComment(eventId: ID, commentId: String, content: String): Comment
#aws_subscribe(mutations: ["createComment"])
onUpdateComment(eventId: ID, commentId: String, content: String): Comment
#aws_subscribe(mutations: ["updateComment"])
onDeleteComment(eventId: ID, commentId: String, content: String): Comment
#aws_subscribe(mutations: ["deleteComment"])
}
input UpdateCommentInput {
eventId: ID!
commentId: String
content: String
}
input UpdateEventInput {
id: ID!
name: String
where: String
when: String
description: String
}
input commentOnEventInput {
eventId: ID!
content: String
}
schema {
query: Query
mutation: Mutation
subscription: Subscription
}
** MUTATIONS **
mutation #1:
mutation {
createEvent(input: {
id: "id8888"
name: "some event"
where: "Tokyo"
when: "tomorrow"
description: "desc for event"
})
{
id
name
}
}
mutation #1 gives:
{
"data": {
"createEvent": {
"id": "id8888",
"name": "some event"
}
}
}
mutation #2:
mutation {
commentOnEvent(input : {
eventId: "id8888"
commentId: "id2222"
content: "some content"
})
{
commentId
content
}
}
mutation #2 gives:
{
"data": {
"commentOnEvent": null
}
}
In the React sample created by AWS AppSync creates commentId automatically but I can't recreate that in manually created schema and resource.
I would like to know how I can establish relations on separate types and query them. Has anybody successfully done this??

Starting from the console's “Create resources” functionality lets talk through how this works. Assume we have this schema.
type Comment {
eventId: ID!
commentId: String!
content: String
}
type CommentConnection {
items: [Comment]
nextToken: String
}
input CreateCommentInput {
eventId: ID!
commentId: String!
content: String
}
input CreateEventInput {
id: ID!
name: String
where: String
when: String
description: String
}
input DeleteCommentInput {
eventId: ID!
}
input DeleteEventInput {
id: ID!
}
type Event {
id: ID!
name: String
where: String
when: String
description: String
comments(limit: Int, nextToken: String): CommentConnection
}
type EventConnection {
items: [Event]
nextToken: String
}
type Mutation {
createEvent(input: CreateEventInput!): Event
updateEvent(input: UpdateEventInput!): Event
deleteEvent(input: DeleteEventInput!): Event
createComment(input: CreateCommentInput!): Comment
updateComment(input: UpdateCommentInput!): Comment
deleteComment(input: DeleteCommentInput!): Comment
}
type Query {
getEvent(id: ID!): Event
listEvents(first: Int, after: String): EventConnection
getComment(eventId: ID!): Comment
listComments(first: Int, after: String): CommentConnection
}
type Subscription {
onCreateEvent(
id: ID,
name: String,
where: String,
when: String,
description: String
): Event
#aws_subscribe(mutations: ["createEvent"])
onUpdateEvent(
id: ID,
name: String,
where: String,
when: String,
description: String
): Event
#aws_subscribe(mutations: ["updateEvent"])
onDeleteEvent(
id: ID,
name: String,
where: String,
when: String,
description: String
): Event
#aws_subscribe(mutations: ["deleteEvent"])
onCreateComment(eventId: ID, commentId: String, content: String): Comment
#aws_subscribe(mutations: ["createComment"])
onUpdateComment(eventId: ID, commentId: String, content: String): Comment
#aws_subscribe(mutations: ["updateComment"])
onDeleteComment(eventId: ID, commentId: String, content: String): Comment
#aws_subscribe(mutations: ["deleteComment"])
}
input UpdateCommentInput {
eventId: ID!
commentId: String
content: String
}
input UpdateEventInput {
id: ID!
name: String
where: String
when: String
description: String
}
schema {
query: Query
mutation: Mutation
subscription: Subscription
}
This is what the schema should look like after running Create Resources on the Event and Comment types. When going through the "Create Resources" flow with the Comment type you should choose the eventId as the table's hash key and the commentId as the sort key. For the Event type you can leave "id" as the single hash key. So what did that do for us?
First it created 2 DynamoDB tables to hold our objects of type Event and Comment. It then imported those tables as AppSync data sources and generated new schema parts including input objects, objects, and query and mutation fields and saved them to the schema. It also wired up resolvers specific to the new table you just defined and attached them to the newly generated query and mutation fields that implement common CRUD patterns. Unfortunately this does not yet understand relations so we have to add those ourselves. To do that let's first make the mutation to create relations as you have asked about and for completeness we will do a query as well.
As you have already done, you are going to need to add something like this to your schema
type Mutation {
commentOnEvent(input: CommentOnEventInput!): Comment
}
input CommentOnEventInput {
eventId: ID!
content: String
}
Save the schema and then click "Attach" on the Mutation.commentOnEvent field to add a resolver. Select the CommentTable data source we created earlier and from the mapping template put this:
{
"version" : "2017-02-28",
"operation" : "PutItem",
"key" : {
"eventId": $util.dynamodb.toDynamoDBJson($ctx.args.input.eventId),
"commentId": $util.dynamodb.toDynamoDBJson($util.autoId()),
},
"attributeValues" : $util.dynamodb.toMapValuesJson($ctx.args.input)
}
and for the response mapping template
$util.toJson($context.result)
Click save. Now you should be able to run a query like this:
mutation {
commentOnEvent(input: { eventId: "***", content: "A comment"}) {
eventId
content
}
}
Let's now add away to read data via a relation. E.G. I want to be able to run a query like this:
query {
getEvent(id: "***") {
id
comments(first: 5) {
items {
content
}
}
}
}
To do this lets first add the following parts to the schema.
type Event {
# add this to existing fields
comments(first: Int, after: String): CommentConnection
}
Click save then click "Attach" on the Event.comments field. Select the CommentTable data source again and then provide the following for the request mapping template.
# Event.comments.request.vtl
{
"version" : "2017-02-28",
"operation" : "Query",
"query" : {
"expression": "eventId = :eventId",
"expressionValues" : {
":eventId" : {
"S" : "${ctx.source.id}"
}
}
},
"limit": $util.defaultIfNull(${ctx.args.first}, 20),
"nextToken": $util.toJson($util.defaultIfNullOrBlank($ctx.args.after, null))
}
Notice the $ctx.source.id. Since we are resolving the Event.comments field, the $ctx.source is the instance of the Event type that we are resolving comments for. In effect this makes it so that anywhere we include { comments { ... } in a selection set on the Event type, only comments for the parent event will be fetched. And then you can return the paginated result object.
# Event.comments.response.vtl
# $ctx.result = { items: [...], nextToken: "..." }
$util.toJson($ctx.result)
This should do the trick. Now you can run both these queries and see the results.
mutation {
commentOnEvent(input: { eventId: "***", content: "A comment"}) {
eventId
content
}
}
query {
getEvent(id: "***") {
id
comments(first: 5) {
items {
content
}
}
}
}
Hope this helps.

Related

Filter Expression can only contain non-primary key attributes

I'm new to AWS Amplify, and have created a GraphQL API for a project that I'm working on in order to learn it & AppSync. Essentially I have a schema that looks like the following:
type User #model {
id: ID! #primaryKey
boards: [Board] #hasMany
createdAt: String!
updatedAt: String!
}
type Board #model {
id: ID! #primaryKey
createdBy: User!
title: String!
}
and I'm trying to run the following query in the AppSync console:
query MyQuery {
listUsers {
items {
boards {
items {
title
}
}
}
}
}
But for some reason I keep seeing this error:
Filter Expression can only contain non-primary key attributes: Primary key attribute: userBoardsId
I've specified the primary key in both models, and I'm aware that AppSync generates the 'userBoardsId' foreign key, but I'm not sure why it's causing an issue.
Have you tried like this? Since boards is array, you need to add items
query MyQuery {
listUsers {
items {
boards {
items {
title
}
}
}
}
}
EDIT:
type User #model {
id: ID! #primaryKey
boards: [Board] #hasMany (indexName: "byUser")
createdAt: String!
updatedAt: String!
}
type Board #model {
id: ID! #primaryKey
userID: ID! #index(name: "byUser")
createdBy: User
title: String!
}

How to query a list on AppSync GraphQL by a nested object

I am using AWS AppSync GraphQL and am trying to filter a list by a nested object's value.
My schema looks like this:
type Post #model {
id: ID
title: String
content: String
hidden: Boolean
}
type PinnedPost #model
{
id: ID!
userID: ID #index(name: "byUser", sortKeyFields: ["postID"])
user: User #hasOne (fields: ["userID"])
postID: ID
post: Post #hasOne (fields: ["postID"])
}
I would like to run a query to list the PinnedPost for a user, but filter out the hidden ones, like so:
const pinnedData = await API.graphql(graphqlOperation(
listPinnedPosts, {
filter: {
userID: {
eq: userInfo.attributes.sub
},
post: {
hidden: {
eq: false
},
}
}
}
))
I have updated the filterinput in my Schema through the AppSync Console to:
input ModelPinnedPostFilterInput {
id: ModelIDInput
userID: ModelIDInput
postID: ModelIDInput
post: ModelPostFilterInput
and: [ModelPinnedPostFilterInput]
or: [ModelPinnedPostFilterInput]
not: ModelPinnedPostFilterInput
}
There are no errors associated with it, but the nested filter is not being applied as it will return both true and false values for hidden.
This question was sort of answered before:
Appsync & GraphQL: how to filter a list by nested value
but it is not clear to me where I am supposed to edit the mapping template to allow this. How can I achieve this result?

AWS Amplify GraphQL Query For Null Connections

I have the following in my schema for my AWS Amplify project:
type DriveTime #model
#auth( rules: [
{allow: groups, groups: ["Admin", "Instructor"]},
{ allow: private, provider: iam }
]) {
id: ID!
start: AWSDateTime!
end: AWSDateTime!
openRegistration: AWSDateTime!
closeRegistration: AWSDateTime!
vehicle: Vehicle #connection(name: "VehicleDriveConnection")
instructor: Instructor #connection(name: "InstructorDriveConnection") #aws_cognito_user_pools #aws_iam
student: Student #connection(name: "StudentDriveConnection")
evaluation: DriveEvaluation #connection(name: "DriveEvaluationConnection")
}
I want to be able to list all drive times where the student connection is empty or null. I am able to get all driveTimes for a single student but not all driveTimes where there is no student.
Since I dont want students to be able to access drive times that are either not open for registration or already registered to another student I have added this to my schema:
type AvailableDriveTime {
id: ID!
start: AWSDateTime!
end: AWSDateTime!
openRegistration: AWSDateTime!
closeRegistration: AWSDateTime!
instructorFirstName: String!
instructorLastName: String!
}
type Query {
listAvailableDriveTimes(limit: Int, nextToken: String): AvailableDriveTimesConnection #function(name: "listAvailableDriveTimes-${env}") #aws_cognito_user_pools #aws_iam
}
And this is my current query in the Lambda resolver:
let currentDate = new Date();
const listDrives = `query ListDrives($limit: Int, $nextToken: String) {
listDriveTimes(limit: $limit, nextToken: $nextToken, filter: {and: {openRegistration: {le: "${currentDate.toISOString()}"}, closeRegistration: {ge: "${currentDate.toISOString()}"}}}) {
items {
id
start
end
openRegistration
closeRegistration
instructor {
firstName
lastName
}
student {
username
}
}
nextToken
}
}`
My current solution is sorting in the lambda resolver then returning the right data but it seems like there has to be a more efficient way.

AWS Appsync Graphql query to get list of items returns empty array even though the dynamodb table has items in it

I'm running an Angular 11 application that is integrated with AWS Amplify and Appsync using GraphQL and dynamoDB for the backend.
This is my Graphql schema:-
type School
#model
#auth(
rules: [{ allow: owner, ownerField: "admins", operations: [update, read] }]
) {
id: ID!
name: String!
admins: [Member]
classes: [Class] #connection(name: "SchoolClasses")
members: [Member] #connection(name: "SchoolMembers")
}
type Class
#model
#auth(
rules: [{ allow: owner, ownerField: "admins", operations: [update, read] }]
) {
id: ID!
name: String!
school: School #connection(name: "SchoolClasses")
admins: [Member]
members: [Member] #connection(name: "ClassMembers")
}
type Member #model #auth(rules: [{ allow: owner }]) {
id: ID!
name: String!
school: School #connection(name: "SchoolMembers")
class: Class #connection(name: "ClassMembers")
}
This is my client definition:-
const client = new AWSAppSyncClient({
url: awsconfig.aws_appsync_graphqlEndpoint,
region: awsconfig.aws_appsync_region,
auth: {
type: awsconfig.aws_appsync_authenticationType,
jwtToken: async () =>
(await Auth.currentSession()).getAccessToken().getJwtToken(),
},
complexObjectsCredentials: () => Auth.currentCredentials(),
cacheOptions: {
dataIdFromObject: (obj: any) => `${obj.__typename}:${obj.myKey}`,
},
});
This is my query method:-
client
.query({
query: ListSchools,
})
.then((data: any) => {
console.log('data from listSchools ', data);
console.log(data.data.listSchools.items);
});
};
This is my query definition:-
import gql from 'graphql-tag';
export default gql`
query ListSchools(
$filter: ModelSchoolFilterInput
$limit: Int
$nextToken: String
) {
listSchools(filter: $filter, limit: $limit, nextToken: $nextToken) {
items {
id
name
admins {
id
name
createdAt
updatedAt
owner
}
classes {
nextToken
}
members {
nextToken
}
createdAt
updatedAt
}
nextToken
}
}
`;
The output for data in the console looks like this:-
{
"data":{
"listSchools":{
"items":[],
"nextToken":null,
"__typename":"ModelSchoolConnection"
}
},
"loading":false,
"networkStatus":7,
"stale":false
}
As you can see, the items is an empty array. But currently I have 3 items in my dynamoDB table:-
What am I doing wrong?
I have checked the regions to see if it is querying a different region, but it is checking the correct region, so I should be seeing the results. Also, wouldn't it throw an error if we're querying the wrong table?
I figured it out. The issue was in the GraphQL Schema definition where I had set the #auth paramter to only allow a certain admin to access the list, that's why I was getting back an empty array. I removed the #auth parameter and it now gives back the proper list of items.

Should I extend my type with extra fields or create a new type?

I have TODO templates which are used to create todos in todo lists.
Should I create one type for both templates and created todos like this:
type TODO {
id: ID
text: String
type: String
templateId: ID
completed: Boolean
}
type TODOList {
id: ID
todos: [TODO]
owner: String
}
Or should I make separate types for templates and created todos?
type TODO {
id: ID
text: String
type: String
templateId: ID
completed: Boolean
}
type TODOTemplate {
id: ID
templateType: String
templateText: String
}
type TODOList {
id: ID
todos: [TODO]
owner: String
}
Or maybe there is more convenient method and I am doing everything wrong?
the second one looks better since you've introduced extra fields and probably want access to them. in that case you'll want to revise your TODO type:
type TODO {
id: ID
text: String
type: String
template: TODOTemplate
completed: Boolean
}