Sorting AWS AppSync 'GraphQL' connected queries (nesting sorting?) - graphql

I am Using AWS AppSync for my react native application and can't seem to figure out how to get sort inside of a query (nested queries/sorting?). Not sure what the proper terminology would be but here are my graphQL models, each month can contain many monthsPhotos:
type Month
#model
#auth(rules: [{ allow: owner, operations: [read, create, delete, update] }]) {
id: ID!
name: String!
owner: String!
monthsphotos: [MonthPhoto] #hasMany
createdAt: AWSDateTime!
updatedAt: AWSDateTime!
sorttype: String!
#index(
name: "monthsByDateTime"
queryField: "monthsByDateTime"
sortKeyFields: ["createdAt"]
)
}
type MonthPhoto
#model
#auth(rules: [{ allow: owner, operations: [read, create, delete, update] }]) {
id: ID!
month: Month #belongsTo
thumbnail: String
owner: String!
caption: String
location: String
date: String
createdAt: AWSDateTime!
updatedAt: AWSDateTime!
monthMonthsphotosId: ID!
#index(
name: "monthPhotosByDateTime"
queryField: "monthPhotosByDateTime"
sortKeyFields: ["createdAt"]
)
file: S3Object
}
my query for my months looks like this:
export const monthsByDateTime = /* GraphQL */ `
query MonthsByDateTime(
$sorttype: String!
$createdAt: ModelStringKeyConditionInput
$sortDirection: ModelSortDirection
$filter: ModelMonthFilterInput
$limit: Int
$nextToken: String
) {
monthsByDateTime(
sorttype: $sorttype
createdAt: $createdAt
sortDirection: $sortDirection
filter: $filter
limit: $limit
nextToken: $nextToken
) {
items {
id
name
monthsphotos {
items {
file {
bucket
region
key
}
createdAt
caption
date
location
}
}
}
}
}
`;
This lets me sort my months data by the date and time is was created. Ultimately I want a query that sorts all the months, and also sorts all the monthsPhotos within those months in 1 query. How would I go about doing this? Below is another query I made to sort monthsPhotos alone, I have not figured out how to connect these two into one:
export const monthPhotosByDateTime = /* GraphQL */ `
query MonthPhotosByDateTime(
$monthMonthsphotosId: ID!
$createdAt: ModelStringKeyConditionInput
$sortDirection: ModelSortDirection
$filter: ModelMonthPhotoFilterInput
$limit: Int
$nextToken: String
) {
monthPhotosByDateTime(
monthMonthsphotosId: $monthMonthsphotosId
createdAt: $createdAt
sortDirection: $sortDirection
filter: $filter
limit: $limit
nextToken: $nextToken
) {
items {
id
file {
bucket
region
key
}
caption
location
date
createdAt
monthMonthsphotosId
}
nextToken
}
}
`;

Related

Can you apply sorting to a lists of models inside another model?

Using AWS Amplify, can we apply sorting to the messages in the Conversation model?
When fetching the conversation, it would be nice that the messages come sorted based on the generated createdAt date.
Currently these are the models used.
type Conversation #model {
id: ID!
messages: [Message!]! #hasMany
...
}
type Message #model {
id: ID!
authorId: String!
content: String!
conversation: Conversation #belongsTo
}
Ideally want to place sorting on the hasMany directive, but this is not possible.
type Conversation #model {
id: ID!
messages: [Message!]! #hasMany(sortKeys:['createdAt'])
...
}
Created a secondary index on the Message model with a sort field on createdAt.
type Message #model {
id: ID!
authorId: String! #index(name: "byAuthorId", queryField: "getMessagesByAuthorId", sortKeyFields: [ "createdAt" ])
content: String!
conversation: Conversation #belongsTo
}
Amplify created a new query to fetch the messages and apply sorting. Following example uses react-query to fetch the messages from an authorId with sorting.
export function useMessagesPerAuthorId({
id,
filter,
enabled = true,
}: {
id: string | undefined;
filter: any;
enabled?: boolean;
}) {
return useQuery(
['conversations', 'messages', id, filter],
() => fetchMessagesByAuthorId({ id: id!, filter }),
{ enabled: enabled && !!id }
);
}
async function fetchMessagesByAuthorId({ id, filter }: { id: string; filter: any }) {
const query: any = await API.graphql({
query: getMessagesByAuthorId,
variables: { authorId: id, sortDirection: 'DESC', filter },
});
const data: Message[] = query.data?.getMessagesByAuthorId.items;
return data;
}
Now we can call that hook in our view component and pass the filters.
const { isLoading, data: messages = [] } = useMessagesPerAuthorId({
id: profile?.id,
filter: {
and: [{ conversationMessagesId: { eq: conversationId } }, { deleted: { eq: false } }],
},
enabled: !!profile?.id,
});

