graphql-lookahead
v1.4.0
Published
GraphQL Lookahead in Typescript to check if some fields are present in the operation
Maintainers
Readme
GraphQL Lookahead in Javascript
Use graphql-lookahead to check within the resolver function if particular fields are part of the operation (query or mutation).
❤️ Provided by Elio Tax's engineering team
| | | :---: | | 🇨🇦 Online tax filing service 🇨🇦 |
Table of contents
Highlights
- ⚡️ Performant - Avoid querying nested database relationships if they are not requested.
- 🎯 Accurate - Check for the
fieldortypename. Check for a specific hierarchy of fields. - 🧘 Flexible - Works with any ORM, query builder, GraphQL servers.
- 💪 Reliable - Covered by integration tests.
- 🏀 Accessible - Clone this repository and try it out locally using the playground.
Quick Setup
Install the module:
# pnpm
pnpm add graphql-lookahead
# yarn
yarn add graphql-lookahead
# npm
npm i graphql-lookaheadBasic usage
You can add a condition using the until option which will be called for every nested field within the operation starting from the resolver field.
import type { createSchema } from 'graphql-yoga'
import { lookahead } from 'graphql-lookahead'
type Resolver = NonNullable<Parameters<typeof createSchema>[0]['resolvers']>
export const resolvers: Resolver = {
Query: {
order: async (_parent, args, _context, info) => {
//
// add your condition
if (lookahead({ info, until: ({ field }) => field === 'product' })) {
// include product in the query
}
// ...
},
},
}Types
function lookahead<TState, RError extends boolean | undefined>(options: {
depth?: number | null
info: GraphQLResolveInfo
next?: (details: NextHandlerDetails<TState>) => TState
nextFragment?: (details: NextFragmentHandlerDetails<TState>) => TState
onError?: (err: unknown) => RError
state?: TState
until?: (details: UntilHandlerDetails<TState>) => boolean
}): boolean
type HandlerDetailsBase<TState> = {
info: GraphQLResolveInfo
sourceType: string
state: TState
type: string
}
type HandlerDetails<TState> = HandlerDetailsBase<TState> & {
args: { [arg: string]: unknown }
field: string
fieldDef: GraphQLField
isList: boolean
selection: FieldNode
}
type UntilHandlerDetails<TState> = HandlerDetails<TState> & {
nextSelectionSet?: SelectionSetNode
}
type NextHandlerDetails<TState> = HandlerDetails<TState> & {
nextSelectionSet: SelectionSetNode
}
type NextFragmentHandlerDetails<TState> = HandlerDetailsBase<TState> & {
nextSelectionSet: SelectionSetNode
selection: FragmentSpreadNode | InlineFragmentNode
}Options
| Name | Description |
| ------ | :---------- |
| depth | ❔ Optional - Specify how deep it should look in the selectionSet (i.e. depth: 1 is the initial selectionSet, depth: null is no limit). Default: depth: null. |
| info | ❗️ Required - GraphQLResolveInfo object which is usually the fourth argument of the resolver function. |
| next | ❔ Optional - Handler called for every field with subfields within the operation. It can return a state that will be passed to each next call of its direct child fields. See Advanced usage. |
| nextFragment | ❔ Optional - Handler called for fragment selections (next is only called for field selections). See Advanced usage. |
| onError | ❔ Optional - Hook called from a try..catch when an error is caught. Default: (err: unknown) => { console.error(ERROR_PREFIX, err); return true }. |
| state | ❔ Optional - Initial state passed to next and nextFragment (and their nested calls). See Advanced usage. |
| until | ❔ Optional - Handler called for every nested field within the operation. Returning true will stop the iteration and make lookahead return true as well. |
Advanced usage
You can pass a state and use the next option that will be called for every nested field within the operation. It is similar to until, but next can mutate the parent state and return the next state that will be passed to its child fields. You will still need the until option if you want to stop the iteration at some point (optional).
If your schema matches your database models, you could build the query filters like this:
Example: Sequelize with nested query filters
- Sequelize documentation: Multiple eager loading
- Stackoverflow: Nested include in sequelize?
import type { createSchema } from 'graphql-yoga'
import { lookahead } from 'graphql-lookahead'
type Resolver = NonNullable<Parameters<typeof createSchema>[0]['resolvers']>
interface QueryFilter {
model?: string
include?: (QueryFilter | string)[]
}
export const resolvers: Resolver = {
Query: {
order: async (_parent, args, _context, info) => {
const sequelizeQueryFilters: QueryFilter = {}
lookahead({
info,
state: sequelizeQueryFilters,
next({ state, type }) {
const nextState: QueryFilter = { model: type }
state.include = state.include || []
state.include.push(nextState)
return nextState
},
})
/**
* `sequelizeQueryFilters` now equals to
* {
* include: [
* {
* model: 'OrderItem',
* include: [
* { model: 'Product', include: [{ model: 'Inventory' }] },
* { model: 'ProductGroup' },
* ],
* },
* ],
* }
*
* or would be without the `ProductGroup` filter if the operation didn't include it
*/
return await Order.findOne(sequelizeQueryFilters)
},
},
}Fragment selections (nextFragment)
For each fragment step in the operation (... on Type { } or ...FragmentName), lookahead calls nextFragment instead of next. It has the same state and return contract as next for nested handlers.
Inline fragments without a type condition (e.g. ... @include(if: true) { }) do not invoke nextFragment (or next / until for that node). The walker still descends into their selection set using the parent GraphQL type and the current state.
More examples in integration tests
- See graphql-yoga directory
Playground
You can play around with lookahead and our mock schema by cloning this repository and running the dev script locally (requires pnpm).
pnpm install
pnpm devVisit the playground at http://localhost:4455/graphql 🚀
Contribution
# Install dependencies
pnpm install
# Develop using the playground
pnpm dev
# Run ESLint
pnpm lint
# Run Vitest
pnpm test
# Run Vitest in watch mode
pnpm test:watch