Today I tried to add a 'name' field to the 'User' type of my AWS GraphQL schema. After running "amplify push" and "code gen", I received an error from AWS saying that 'owner' was null. After comparing my git history side by side, I found that codegen deleted the autogenerated owner field in my queries while simultaneously adding two new fields, 'createdAt' and 'updatedAt'. Unsure how/why this was happening, I reverted to an earlier git commit where everything was working fine and pushed to amplify. All my files were reverted back to a commit where everything was working perfectly. However, I am still receiving errors that 'owner' is null. GraphQL schema and screenshots of terminal are below. Happy to provide other files (queries, mutations, etc.) if helpful.
type Image {
bucket: String!
region: String!
key: String!
}
type Circle
#model
#auth(rules: [
{ allow: owner, operations: [create, delete] }
]) {
id: ID!
name: String!
username: String!
password: String
bio: String
avatar: Image
favors: [CircleFavor] #connection(name: "CirclesFavors")
users: [CircleUser] #connection(name: "CirclesUsers")
pendingUsers: [User] #connection
tags: [String]
admin: User #connection
isPrivate: Boolean!
poster: ID!
}
type Favor
#model
#auth(rules: [
{ allow: owner, operations: [create, delete] }
]) {
id: ID!
name: String
description: String
location: String
deadline: AWSDateTime
circles: [CircleFavor] #connection(name: "FavorsCircles")
price: Float!
}
type CircleFavor
#model(queries: { get: "getCircleFavor" })
#auth(rules: [
{ allow: owner, operations: [create, delete] }
]) {
id: ID!
circle: Circle! #connection(name: "CirclesFavors")
favor: Favor! #connection(name: "FavorsCircles")
poster: User! #connection(name: "UsersFavors")
}
type User
#model(
queries: { get: "getUser" }
mutations: { create: "registerUser", update: "updateUser" }
subscriptions: null
)
#auth(rules: [
{ allow: owner, operations: [create, delete] }
]) {
id: ID!
username: String!
bio: String
email: AWSEmail
isRegistered: Boolean
orders: [Order] #connection(name: "UsersOrders")
circles: [CircleUser] #connection(name: "UsersCircles")
favors: [CircleFavor] #connection(name: "UsersFavors")
}
type CircleUser
#model(queries: { get: "getCircleUser" })
#auth(rules: [
{ allow: owner, operations: [create, delete] }
]) {
id: ID!
circle: Circle! #connection(name: "CirclesUsers")
user: User! #connection(name: "UsersCircles")
}
type Order
#model(
queries: null
mutations: { create: "createOrder" }
subscriptions: null
)
#auth(rules: [
{ allow: owner, operations: [create, delete] }
]) {
id: ID!
favor: Favor #connection
claimer: User #connection(name: "UsersOrders")
additional_costs: Float
isCompletedByClaimer: Boolean!
isApprovedByPoster: ApprovalStatus!
}
enum ApprovalStatus {
PENDING
APPROVED
DISPUTED
}
Bad news: You dropped those fields from the database. The owner data is gone, which is why it's coming back NULL now that you re-added it to the schema.
Related
My goal is to write an app where users can add a list of Items (lets say 20-30) to every Entry... There would be one entry per day and the number of items would be different each time.
I have two GraphQL types which look like this:
type Entry #model #auth(rules: [{allow: public}]) {
id: ID!
date: String!
entries: [Item] #hasMany
}
type Item #model #auth(rules: [{allow: public}]) {
id: ID!
name: String!
received: Boolean!
quantity: String!
hazardRating: Int!
entry: Entry #belongsTo
comments: [Comment] #hasMany
}
type Comment #auth(rules: [{allow: public}]) #model {
id: ID!
item: Item #belongsTo
content: String!
}
I want to write a mutation which adds an Item to an existing Entry:
I have tried this:
mutation createItem{
createItem( input:{name: "Sodium Hydroxide", received: true, quantity: "1L", hazardRating: 3, entry: {id = "7a59cfca-db53-4f15-8ae6-c37e025b2a44", date = "21 October 2022" }) {
id
name
received
quantity
hazardRating
entry {
id
date
}
}
}
but I get the error message "entry" does not exist on type Item...
How would I write a mutation that would add an Item to an existing Entry?
Is it even possible to do so or is it only possible to add all the Items per Entry at the same time?
I was missing references in Item.
In order that Item is recognised as part of Entry - you have to add entryID: ID! #index(name: "byEntry", sortKeyFields: ["name"]) into Item and also an indexName parameter into entry: (indexName: "byEntry", fields: ["id"])
Unlike GraphQL v1 - v2 fails to do this automatically when you start a schema from scratch so you have to make sure each type references each other.
The whole scheme looks like this:
type Entry #model #auth(rules: [{allow: public}]) {
id: ID!
date: String!
items: [Item] #hasMany(indexName: "byEntry", fields: ["id"])
}
type Item #model #auth(rules: [{allow: public}]) {
id: ID!
entryID: ID! #index(name: "byEntry", sortKeyFields: ["name"])
name: String!
amount: String!
hazardRating: Int!
comments: [Comment] #hasMany(indexName: "byItem", fields: ["id"])
}
type Comment #model #auth(rules: [{allow: public}]) {
id: ID!
itemID: ID! #index(name: "byItem" sortKeyFields: ["content"])
content: String!
}
I have been following a YouTube tutorial to create and sell books online. In the tutorial, there has been a case of designing a GraphQL scheme for the orders. I have seen that the migrate details have been updated and have tried to adhere to the new regulations,I have faced a lot of errors. I tried solving most of them but some remain persistent. As this is my first time working with Graphql and AWS, I cannot progress any further. Youtube Link is provided below:
https://youtu.be/cWDJoK8zw58
type Book
#model(subscriptions: null)
#auth(
rules: [
#allow admins to create, update and delete books
{ allow: groups, groups: ["Admin"] }
# allow all authenticated users to view books
{ allow: private, operations: [read] }
# allow all guest users (not authenticated) to view books
{ allow: public, operations: [read] }
]
)
{
id: ID!
title: String!
description: String
image: String
author: String
featured: Boolean
price: Float
orders: [BookOrder] #hasOne(keyName: "byBook", fields: ["id"])
}
type BookOrder
#model(queries: null, subscriptions: null)
##key(name: "byBook", fields: ["book_id", "order_id"])
##key(name: "byOrder", fields: ["order_id", "book_id"])
#auth(
rules: [
# allow admins to create bookorders for customers by using customer email in lambda
{ allow: owner, identityClaim: "email", ownerField: "customer" }
{ allow: groups, groups: ["Admin"] }
]
)
{
id: ID!
book_id: ID! #index(name: "byBook", sortKeyFields: ["book_id, order_id"])
order_id: ID! #index(name: "byOrder", sortKeyFields: ["order_id, book_id"])
book: Book #hasOne(fields: ["book_id"])
order: Order #hasOne(fields: ["order_id"])
}
type Order
#model(subscriptions: null)
#auth(
rules: [
# only owner can see his orders
{ allow: owner, identityClaim: "email", ownerField: "customer" }
#allow admins to view orders
{ allow: groups, groups: ["Admin"] }
]
)
##key(name: "byUser", fields: ["user"])
{
id: ID!
user: String! #index(name: "byUser", sortKeyfields: ["user"])
date: String
total: Float
books: [BookOrder] #manyToMany(keyName: "byOrder", fields: ["id"])
}
enum OrderStatus {
SUCCESS
FAILED
}
input CartItem {
id: ID!
title: String
image: String
price: Float
amount: Int
}
input ProcessOrderInput {
id: ID!
cart: [CartItem]
total: Float!
token: String!
address: String
}
type Mutation {
processOrder(input: ProcessOrderInput!): OrderStatus
#function(name: "processPayment-${env}")
#function(name: "createOrder-${env}")
}
The error message being shown is as follows:
n error occurred when pushing the resources to the cloud
🛑 An error occurred during the push operation: /
Schema validation failed.
Unknown argument "keyName" on directive "#hasOne".
GraphQL request:21:31
20 | price: Float
21 | orders: [BookOrder] #hasOne(keyName: "byBook", fields: ["id"])
| ^
22 | }
Unknown argument "sortKeyfields" on directive "#index". Did you mean "sortKeyFields"?
GraphQL request:56:40
55 | id: ID!
56 | user: String! #index(name: "byUser", sortKeyfields: ["user"])
| ^
57 | date: String
Unknown argument "keyName" on directive "#manyToMany".
GraphQL request:59:34
58 | total: Float
59 | books: [BookOrder] #manyToMany(keyName: "byOrder", fields: ["id"])
| ^
60 | }
Unknown argument "fields" on directive "#manyToMany".
GraphQL request:59:54
58 | total: Float
59 | books: [BookOrder] #manyToMany(keyName: "byOrder", fields: ["id"])
| ^
60 | }
Directive "#manyToMany" argument "relationName" of type "String!" is required, but it was not provided.
GraphQL request:59:22
58 | total: Float
59 | books: [BookOrder] #manyToMany(keyName: "byOrder", fields: ["id"])
| ^
60 | }
⚠️ Review the Amplify CLI troubleshooting guide for potential next steps: https://docs.amplify.aws/cli/project/troubleshooting/
How do I resolve this error? Following the newly updated was-amplify docs, it seems right. But it is not working
It seems like your schema is missing a few logic statements, there is no need of putting up #manyTomany statements there. The updated Schema can be done as shown below
type Book
#model(subscriptions: null)
#auth(
rules: [
#allow admins to create, update and delete books
{ allow: groups, groups: ["Admin"] }
# allow all authenticated users to view books
{ allow: private, operations: [read] }
# allow all guest users (not authenticated) to view books
{ allow: public, operations: [read] }
]
)
{
id: ID!
title: String!
description: String
image: String
author: String
featured: Boolean
price: Float
orders: [BookOrder] #hasMany(fields: ["id"])
}
type BookOrder
#model(queries: null, subscriptions: null)
#auth(
rules: [
# allow admins to create bookorders for customers by using customer email in lambda
{ allow: owner, identityClaim: "email", ownerField: "customer" }
{ allow: groups, groups: ["Admin"] }
]
)
{
id: ID!
book_id: ID! #index(name: "byBook", sortKeyFields: ["order_id"])
order_id: ID! #index(name: "byOrder", sortKeyFields: ["book_id"])
book: Book #belongsTo(fields: ["book_id"])
order: Order #belongsTo(fields: ["order_id"])
}
type Order
#model(subscriptions: null)
#auth(
rules: [
# only owner can see his orders
{ allow: owner, identityClaim: "email", ownerField: "customer" }
#allow admins to view orders
{ allow: groups, groups: ["Admin"] }
]
)
{
id: ID!
user: String! #index(name: "byUser")
date: String
total: Float
books: [BookOrder] #hasMany(fields: ["id"])
}
enum OrderStatus {
SUCCESS
FAILED
}
input CartItem {
id: ID!
title: String
image: String
price: Float
amount: Int
}
input ProcessOrderInput {
id: ID!
cart: [CartItem]
total: Float!
token: String!
address: String
}
type Mutation {
processOrder(input: ProcessOrderInput!): OrderStatus
#function(name: "processPayment-${env}")
#function(name: "createOrder-${env}")
}
You should not be facing the issue now.
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!
}
I'm not sure if I'm doing this correctly with the connections in AppSync GraphQL.
This is what my graphql models look like:
type User #model #auth(rules: [{ allow: owner, ownerField: "username" }]) {
id: ID!
username: String!
email: String!
userType: UserType
}
enum UserType {
TEACHER
CREATOR
}
type Teacher #model {
id: ID!
userId: ID
name: String!
activations: [Activation]
#connection(keyName: "activationsByTeacherId", fields: ["id"])
creators: [TeacherCreatorPartnership]
#connection(name: "TeacherCreatorPartnership")
}
type Creator #model {
id: ID!
userId: ID
name: String!
email: String!
username: String
teachers: [TeacherCreatorPartnership] #connection(name: "CreatorTeacherPartnership")
posts: [Post] #connection(name: "CreatorPosts")
activations: [CreatorActivations] #connection(name: "CreatorActivations")
}
type TeacherCreatorPartnership #model(queries: null) {
id: ID!
teacher: Teacher! #connection(name: "TeacherCreatorPartnership")
creator: Creator! #connection(name: "CreatorTeacherPartnership")
}
type CreatorActivations #model(queries: null) {
id: ID!
creator: Creator! #connection(name: "CreatorActivations")
activation: Activation! #connection(name: "ActivationCreators")
}
type Activation
#model
#key(
name: "activationsByTeacherId"
fields: ["teacherId"]
queryField: "activationsByTeacherId"
)
#auth(
rules: [
{ allow: groups, groups: ["Admin"] }
{
allow: owner
ownerField: "teacherId"
operations: [create, update, delete]
}
{ allow: private, operations: [read] }
{ allow: public, operations: [read] }
]
) {
id: ID!
teacherId: ID!
title: String!
teacher: Teacher #connection(fields: ["teacherId"])
creators: [CreatorActivations] #connection(name: "ActivationCreators")
}
The idea is that when user signs in with Amplify, they'll go through an onboarding process and choose whether they're a creator or a teacher.
This works fine, but the problem is if a signed-in user wants to create a new Activation.
I'm not sure if the graphql on the Activation model is set correctly, perhaps the auth key is wrong?
This is how I'm processing create
const createNewActivation = async () => {
if (!title || !content || !location) return;
const newId = uuid();
activation.id = newId;
const user = await Auth.currentAuthenticatedUser();
try {
await API.graphql({
query: createActivation,
variables: {
input: {
...activation,
teacherId: user.attributes.sub,
},
},
authMode: "AMAZON_COGNITO_USER_POOLS",
});
} catch (error) {
console.log("Error: problem creating activation: ", error);
}
};
I've also set up a lambda function so that when user confirms their account from sign up, it will save the user information in DynamoDB with an ID, the username, and email.
Edit: Got it working but...
So, I was able to save the data, but I had to change the schema in my Activation model from:
{
allow: owner
ownerField: "teacherId"
operations: [create, update, delete]
}
to just
{
allow: owner
}
Not sure why I can't set the owner to teacherId? Wouldn't I need this so I can make proper connections to Teacher's model with teachId field?
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.