I'm using Kotlin and AWS Amplify to make a simple mobile app. I'll begin by showing what I have setup. My schema.graphql:
type OfferGQL #model {
id: ID!
name: String!
description: String!
address: String!
price: Float!
}
My AWS plugins are setup like this:
Amplify.addPlugin(AWSCognitoAuthPlugin())
Amplify.addPlugin(AWSS3StoragePlugin())
Amplify.addPlugin(AWSDataStorePlugin())
Amplify.configure(applicationContext)
This is how I try to save my data to the DataStore:
// Create a new offer object
val newOffer = OfferGQL.builder()
.name(textFieldOfferName.text.toString())
.description(textFieldOfferDescription.text.toString())
.address(textFieldOfferAddress.text.toString())
.price(textFieldOfferPrice.text.toString().toFloat())
.build()
// Put it in the DataStore
Amplify.DataStore.save(newOffer,
{result ->
runOnUiThread{Toast.makeText(this,"Offer added successfully", Toast.LENGTH_LONG).show()}
},
{error ->
println(error.message)
println(error.localizedMessage)
println(error.cause)
println(error.recoverySuggestion)
})
The problem is that when I invoke Amplify.DataStore.save() the entire app freezes. I followed the documentation to configure everything so I don't really now why this is happening.
After a full reinstall of the app on my phone the function finally works.
Related
I'm fairly new to Amplify. I ran the amplify commands to create the src/models/index.d.ts and the generated API file, src/app/API.ts files. Each of these have the same types generated except that embedded collections generated via #belogsTo and #hasMany is not on the type in API.ts but IS on index.d.ts. When I try running the code I have a JSON object that I've cast to the model in src/app/API.ts. Like I say, there is an embedded collection that does NOT show up on the API file. Here is what I have for the schema file schema.graphql.
EDIT: It appears there are multiple ways to do the same thing, such as getting, updating, and deleting data. I think that using API.ts is the latests way to do it? I'm just totally confused by all of this.
type Blog #model {
id: ID! #primaryKey
name: String!
posts: [Post] #hasMany
}
type Post #model {
id: ID! #primaryKey
title: String!
blog: Blog #belongsTo
comments: [Comment] #hasMany
}
type Comment #model {
id: ID! #primaryKey
post: Post #belongsTo
content: String!
}
The API model that was generated does not have comments on type Post. Here is the generated code in the API file:
export type CreatePostInput = {
id?: string | null;
title: string;
blogPostsId?: string | null;
};
That is the type that is passed into CreatePostInput. When I try to specify the json:
const json = {
blogPostsId: 'Some Random UUID String',
title: 'MyPost',
} as Post;
I cannot add a comments array to this json because CreatePostInput and Post models does not contain comments that I specified on the schema.graphql.
My question is, first, what definition of Blog should I be using, the one in the index.t.ds file or the definition in the API file? If the answer is the one in index.d.ts, how to do go about creating one because the CreateBlogInput is the type that CreatePost in API.ts file.
I've tried different things that I've found on the interwebs from AWS blogs to Medium posts.
I am having trouble with
"message": "Not Authorized to access createMerchant on type Merchant"
I'm executing this on the AWS AppSync Request tab.
I'm able to list (this one too), create other types but just not this one.
input CreateMerchantInput {
id: ID
pass: AWSURL
validated: Boolean!
_version: Int
}
type MerchantType #aws_iam
#aws_cognito_user_pools {
id: ID!
role: String!
merchantSpotMerchantTypes(
filter: ModelMerchantSpotMerchantTypeFilterInput,
sortDirection: ModelSortDirection,
limit: Int,
nextToken: String
): ModelMerchantSpotMerchantTypeConnection
createdAt: AWSDateTime!
updatedAt: AWSDateTime!
_version: Int!
_deleted: Boolean
_lastChangedAt: AWSTimestamp!
}
Not sure how to fix this. Rights seem ok to me and I don't know where to look else.
The solution might depend on how you're authenticating the call - are you using Cognito? IAM?
"Rights seem ok" ... well, they might seem ok to you but still not be correct :) If it's IAM then you should probably post your policy.
But you don't seem to have any explicit #auth directives, so -- in the absence of other info -- I'm going to guess that you're perhaps using Cognito and that you might have some custom VTL resolvers in your amplify project that are affecting createMerchant (perhaps accidentally). But it is hard to say for certain without more detail on your project.
I'm playing with the AWS Amplify GraphQL console and I've noticed that updating a boolean field is not working and I'm not sure exactly why. This is also not working from my React Native app. Basically, what I'm trying to do, is at onPress, change the isOnline to true or false (see full code below):
isOnline: !car.isOnline
schema.graphql
type Car #model
#key(name: "byUser", fields: ["userId"])
{
id: ID!
type: String!
latitude: Float
longitude: Float
heading: Float
plate: String
isOnline: Boolean
isActive: Boolean
orders: [Order] #connection(keyName: "byCar", fields: ["id"])
userId: ID!
user: User #connection(fields: ["userId"])
}
mutations.js
export const updateCar = /* GraphQL */ `
mutation UpdateCar(
$input: UpdateCarInput!
$condition: ModelCarConditionInput
) {
updateCar(input: $input, condition: $condition) {
id
type
latitude
longitude
heading
plate
isOnline
isActive
userId
_version
_deleted
_lastChangedAt
createdAt
updatedAt
}
}
`;
index.js
try {
const userData = await Auth.currentAuthenticatedUser();
const input = {
id: userData.attributes.sub,
isOnline: !car.isOnline,
}
const updatedCarData = await API.graphql(
graphqlOperation(
updateCar, {
input
})
)
console.log("Updated car: ", updatedCarData.data.updateCar)
setCar(updatedCarData.data.updateCar);
} catch (e) {
console.error(e);
}
From the app, every time I get the isOnline field set to true, even if I tried setting it to false instead of !car.isOnline.
I also tried creating a new field called isActive which was null initially, I created a mutation on AWS AppSync GraphQL console and was able to set it to false, but then, when trying to set it to true, updating is not working, it's always returning false.
As a note, updating the other fields, for example String fields, is working.
Can you please guide me into this issue?
I was able to solve this issue by:
Running the below command:
amplify update api
Select GraphQL, then Disable Conflict Detection
Last, but not least, run:
amplify push
I haven't found any explanation for this on the Amplify Docs, but if you're running into this issue, make sure to follow the above steps.
shown below is the graphql Schema.
#auth(rules: [{ allow: owner,operations: [create, delete ] ,ownerField: "user"}])
{
id: ID!
videoKey: String!
videoThumbnailKey :String!
videoTitle:String!
videoDescription:String!
channelName:String!
videoLikes: Int
videoDislikes: Int
comments: [Comment] #connection(keyName: "byVideo", fields: ["id"])
user: String
}
type Comment #model
#auth(rules: [{ allow: owner,operations: [create,delete] ,ownerField: "user"}])
#key(name: "byVideo", fields: ["videoID", "comment"]) {
id: ID!
videoID: ID!
comment: String!
video: Video #connection(fields: ["videoID"])
user: String
}
type LikedVideos #model
{
id:ID!
video:[Video]#connection
}
this is the query for listing videos
and these are the results
this is the query for getting a video
and these are the results
all of these works fine, but when I try to delete it I get error.
this is the mutation query
and this is the error response i got
Seems like you have not added sort key in dynamo db table and the other items have the same primary key as of first item. I faced similar issue and worked after adding sort key.
This seems to be another bug in AWS Amplify or local DynamoDB.
I am using the same schema - when I add even just a space to schema.grapql, first delete operation works. The delete operations executed after are not working.
Also, it seems like something is throttling query response (I am using amplify mock command):
E.g. I have 7 items in the database and when I am trying to list all of them, I got responses with 1, 2, or even zero items, multiple times - when I would expect, that they will be loaded in 1 request, at the same time.
I am using AWS Amplify
"aws-amplify": "^3.1.1",
"aws-amplify-react-native": "^4.2.5",
Even if you modify schema.graphql, it's still unreliable.
I am using AWS Amplify to configure Appsync in my project. In my schema.graphql, I have the following types:
type Post #model {
id: ID!
tweet: Tweet
}
type Tweet {
id: ID
text: String!
}
Tweet is a nested object under Post, it is intentionally not a #model.
When I upload to AWS via the cli (amplify push), it removes the Tweet's id field from TweetInput on the generated schema. This is the generated schema from the AWS console:
input CreatePostInput {
id: ID
tweet: TweetInput
}
type Tweet {
id: ID
text: String!
}
input TweetInput {
text: String!
}
I have searched the Appsync documentation, but I cannot find anywhere that says I can't use an id field on an object type.
Is there any way around this? I'd like to avoid renaming the field if I can.
Turns out that this is a bug in the CLI https://github.com/aws-amplify/amplify-cli/issues/1984
Hopefully it gets resolved soon.