import * as express from 'express' ; import { GraphQLResolveInfo } from 'graphql' ; import * as getFieldNames from 'graphql-list-fields' ; import { Schema , Query , ObjectType , Field , Inject , compileSchema , } from 'typegql' ; import * as graphqlHTTP from 'express-graphql' ; function NeededFields ( filter = [ ] ) { return Inject ( ( { info } ) => { const selectionFieldNames = getFieldNames ( info ) ; if ( ! filter || ! filter . length ) { return selectionFieldNames ; } return selectionFieldNames . filter ( fieldName => { return filter . includes ( fieldName ) ; } ) ; } ) ; } @ ObjectType ( ) class LazyObject { constructor ( neededFields ) { console . log ( 'I will only perform expensive operations for fields:' , neededFields ) ; if ( neededFields . includes [ 'foo' ] ) { this . foo = 'I have foo' ; } if ( neededFields . includes [ 'bar' ] ) { this . bar = 'I have bar' ; } } @ Field ( ) foo : string ; @ Field ( ) bar : string ; } @ Schema ( ) class SuperSchema { @ Query ( ) foo ( @ NeededFields ( [ 'foo' , 'bar' ] ) neededFields ) { console . log ( 'Needed fields are: ' , { neededFields } ) ; return new LazyObject ( neededFields ) ; } } const compiledSchema = compileSchema ( SuperSchema ) ; const app = express ( ) ; app . use ( '/graphql' , graphqlHTTP ( { schema : compiledSchema , graphiql : true , } ) ) ; app . listen ( 3000 ) ;