Last active
August 31, 2022 17:25
-
-
Save Frando/1758dc8cca8e2d75b0b518c214b3158a to your computer and use it in GitHub Desktop.
Postgraphile plugin to add a default for `first` argument for connection queries
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { makeWrapResolversPlugin } from 'graphile-utils' | |
import type { GraphQLField } from 'graphql' | |
const PaginationDefault = makeWrapResolversPlugin( | |
({ scope }) => { | |
if (scope.isPgFieldConnection) { | |
return { scope } | |
} | |
return null | |
}, | |
({ scope }) => | |
async (resolver, _user, args, _context, resolveInfo) => { | |
const fieldName = scope.fieldName | |
const rootField = resolveInfo.schema.getQueryType()?.getFields()[fieldName] | |
if (rootField && hasPaginationArgs(rootField)) { | |
if (args.first === undefined && args.last === undefined) { | |
// If first and last are both unset, return the first 10 rows. | |
args.first = 10 | |
// Alternative: Return an error if neither first nor last is set. | |
// throw new Error('Either `first` or `last` argument is required.') | |
} | |
} | |
// @ts-ignore | |
const result = await resolver() | |
return result | |
}, | |
) | |
function hasPaginationArgs(field: GraphQLField<any, any>): boolean { | |
const hasArg = (name: string) => !!field.args.find((x) => x.name === name) | |
return hasArg('first') && hasArg('last') | |
} | |
export default PaginationDefault |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment