Search code examples
amazon-web-servicesgraphqlnext.jsaws-amplifyaws-amplify-cli

AWS Amplify GraphQL fetch data using multiple input parameters


I'm working on Next.js and I have this setup:

const data = await API.graphql({
  query: projectByUserIdandProjectId,
  variables: {
    userId: props.userId,
    projectId: project.id,
  },
});

Then I have this schema:

type Project
  @model
  @key(
    name: "byUserId"
    fields: ["userId"]
    queryField: "projectByUserIdandProjectId"
  )
  id: ID!
  userId: ID!
  projectId: ID!
}

I tried adding projectId into fields: fields: ["userId", "projectId"] but when I was looking at amplify's queries console, it doesn't give me an option to add the projectId.

I wanted to be able to get 1 data from the record when both userId and projectId matches.


Solution

  • Why adding projectId again in the Project model when you can use id?

    I don't know about your use case, but you can use filter.

    type Project
      @model
      @key(
        name: "byUserId"
        fields: ["userId"]
        queryField: "projectByUserId"
      )
      id: ID!
      userId: ID!
      projectId: ID!
    }
    
    import { API, graphqlOperation } from "aws-amplify";
    
    --- 
    
    await API.graphql(
      graphqlOperation(projectByUserId, {
        userId: props.userId,
        filter: { projectId: { eq: props.projectId } }
      })
    );