Fran Dios
02/22/2019, 7:10 AMusers { id posts { id } }
and then counting user.posts.length
in the frontend would work, but we cannot sort users by post amount from DB if we have pagination, right?
I think requesting users { id postsConnections { aggregate { count } } }
or similar is not supported by Prisma (in one single request), and if it was probably we cannot order by that in the same request.
Another solution would be adding a totalPosts
counter to the user and increment it every time a user writes a post, but atomic increments are not supported either so there could be issues with this as well. Therefore, what’s the recommended way to do this?Jenkins
02/22/2019, 7:20 AMctx.prisma.postConnection({where: { someIdField: parent.id }}).aggregate.count
something like that?
P.S. I'm not 100% on the syntax there - but that's the general gist.Fran Dios
02/22/2019, 7:30 AMJenkins
02/22/2019, 8:14 AMFran Dios
02/22/2019, 9:14 AMJenkins
02/22/2019, 9:18 AMmarcus
02/22/2019, 9:49 AMmarcus
02/22/2019, 9:56 AMcreatePost
in your application at some point. Inside this mutation you probably call a nested connect to the user for that Post.
2. My suggestion is to also update that User
in the same mutation. The User
should have a field lastPost: DateTime!
. Set that time to the current time.
3. Have a cronjob in the background that runs every few minutes. This cronjob can query all users that have a lastPost
greater than the last time it ran. Recompute the totalPosts
property for all users returned by that queries and write it to the users.marcus
02/22/2019, 9:58 AMtotalPosts
property might be out of date when you query. If your cronjob runs it is up-to-date again. Sounds good to me for your usecase. I guess your users won’t post lots of posts all the time. So that counter is off by max 1 for a few minutes.Fran Dios
02/22/2019, 10:02 AMreturn db.query.users()
. Then, I will have a “computed” User.totalPosts
field only in my API, not in my DB, and add a resolver for this field which basically does return db.query.postsConnection({ author: { id: "xxx" }, '{ aggregate { count } }')
.
Doesn’t this create 1 request for query.users
and many requests for query.postsConnection
(one per user)? Or is it batched somehow?Fran Dios
02/22/2019, 10:02 AMFran Dios
02/22/2019, 10:04 AMpg
would work for us as well. This is just a toy example with User+Post to make it easier.
In any case, thank you for taking the time @marcusmarcus
02/22/2019, 10:05 AMUser
type. I would add a new toplevel query field to your schema totalPosts
which allows you to retrieve those counts for multiple users at once.marcus
02/22/2019, 10:06 AMFran Dios
02/22/2019, 10:07 AMHow would be the query to Prisma in that case? I thought we would need a “group by user id” in order to make this in 1 request?which allows you to retrieve those counts for multiple users at once.totalPosts