I am using react-apollo on meteor with mysql and sequelize, I am still a beginner in JS. Lets assume I have the following resolver function on my apollo-server:
You should think more about the design and what each of those queries should do. Those queries should not mutate the database or the global state.
The best thing you can do is to simply define a new type that includes total
and filtered
, like what you did as NumberOfPosts
in your first try, and also the list of posts.
So, your schema would be like:
type Post {
id: Int
date: Float
text: String
}
type PostList {
total: Int
filtered: Int
posts: [Post]
}
type Query {
posts(
id: Ind,
offset: Int,
limit: Int,
filter: String): PostList
}
schema {
query: Query
}
And you resolve posts
like:
posts(_, args) {
return Post.findAndCountAll({ where: args }).then(result => {
return {
total: 1000,
filtered: result.count,
posts: result.rows
}
})
}
Notice how I just put 1000 for the total number. You can not get the total number of rows with findAndCountAll
. If you that, need you can run two different queries in parallel and use Promise.all to wait for them to be resolved.
posts(_, args) {
return Promise.all([
Post.count(),
Post.findAndCountAll({ where: args })
]).then(data => {
return {
total: data[0],
filtered: data[1].count,
posts: data[1].rows
}
})
}
The above code also could benefit from ES6's destructuring:
posts(_, args) {
return Promise.all([
Post.count(),
Post.findAndCountAll({ where: args })
]).then(([totalCount, filteredData]) => {
return {
total: totalCount,
filtered: filteredData.count,
posts: filteredData.rows
}
})
}
Now you can run:
query {
posts(filter:"example") {
total
filtered
posts {
id
date
text
}
}
}
and get:
{
"data": {
"posts": {
"total": 1000,
"filtered": 21,
"posts": [
{
"id": 4,
"date": 5105626122,
"text": "jzybiwutudi"
},
...
]
}
}
}