import { GraphQLSchema } from 'graphql' ; import { addResolversToSchema } from '@graphql-tools/schema' ; import { IApplyOptions , IMiddleware , FragmentReplacement , IMiddlewareGenerator , GraphQLSchemaWithFragmentReplacements , } from './types' ; import { generateResolverFromSchemaAndMiddleware } from './applicator' ; import { validateMiddleware } from './validation' ; import { extractFragmentReplacements } from './fragments' ; import { isMiddlewareGenerator } from './utils' ; param schema param options param middleware export function addMiddlewareToSchema < TSource , TContext , TArgs > ( schema , options , middleware ) { const validMiddleware = validateMiddleware ( schema , middleware ) ; const resolvers = generateResolverFromSchemaAndMiddleware ( schema , options , validMiddleware ) ; const fragmentReplacements = extractFragmentReplacements ( resolvers ) ; const newSchema = addResolversToSchema ( { schema , resolvers , updateResolversInPlace : false , resolverValidationOptions : { requireResolversForResolveType : 'ignore' , } , } ) ; return { schema : newSchema , fragmentReplacements } ; } param schema param options param middlewares function applyMiddlewareWithOptions < TSource = any , TContext = any , TArgs = any > ( schema , options , ... middlewares ) { const normalisedMiddlewares = middlewares . map ( ( middleware ) => { if ( isMiddlewareGenerator ( middleware ) ) { return middleware . generate ( schema ) ; } else { return middleware ; } } ) ; const schemaWithMiddlewareAndFragmentReplacements = normalisedMiddlewares . reduceRight ( ( { schema : currentSchema , fragmentReplacements : currentFragmentReplacements , } , middleware ) => { const { schema : newSchema , fragmentReplacements : newFragmentReplacements , } = addMiddlewareToSchema ( currentSchema , options , middleware ) ; return { schema : newSchema , fragmentReplacements : [ ... currentFragmentReplacements , ... newFragmentReplacements , ] , } ; } , { schema , fragmentReplacements : [ ] } ) ; const schemaWithMiddleware = schemaWithMiddlewareAndFragmentReplacements . schema ; schemaWithMiddleware . schema = schemaWithMiddlewareAndFragmentReplacements . schema ; schemaWithMiddleware . fragmentReplacements = schemaWithMiddlewareAndFragmentReplacements . fragmentReplacements ; return schemaWithMiddleware ; } param schema param middlewares export function applyMiddleware < TSource = any , TContext = any , TArgs = any > ( schema , ... middlewares ) { return applyMiddlewareWithOptions ( schema , { onlyDeclaredResolvers : false } , ... middlewares ) ; } param schema param middlewares export function applyMiddlewareToDeclaredResolvers < TSource = any , TContext = any , TArgs = any > ( schema , ... middlewares ) { return applyMiddlewareWithOptions ( schema , { onlyDeclaredResolvers : true } , ... middlewares ) ; }