如何在GraphQL+Apollo Server+Node.js中对Resolver返回的数组排序?
在GraphQL Resolver中对关联数组排序的方法
我目前只会通过数据库查询实现排序,现在需要在GraphQL Resolver里对返回的关联数组(比如示例中的comment数组)进行排序,不清楚具体实现方式。
当前Query Resolver代码
getAllNotifications: ( _parent, _args: { authorId: string }, context: Context ) => { return context.prisma.blog.findMany({ where: { authorId: _args.authorId, }, orderBy: { created_at: "desc", }, }); },
查询语句
query Query($authorId: String) { getAllNotifications(authorId: $authorId) { title comment { id created_at } } }
返回结果
{ "data": { "getAllNotifications": [ { "title": "First Ride! ", "comment": [ // 需要按created_at日期对这个数组排序 { "id": "cl8afqaqx001209jtxx7mt5h6", "created_at": "2022-09-20T16:53:07.689Z" }, { "id": "cl8agiq71001509l27or7oxyd", "created_at": "2022-09-20T17:15:14.077Z" }, { "id": "cl8ahmvrm003109l8dp684bn6", "created_at": "2022-09-20T17:46:27.538Z" }, { "id": "cl99kj24p002609iajdbpycg0", "created_at": "2022-10-15T06:59:24.169Z" } ] } ] } }
解决方案
方案1:数据库层面排序(推荐)
直接在Prisma查询关联数据时指定排序规则,性能更优:
getAllNotifications: ( _parent, _args: { authorId: string }, context: Context ) => { return context.prisma.blog.findMany({ where: { authorId: _args.authorId, }, orderBy: { created_at: "desc", }, // 新增include配置,对关联的comment排序 include: { comment: { orderBy: { created_at: "desc" // 改为"asc"可实现升序排序 } } } }); }
方案2:Resolver内存中手动排序
如果无法在数据库层面处理,可在Resolver获取数据后手动排序:
getAllNotifications: async ( _parent, _args: { authorId: string }, context: Context ) => { const blogs = await context.prisma.blog.findMany({ where: { authorId: _args.authorId, }, orderBy: { created_at: "desc", }, }); // 对每个blog的comment数组按created_at降序排序 return blogs.map(blog => ({ ...blog, // 复制数组后再排序,避免修改原数据 comment: [...blog.comment].sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime() ) })); }
说明
GraphQL本身没有内置的数组排序功能,所有排序逻辑需要在数据获取阶段(数据库查询)或Resolver返回数据前手动实现。优先选择数据库层面排序,减少内存计算开销。
内容的提问来源于stack exchange,提问作者thisisjaymehta
相关产品推荐
相关产品推荐