Not getting count according to filter in GraphQL amplify queries

Getting Scanned count but not count of data according to filter
count: null
items: [{id: "bcd75096-7fd9-4e9d-8675-6877f0609ac2", name: "dxfrdhjkhklklkl", description: "dgdxrfg",…},…]
0: {id: "bcd75096-7fd9-4e9d-8675-6877f0609ac2", name: "dxfrdhjkhklklkl", description: "dgdxrfg",…}
1: {id: "52f6ff60-fc07-4631-a1fb-b039f376ff21", name: "ghnfgyhj", description: "gyhkjmuhjolk",…}
2: {id: "f73dfb37-2778-4b87-88c7-e6f9f5b5c931", name: "drftgserty", description: "trse54rte54ty",…}
3: {id: "6df9f5c2-ec06-4e70-b5e2-133cb0d8e958", name: "tygujghukuh", description: "tuyjyuikuolnh",…}
4: {id: "9360a766-ac89-420c-881b-2b3089bcca7f", name: "kl;", description: "vcbghnjmk,l", is_active: true,…}
5: {id: "c0dcbaff-37d4-4e4c-9375-584ff7110d77", name: "dfhgbdcb", description: "dfxvcx", is_active: true,…},...
scannedCount: 100
I have followed these tutorials to get count HOW TO COUNT THE NUMBER OF RESULTS WITH AWS AMPLIFY DYNAMODB AND GRAPHQL
Filter
var body = {
filter: {
is_active: {
eq: true
}
}
}
Query to get list of todos
export const listTodos = /* GraphQL */ `
query ListTodos(
$filter: ModelTodoFilterInput
$limit: Int
$nextToken: String
) {
listTodos(filter: $filter, limit: $limit, nextToken: $nextToken) {
count
items {
id
name
description
is_active
createdAt
updatedAt
}
scannedCount
}
}
`;
GraphQl shema
type Todo #model {
id: ID!
name: String!
description: String!
is_active: Boolean
}
type ModelTodoConnection {
items: [Todo]
scannedCount: Int
count: Int
total: Int
}
And IF I set limit to 5 and it will send back scannedCount 5 if when I have total data in database around 110. I want to count data where is_active: { eq: true }
Check out the package I wrote to solve this issue: https://github.com/multimeric/AmplifyCountDirective.
After following the installation instructions, to solve your issue I would change the schema to this:
type Todo #model #count {
id: ID!
name: String!
description: String!
is_active: Boolean
}
Then you can query the count using a GraphQL query such as:
{
countTodo(filter: {
is_active: {
eq: true
}
})
}

Prisma graphql computed fields on relations

I have the following datamodel:
type Tvshow {
id: ID! #unique
title: String!
pricing: [Pricing]
startDate: DateTime!
endDate: DateTime!
subscribers: [Tvshowsubscription!]
.....
}
type FavoriteTvshow {
id: ID! #unique
tvshow: Tvshow!
user: User!
}
type User {
id: ID! #unique
name: String
email: String! #unique
password: String
googleID: String #unique
resetToken: String
resetTokenExpiry: String
permissions: [Permission]
address: Address
phone: String
favorites: [FavoriteTvshow!]
tvshowSubscriptions: [Tvshowsubscription!]
}
I have my custom Tvshow resolver using addFragmentToInfo:
resolver-queries.js
const Query = {
...
favoriteTvshows: forwardTo('db'),
tvshow: (parent, args, ctx, info) => {
const fragment = `fragment EnsureComputedFields on Tvshow { pricing { minQuantity maxQuantity unitPrice} subscribers { id }}`
return ctx.db.query.tvshow({}, addFragmentToInfo(info, fragment))
},
....
};
tvshow-resolver.js
const Tvshow = {
countSubscribers: (parent) => {
return parent.subscribers.length;
},
}
This is an example, I have more computed fields for Tvshow
I can query Tvshows with countSubscribers, It works fine doing something like this:
query SINGLE_TVSHOW_QUERY($id: ID!) {
tvshow(where: { id: $id }) {
id
title
pricing {
minQuantity
maxQuantity
unitPrice
}
startDate
endDate
countSubscribers
}
}
But what I want to do is to get all the favorite Tvshows from an user returning the countSubscribers, a query for that could be something like this:
query FAVORITES_FROM_USER($userId: ID!) {
favoriteTvshows(where: { user: {id: $userId} }) {
tvshow {
id
title
startDate
endDate
countSubscribers
}
}
}
The problem is that when I query this, in the tvshow-resolver.js I mentioned before, the parent doesn’t have any subscribers object
The error was very silly but I will post it anyway. I needed subscribers in the query
query FAVORITES_FROM_USER($userId: ID!) {
favoriteTvshows(where: { user: {id: $userId} }) {
tvshow {
id
title
startDate
endDate
subscribers { <---
id
quantity
}
countSubscribers
}
}
}
That way the parent in tvshow-resolver.js will have subscribers object

