1- const graphql = require ( 'graphql' ) ;
2- const _ = require ( 'lodash' ) ;
1+ const graphql = require ( "graphql" ) ;
2+ const axios = require ( "axios" ) ;
3+ const _ = require ( "lodash" ) ;
34
45const {
56 GraphQLObjectType,
67 GraphQLString,
78 GraphQLInt,
89 GraphQLSchema,
10+ GraphQLList
911} = graphql ;
1012
11- const users = [
12- {
13- id : '12' ,
14- firstName : 'Alice' ,
15- age : 22 ,
16- } ,
17- {
18- id : '23' ,
19- firstName : 'Bob' ,
20- age : 23 ,
21- }
22- ]
13+ const BASE_URL = 'http://localhost:3000' ;
14+
15+ const fetchFromUrl = url =>
16+ axios
17+ . get ( url )
18+ . then ( _ . property ( "data" ) )
19+ . catch ( console . error ) ;
20+
21+ const CompanyType = new GraphQLObjectType ( {
22+ name : "Company" ,
23+ fields : ( ) => ( {
24+ id : { type : GraphQLString } ,
25+ name : { type : GraphQLString } ,
26+ description : { type : GraphQLString } ,
27+ users : {
28+ type : new GraphQLList ( UserType ) ,
29+ resolve ( parentValue , args ) {
30+ return fetchFromUrl ( `${ BASE_URL } /companies/${ parentValue . id } /users` ) ;
31+ }
32+ }
33+ } )
34+ } ) ;
2335
2436const UserType = new GraphQLObjectType ( {
25- name : 'User' ,
26- fields : {
27- id : { type : GraphQLString } ,
28- firstName : { type : GraphQLString } ,
29- age : { type : GraphQLInt } ,
30- }
37+ name : "User" ,
38+ fields : ( ) => ( {
39+ id : { type : GraphQLString } ,
40+ firstName : { type : GraphQLString } ,
41+ age : { type : GraphQLInt } ,
42+ company : {
43+ type : CompanyType ,
44+ resolve ( parentValue , args ) {
45+ return fetchFromUrl (
46+ `${ BASE_URL } /companies/${ parentValue . companyId } `
47+ ) ;
48+ }
49+ }
50+ } )
3151} ) ;
3252
3353const RootQuery = new GraphQLObjectType ( {
34- name : ' RootQueryType' ,
54+ name : " RootQueryType" ,
3555 fields : {
36- userKey : {
56+ user : {
3757 type : UserType ,
3858 args : { id : { type : GraphQLString } } ,
3959 resolve ( parentValue , args ) {
40- return _ . find ( users , { id : args . id } ) ;
60+ return fetchFromUrl ( `${ BASE_URL } /users/${ args . id } ` ) ;
61+ }
62+ } ,
63+ company : {
64+ type : CompanyType ,
65+ args : { id : { type : GraphQLString } } ,
66+ resolve ( parentValue , args ) {
67+ return fetchFromUrl ( `${ BASE_URL } /companies/${ args . id } ` ) ;
4168 }
4269 }
4370 }
44- } )
71+ } ) ;
4572
4673module . exports = new GraphQLSchema ( {
47- query : RootQuery ,
48- } )
74+ query : RootQuery
75+ } ) ;
0 commit comments