Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unable to create mutation if @connection is present #483

Closed
mreaybeaton opened this issue May 23, 2020 · 5 comments
Closed

Unable to create mutation if @connection is present #483

mreaybeaton opened this issue May 23, 2020 · 5 comments
Assignees
Labels
api Issues related to the API category bug Something isn't working pending-community-response Issue is pending response from the issue requestor

Comments

@mreaybeaton
Copy link

State your question

I have a graphql setup which has users and posts. If there is no connection between them, I can create a post, however as soon as I create the connection, I get the following error:

Successfully retrieved user: User(id: "a79cf3ce-70f8-4f4b-ac91-7454251486ec", fullName: "Michael Reay-Beaton", emailAddress: nil, bio: nil, profileImageUrl: nil, isFollowing: nil, following: nil, followers: nil, isEditable: nil, posts: nil, createdTimestamp: 1590189074, updatedTimestamp: nil)
Failed to create post: GraphQLResponseError<Post>: GraphQL service returned a successful response containing errors: [Amplify.GraphQLError(message: "Validation error of type FieldUndefined: Field \'postUserId\' in type \'Post\' is undefined @ \'createPost/postUserId\'", locations: Optional([Amplify.GraphQLError.Location(line: 8, column: 5)]), path: nil, extensions: nil)]
Recovery suggestion: The list of `GraphQLError` contains service-specific messages
GraphQLResponseError<Post>: GraphQL service returned a successful response containing errors: [Amplify.GraphQLError(message: "Validation error of type FieldUndefined: Field \'postUserId\' in type \'Post\' is undefined @ \'createPost/postUserId\'", locations: Optional([Amplify.GraphQLError.Location(line: 8, column: 5)]), path: nil, extensions: nil)]
Recovery suggestion: The list of `GraphQLError` contains service-specific messages

Which AWS Services are you utilizing?
Amplify graphql
Provide code snippets (if applicable)

 func createPost(postText: String, imageName: String, user: User, timeStamp: Int) -> PromiseKit.Promise<Void> {
        let post = Post(text: postText, imageName: imageName, user: user, createdTimestamp: timeStamp)
        return Promise { seal in
            _ = Amplify.API.mutate(of: post, type: .create) { event in
                switch event {
                case .completed(let result):
                    switch result {
                    case .success(let post):
                        print("Api mutate successful, created post: \(post)")
                        seal.fulfill(())
                    case .failure(let error):
                        print("Failed to create post: \(error)")
                        seal.reject(error)
                    }
                case .failed(let error):
                    print("Failed with error \(error)")
                default:
                    print("Unexpected event")
                }
            }
        }
    }

model

type User @model {
  id: ID!
  fullName: String!
  emailAddress: String
  bio: String
  profileImageUrl: String
  isFollowing: Boolean
  following: [UserFollowing] @connection (name: "following")
  followers: [UserFollowers] @connection (name: "followers")
  isEditable: Boolean
  posts: [Post] @connection(name: "posts")
  createdTimestamp: Int!
  updatedTimestamp: Int
}

type UserFollowing @model {
  id: ID! 
  user: User @connection(name: "following")
  followingUser: User @connection
}

type UserFollowers @model {
  id: ID!
  user: User @connection(name: "followers")
  followersUser: User @connection
}

type Post @model {
  id: ID!
  text: String
  imageName: String
  user: User @connection(name: "posts")
  createdTimestamp: Int!
  updatedTimestamp: Int
}

If I remove the posts connection, I can create Posts.

Please note that I am using Amplify plugins, not the SDK.

Any help is appreciated. All versions of tools are up to date.

@wooj2 wooj2 transferred this issue from aws-amplify/aws-sdk-ios May 25, 2020
@wooj2 wooj2 added pending-community-response Issue is pending response from the issue requestor api Issues related to the API category labels May 25, 2020
@lawmicha lawmicha self-assigned this May 29, 2020
@lawmicha
Copy link
Contributor

lawmicha commented Jun 2, 2020

Hi @mickeysox, thanks for reporting this issue. I was able to reproduce this and it appears that when creating a Post, the selection set that is generated is missing the User fields, instead it populating another field called postUserId that is causing the service to return that GraphQL error.

I fixed this in #509 if you like, feel free to use this branch. I have also tried your schema and was able to create a post with the following code.

Podfile, using local pods on the fix-optional-associations branch

$LOCAL_REPO = '~/aws-amplify/master/amplify-ios'

pod 'Amplify', :path => $LOCAL_REPO
pod 'AmplifyPlugins', :path => $LOCAL_REPO
pod 'AWSPluginsCore', :path => $LOCAL_REPO
pod 'AmplifyPlugins/AWSAPIPlugin', :path => $LOCAL_REPO

ContentView.swift

