import { UserInputError } from 'apollo-server-express' ; import { fromGlobalId , toGlobalId } from 'graphql-relay' ; import { Arg , Ctx , FieldResolver , ID , Info , Query , Resolver , Root } from 'type-graphql' ; import { Context } from '../interfaces/context.interface' ; import { Node } from './node.interface' ; @ Resolver ( ( ) => Node ) export class NodeResolver { @ FieldResolver ( ) globalId ( @ Root ( ) { id } , @ Info ( ) { parentType : { name } } ) { return toGlobalId ( name , id ) ; } private async fetcher ( globalId , { repositories } ) { const { type , id } = fromGlobalId ( globalId ) ; const repository = repositories [ type ] ; if ( ! repository ) { throw new UserInputError ( `Could not resolve to a node with the global ID of '${ globalId }'` ) ; } return await repository . findOne ( id ) ; } @ Query ( ( ) => Node , { nullable : true , description : 'Fetches an object given its global ID.' } ) node ( @ Arg ( 'id' , ( ) => ID , { description : 'The global ID of the object.' } ) globalId , @ Ctx ( ) context ) { return this . fetcher ( globalId , context ) ; } @ Query ( ( ) => [ Node ] , { nullable : 'items' , description : 'Fetches objects given their global IDs.' } ) nodes ( @ Arg ( 'ids' , ( ) => [ ID ] , { description : 'The global IDs of the objects.' } ) globalIds , @ Ctx ( ) context ) { return globalIds . map ( id => this . fetcher ( id , context ) ) ; } }