graphql trouble accessing items in object

I am still trying to learn graphql and I am having trouble accessing items that are within an object in the database. In my client side code the data for id and createdAt shows up just fine it is just when I add the object that I get the error:
Expected Iterable, but did not find one for field Users.profile
I am not sure what my code is missing:
resolver:
Query: {
getUser(root, args, { userId }) {
const {id } = args;
const user = User.findOne({
id
});
return user;
}
},
schema
const User = `
type User{
id: String!
createdAt: Date
profile: [Profile]
}
type Profile {
name: String!
email: String!
}
extend type Query {
getUser(
id: String!
): User
}
How I am calling it in my client code:
const getUser = gql`
query getUser($id: String!) {
getUser(id: $id) {
id
createdAt
profile {
name
email
}
}
}
`;
This is how it looks in the MongoDB database:
user{
_id: "22222"
createdAt: 11/22/2018
profile:{
name: "Chris"
email: "chris#emample.com"
}
} `
In case it helps someone in future I had to set my objects to JSON to get it to work.
const User = `
type User{
id: String!
createdAt: Date
profile: JSON
}
extend type Query {
getUser(
id: String!
): User
}

Query.products is defined in resolvers but not in schema

Hi I defined rootQuery in Customer schema and then in Product schema I extended query. I wrote resolvers for product schema but then I got following error: Error: Query.products defined in resolvers, but not in schema.
When I move product queries to customer query definition it works.
I dont understand why I'm getting this error. Do I need implement some rootQuery and insert it into typeDefs array and then extend queries in Customer and Product ?
Customer schema
import CustomerPhoto from "./customerPhoto";
const Customer = `
type Customer {
customerID: ID!
firstname: String
lastname: String
phone: String
email: String
CustomerPhoto: CustomerPhoto
}
input CustomerInput {
firstname: String!
lastname: String!
phone: String!
email: String!
}
type Query {
customers(cursor: Int!):[Customer]
customer(id: Int!): Customer
}
type Mutation {
createCustomer(photo: String!, input: CustomerInput): Customer
updateCustomer(customerID: ID!, photo: String, input: CustomerInput): Customer
deleteCustomer(customerID: ID!): Customer
}
`;
export default [Customer, CustomerPhoto];
Product Schema
import ProductPhoto from "./productPhoto";
const Product = `
type Product {
productID: ID!
name: String!
description: String!
pricewithoutdph: Float!
pricewithdph: Float!
barcode: Int!
ProductPhoto: ProductPhoto
}
extend type Query {
products: [Product]
product(productID: ID!): Product
}
`;
export default [Product, ProductPhoto]
Here Im importing both schemas. Is there something missing ?
const schema = makeExecutableSchema({
typeDefs: [...Customer,...Product],
resolvers: merge(CustomerResolvers, ProductResolvers),
logger: {
log: e => {
console.log("schemaError", e);
}
},
resolverValidationOptions: {
requireResolversForNonScalar: true
}
});
Product Resolvers
const ProductResolvers = {
Query: {
products: (_, { cursor }) => {
return models.Product.findAndCountAll({
include: {
model: models.ProductPhoto,
attributes: ["productPhotoID", "photo"],
required: true
},
offset: cursor,
limit: 10,
attributes: ["productID", "name", "description", "pricewithoutdph", "pricewithdph", "barcode"]
}).then(response => {
return response.rows;
});
}
};
export default ProductResolvers;
Customer Resolvers
const CustomerResolvers = {
Query: {
customers: (_, {cursor}) => {
return models.Customer.findAndCountAll({
include: {
model: models.CustomerPhoto,
attributes: ["customerPhotoID", "photo"],
required: true
},
offset: cursor,
limit: 10,
attributes: ["customerID", "firstname", "lastname", "phone", "email"]
}).then(response => {
return response.rows;
});
}
......
}
};

Resources