import SwiftUI
import Amplify
import AmplifyPlugins
struct ContentView: View {
    func create() {
        let user = User(fullName: "fullname", createdTimestamp: 1)
        createPost(postText: "postText", imageName: "imageName", user: user, timeStamp: 1)
    }
    func createPost(postText: String, imageName: String, user: User, timeStamp: Int) {
        let post = Post(text: postText, imageName: imageName, user: user, createdTimestamp: timeStamp)

        _ = Amplify.API.mutate(request: .create(post)) { event in
            switch event {
            case .success(let result):
                switch result {
                case .success(let post):
                    print("Api mutate successful, created post: \(post)")
                case .failure(let error):
                    print("Failed to create post: \(error)")
                }
            case .failure(let error):
                print("Failed with error \(error)")
            }
        }

    }
    var body: some View {
        ZStack {
            VStack {
                Button(action: {
                    self.create()
                }, label: {
                    Text("Create")
                })
            }
        }

    }
}

@lawmicha lawmicha added the bug Something isn't working label Jun 2, 2020
@mreaybeaton
Copy link
Author

mreaybeaton commented Jun 2, 2020

Hi @lawmicha

Thank you so much for fixing this. Could you tell me how I could use the fixed branch? i.e. update my pods or?

I have a separate but potentially related issue regarding DataStore. I have put a message out in discord https://discord.com/channels/705853757799399426/707328996995760179/717494199875797092 if you have a minute would you mind checking?

In summary, when I use self.users?.posts?.count the output fails (I have tested and the data exists online 1:m posts

Here is the output:

no such column: root.postUserIdId in "select "root"."id" as "id", "root"."createdTimestamp" as "createdTimestamp", "root"."imageUrl" as "imageUrl", "root"."text" as "text", "root"."updatedTimestamp" as "updatedTimestamp", "root"."userId" as "userId" from Post as root where 1 = 1 and "root"."postUserIdId" = ?" Fatal error: The operation couldn’t be completed. (SQLite.Result error 0.): file /Users/development/Documents/Development/AWS/FullStackSocial/Pods/Amplify/Amplify/Categories/DataStore/Model/Collection/List+LazyLoad.swift, line 96 2020-06-02 22:47:50.150875+0100 FullStackSocial[45576:1966345] Fatal error: The operation couldn’t be completed. (SQLite.Result error 0.): file /Users/development/Documents/Development/AWS/FullStackSocial/Pods/Amplify/Amplify/Categories/DataStore/Model/Collection/List+LazyLoad.swift, line 96

Model (note that I added userId and no connection to Post):

`type User @model {
id: ID!
fullName: String!
emailAddress: String
bio: String
profileImageUrl: String
isFollowing: Boolean
following: [UserFollowing] @connection (keyName: "following", fields: ["id"])
followers: [UserFollowers] @connection (keyName: "followers", fields: ["id"])
isEditable: Boolean
posts: [Post] @connection(keyName: "posts", fields: ["id"])
createdTimestamp: Int!
updatedTimestamp: Int
}

type UserFollowing @model @key(name: "following", fields:["userId"]) {
id: ID!
userId: ID!
}

type UserFollowers @model @key(name: "followers", fields:["userId"]) {
id: ID!
userId: ID!
}

type Post @model @key(name: "posts", fields:["userId", "createdTimestamp"], queryField: "postsByCreatedtimestamp" ) {
id: ID!
userId: ID!
text: String
imageUrl: String
createdTimestamp: Int!
updatedTimestamp: Int
}`

@lawmicha
Copy link
Contributor

lawmicha commented Jun 2, 2020

Hi @mickeysox
if you would like to try out the changes, you'll need to get a local clone of the repository on your machine

git clone https://github.com/aws-amplify/amplify-ios.git
cd amplify-ios
git checkout -b fix-optional-associations origin/fix-optional-associations
pwd

pwd will print out the full path with the current directory. this can be used in the Podfile to install pods directly from your local repo, by using

# variable pointing to your directory
$LOCAL_REPO = '~/aws-amplify/master/amplify-ios'

# install the pods from the local repo
pod 'Amplify', :path => $LOCAL_REPO
pod 'AmplifyPlugins', :path => $LOCAL_REPO
pod 'AWSPluginsCore', :path => $LOCAL_REPO
pod 'AmplifyPlugins/AWSAPIPlugin', :path => $LOCAL_REPO

I usually just remove Podfile.lock and Pods directory, before pod install to make sure it's doing a fresh install.

If you need to go back to the released version, remove the :path => $LOCAL_REPO and install from cocoapods

@lawmicha
Copy link
Contributor

lawmicha commented Jun 2, 2020

For the DataStore issue, i have created a new issue for us to take a look at over here #510

@lawmicha
Copy link
Contributor

lawmicha commented Jun 9, 2020

the change related to associations #509 has been released in 1.0.1

@lawmicha lawmicha closed this as completed Jun 9, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
api Issues related to the API category bug Something isn't working pending-community-response Issue is pending response from the issue requestor
Projects
None yet
Development

No branches or pull requests

3 participants