|
1 | | -import { PetService } from './../services/PetService'; |
2 | 1 | import { |
3 | 2 | GraphQLID, |
4 | 3 | GraphQLString, |
5 | 4 | GraphQLObjectType, |
| 5 | + GraphQLFieldConfigMap, |
6 | 6 | GraphQLList, |
7 | 7 | } from 'graphql'; |
8 | | -import { PetType } from './PetType'; |
9 | | -import { User } from '../models/User'; |
| 8 | +import { merge } from 'lodash'; |
10 | 9 | import { GraphQLContext } from '../../lib/graphql'; |
| 10 | +import { PetOfUserType } from './PetType'; |
| 11 | +import { User } from '../models/User'; |
| 12 | + |
| 13 | +const UserFields: GraphQLFieldConfigMap = { |
| 14 | + id: { |
| 15 | + type: GraphQLID, |
| 16 | + description: 'The ID', |
| 17 | + }, |
| 18 | + firstName: { |
| 19 | + type: GraphQLString, |
| 20 | + description: 'The first name of the user.', |
| 21 | + }, |
| 22 | + lastName: { |
| 23 | + type: GraphQLString, |
| 24 | + description: 'The last name of the user.', |
| 25 | + }, |
| 26 | + email: { |
| 27 | + type: GraphQLString, |
| 28 | + description: 'The email of this user.', |
| 29 | + }, |
| 30 | +}; |
11 | 31 |
|
12 | 32 | export const UserType = new GraphQLObjectType({ |
13 | 33 | name: 'User', |
14 | 34 | description: 'A single user.', |
15 | | - fields: { |
16 | | - id: { |
17 | | - type: GraphQLID, |
18 | | - description: 'The ID', |
19 | | - }, |
20 | | - firstName: { |
21 | | - type: GraphQLString, |
22 | | - description: 'The first name of the user.', |
23 | | - }, |
24 | | - lastName: { |
25 | | - type: GraphQLString, |
26 | | - description: 'The last name of the user.', |
27 | | - }, |
28 | | - email: { |
29 | | - type: GraphQLString, |
30 | | - description: 'The email of this user.', |
31 | | - }, |
| 35 | + fields: () => merge<GraphQLFieldConfigMap, GraphQLFieldConfigMap>(UserFields, { |
32 | 36 | pets: { |
33 | | - type: new GraphQLList(PetType), |
| 37 | + type: new GraphQLList(PetOfUserType), |
34 | 38 | description: 'The pets of a user', |
35 | | - resolve: (user: User, args: any, context: GraphQLContext<any, any>) => |
36 | | - context.container.get<PetService>(PetService).findByUser(user), |
| 39 | + resolve: async (user: User, args: any, context: GraphQLContext<any, any>) => |
| 40 | + // We use data-loaders to save db queries |
| 41 | + context.dataLoaders.petByUserIds.loadMany([user.id]), |
| 42 | + // This would be the case with a normal service, but not very fast |
| 43 | + // context.container.get<PetService>(PetService).findByUser(user), |
37 | 44 | }, |
38 | | - }, |
| 45 | + }), |
| 46 | +}); |
| 47 | + |
| 48 | +export const OwnerType = new GraphQLObjectType({ |
| 49 | + name: 'Owner', |
| 50 | + description: 'The owner of a pet', |
| 51 | + fields: () => merge<GraphQLFieldConfigMap, GraphQLFieldConfigMap>(UserFields, {}), |
39 | 52 | }); |
0 commit comments