Graphql 基于 offset 的分页查询
Server 端
graphql schema 定义:
type Post { id: Int body: String published: Boolean title: String } type PageInfo { page: Int limit: Int } type PostsResult { totalCount: Int edges: [Post] pageInfo: PageInfo } type Query { posts(page: Int, limit: Int): PostsResult }
resolvers 定义,基于 nodejs :
'use strict' const Fastify = require('fastify') const mercurius = require('mercurius') const { PrismaClient } = require('@prisma/client') const app = Fastify() const prisma = new PrismaClient() const schema = ` type Post { id: Int body: String published: Boolean title: String } type PageInfo { page: Int limit: Int } type PostsResult { totalCount: Int edges: [Post] pageInfo: PageInfo } type Query { posts(page: Int, limit: Int): PostsResult } ` const resolvers = { Query: { posts: async (_parent, args, ctx) => { const page = args.page ?? 1; const limit = args.limit == null || args.limit > 100 || args.limit <= 0 ? 10: args.limit; const total = await ctx.prisma.post.count(); const posts = await ctx.prisma.post.findMany({ skip: (page - 1) * limit, take: limit, }); return { totalCount: total, edges: posts, pageInfo: { page, limit, } }; }, }, } app.register(mercurius, { schema, resolvers, context: (request, reply) => { return {prisma} } }) app.listen({port: 3000}).then(() => { console.log(`
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论