Reputation: 604
I have an iOS app where users can login and message one another using the backend AWS Amplify. My API is configured using GraphQL and currently looks like this.
type User @model {
id: ID!
userSub: String!
fullName: String!
}
type ChatMessage @model {
id: ID!
senderUserSub: String
recieverUserSub: String
messageText: String
messageImageFilename: String
dateSent: String!
}
I am new to GraphQL and its Schema Definition Language. The schema above works however inside the dynamodb table there is no structure to it, I am trying to create an efficient way of structuring data for user messaging. The "One to many relationship" is schema example that can be found inside of the Amplify CLI when configuring an API. I try to copy its example base my current one off of.
Default one to many relationship schema
type Blog @model {
id: ID!
name: String!
posts: [Post] @connection(keyName: "byBlog", fields: ["id"])
}
type Post @model @key(name: "byBlog", fields: ["blogID"]) {
id: ID!
title: String!
blogID: ID!
blog: Blog @connection(fields: ["blogID"])
comments: [Comment] @connection(keyName: "byPost", fields: ["id"])
}
type Comment @model @key(name: "byPost", fields: ["postID", "content"]) {
id: ID!
postID: ID!
post: Post @connection(fields: ["postID"])
content: String!
}
I try to copy its example like this.
Updated schema
type User @model {
id: ID!
userSub: String!
fullName: String!
messages: [ChatMessage] @connection(keyName: "byUser", fields: ["id"])
}
type ChatMessage @model @key(name: "byUser", fields: ["messageID"]){
id: ID!
messageID: ID!
senderUserSub: String
recieverUserSub: String
messageText: String
messageImageFilename: String
dateSent: String!
user: User @connection(fields: ["messageID"])
}
I was wondering does this updated schema above even look appropriate? If possible can anyone give me pointers as to how to make one correctly for messaging? I am not experienced when it comes to GraphQL SDL.
Upvotes: 2
Views: 5457
Reputation: 1061
You don't need to use the @key attribute for this kind of connection. You can give the @connection a name so that amplify understands which connection you are referring to like this:
@connection(name: "nameOfYourConnection")
The name must be provided on the connection attribute on both types.
type User @model {
id: ID!
userSub: String
fullName: String
chatMessages: [ChatMessage] @connection(name: "UserChatMessageConnection") #new
}
type ChatMessage @model {
id: ID!
senderUserSub: String
recieverUserSub: String
messageText: String
messageImageFilename: String
dateSent: String!
user: User @connection(name: "UserChatMessageConnection") #new
}
After you have run amplify push you will se in the generated mutations, that when you are creating a ChatMessage object you should give it a value named chatMessagesUserId
. This is the reference (the id on the user type) to which user created the ChatMessage.
Upvotes: 5