AWS FlutterAmplify using DataStore

335 views Asked by At

How can we get the User Conversations with a query. Ideal would be to do a query to the user table and get all the user conversations loaded. example:

final user = await Amplify.DataStore.query(User.classType, where: User.ID.eq(id))

user.conversations to have the list of conversations loadd.

If that can not be done, next would be to get all the conversations that have a specific User. example not working:

await Amplify.DataStore.query(UserConversation.classType
          where: UserConversation.USER.eq(user.id)
         )

type Message @model @auth(rules: [{allow: public}]) {
  id: ID!
  ConversationId: Conversation @connection
  UserId: User @connection
  body: String
  createdDate: AWSDateTime!
}

type Conversation @model @auth(rules: [{allow: public}]) {
  id: ID!
  date: AWSDateTime
  readBy: [ReadBy] @connection(keyName: "byConversation", fields: ["id"])
  users: [UserConversation] @connection(keyName: "byConversation", fields: ["id"])
  name: String
  image: String
}

type ReadBy @model @auth(rules: [{allow: public}]) @key(name: "byConversation", fields: ["conversationID"]) {
  id: ID!
  date: AWSDateTime
  RedByUsers: User @connection
  conversationID: ID
}

type User @model @auth(rules: [{allow: public}]) {
  id: ID!
  firstName: String
  lastName: String
  userImg: String
  createdDate: AWSDateTime
  updatedDate: AWSDateTime
  email: AWSEmail
  conversations: [UserConversation] @connection(keyName: "byUser", fields: ["id"])
}

type UserConversation @model(queries: null) @key(name: "byUser", fields: ["userID", "conversationID"]) @key(name: "byConversation", fields: ["conversationID", "userID"]) @auth(rules: [{allow: public}, {allow: public}]) {
  id: ID!
  userID: ID!
  conversationID: ID!
  user: User! @connection(fields: ["userID"])
  conversation: Conversation! @connection(fields: ["conversationID"])
}
1

There are 1 answers

1
NCoop On BEST ANSWER

I was able to get the second version by doing the following:

await Amplify.DataStore.query(UserConversation.classType
      where: User.ID.eq(user.id)
     );

The above will perform a selection of all user conversations that have the user id equal to whatever the id of the user variable is. It was a bit confusing at first as to why you need to pass the User.ID for the query, but from what I understand it is due to how the SQL query gets created by AWS DataStore, it is doing a join behind the scenes and therefore will use the column of the second table (in this case the User table) to perform the join. I wish I could point to some documentation on this, but I couldn't find any. I kinda just got lucky trying a bunch of stuff and noticing in the error message how the SQL query is generated.