From 44623cc384ff13447c6cd84dd1a930a268d911a7 Mon Sep 17 00:00:00 2001 From: Faruk AYDIN Date: Thu, 10 Mar 2022 23:20:54 +0300 Subject: [PATCH] feat: Implement pagination logic and use with getExecutions query --- .../src/graphql/queries/get-executions.ts | 14 ++++++--- packages/backend/src/graphql/schema.graphql | 16 +++++++++- packages/backend/src/helpers/pagination.ts | 30 +++++++++++++++++++ 3 files changed, 55 insertions(+), 5 deletions(-) create mode 100644 packages/backend/src/helpers/pagination.ts diff --git a/packages/backend/src/graphql/queries/get-executions.ts b/packages/backend/src/graphql/queries/get-executions.ts index ed635650..2d41d722 100644 --- a/packages/backend/src/graphql/queries/get-executions.ts +++ b/packages/backend/src/graphql/queries/get-executions.ts @@ -1,16 +1,22 @@ import Context from '../../types/express/context'; +import paginate from '../../helpers/pagination'; + +type Params = { + limit: number; + offset: number; +}; const getExecutions = async ( _parent: unknown, - _params: unknown, + params: Params, context: Context ) => { - const executions = await context.currentUser + const executions = context.currentUser .$relatedQuery('executions') .withGraphFetched('flow') - .orderBy('created_at', 'asc'); + .orderBy('created_at', 'desc'); - return executions; + return paginate(executions, params.limit, params.offset); }; export default getExecutions; diff --git a/packages/backend/src/graphql/schema.graphql b/packages/backend/src/graphql/schema.graphql index 50b68224..ebe11b03 100644 --- a/packages/backend/src/graphql/schema.graphql +++ b/packages/backend/src/graphql/schema.graphql @@ -7,7 +7,7 @@ type Query { getFlow(id: String!): Flow getFlows: [Flow] getStepWithTestExecutions(stepId: String!): [Step] - getExecutions: [Execution] + getExecutions(limit: Int!, offset: Int!): ExecutionConnection } type Mutation { @@ -354,6 +354,20 @@ type User { updatedAt: String } +type PageInfo { + currentPage: Int! + totalPages: Int! +} + +type ExecutionEdge { + node: Execution +} + +type ExecutionConnection { + edges: [ExecutionEdge] + pageInfo: PageInfo +} + schema { query: Query mutation: Mutation diff --git a/packages/backend/src/helpers/pagination.ts b/packages/backend/src/helpers/pagination.ts new file mode 100644 index 00000000..b283dd93 --- /dev/null +++ b/packages/backend/src/helpers/pagination.ts @@ -0,0 +1,30 @@ +import { QueryBuilder, Model } from 'objection'; + +const paginate = async ( + query: QueryBuilder, + limit: number, + offset: number +) => { + if (limit < 1 || limit > 100) { + throw new Error('Limit must be between 1 and 100'); + } + + const [records, count] = await Promise.all([ + query.limit(limit).offset(offset), + query.resultSize(), + ]); + + return { + pageInfo: { + currentPage: Math.ceil(offset / limit + 1), + totalPages: Math.ceil(count / limit), + }, + edges: records.map((record: Model) => { + return { + node: record, + }; + }), + }; +}; + +export default paginate;