-
-
Notifications
You must be signed in to change notification settings - Fork 821
/
addMocksToSchema.ts
256 lines (233 loc) · 7.19 KB
/
addMocksToSchema.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
import {
GraphQLSchema,
GraphQLFieldResolver,
defaultFieldResolver,
GraphQLObjectType,
GraphQLTypeResolver,
isUnionType,
GraphQLUnionType,
GraphQLInterfaceType,
isSchema,
} from 'graphql';
import { mapSchema, MapperKind, IResolvers } from '@graphql-tools/utils';
import { addResolversToSchema } from '@graphql-tools/schema';
import { isRef, IMockStore, IMocks, TypePolicy } from './types';
import { copyOwnProps, isObject } from './utils';
import { createMockStore } from '.';
type IMockOptions = {
schema: GraphQLSchema;
store?: IMockStore;
mocks?: IMocks;
typePolicies?: {
[typeName: string]: TypePolicy;
};
resolvers?: IResolvers | ((store: IMockStore) => IResolvers);
/**
* Set to `true` to prevent existing resolvers from being
* overwritten to provide mock data. This can be used to mock some parts of the
* server and not others.
*/
preserveResolvers?: boolean;
};
// todo: add option to preserve resolver
/**
* Given a `schema` and a `MockStore`, returns an executable schema that
* will use the provided `MockStore` to execute queries.
*
* ```ts
* const schema = buildSchema(`
* type User {
* id: ID!
* name: String!
* }
* type Query {
* me: User!
* }
* `)
*
* const store = createMockStore({ schema });
* const mockedSchema = addMocksToSchema({ schema, store });
* ```
*
*
* If a `resolvers` parameter is passed, the query execution will use
* the provided `resolvers` if, one exists, instead of the default mock
* resolver.
*
*
* ```ts
* const schema = buildSchema(`
* type User {
* id: ID!
* name: String!
* }
* type Query {
* me: User!
* }
* type Mutation {
* setMyName(newName: String!): User!
* }
* `)
*
* const store = createMockStore({ schema });
* const mockedSchema = addMocksToSchema({
* schema,
* store,
* resolvers: {
* Mutation: {
* setMyName: (_, { newName }) => {
* const ref = store.get('Query', 'ROOT', 'viewer');
* store.set(ref, 'name', newName);
* return ref;
* }
* }
* }
* });
* ```
*
*
* `Query` and `Mutation` type will use `key` `'ROOT'`.
*/
export function addMocksToSchema({
schema,
store: maybeStore,
mocks,
typePolicies,
resolvers: resolversOrFnResolvers,
preserveResolvers = false,
}: IMockOptions): GraphQLSchema {
if (!schema) {
throw new Error('Must provide schema to mock');
}
if (!isSchema(schema)) {
throw new Error('Value at "schema" must be of type GraphQLSchema');
}
if (mocks && !isObject(mocks)) {
throw new Error('mocks must be of type Object');
}
const store =
maybeStore ||
createMockStore({
schema,
mocks,
typePolicies,
});
const resolvers =
typeof resolversOrFnResolvers === 'function' ? resolversOrFnResolvers(store) : resolversOrFnResolvers;
const mockResolver: GraphQLFieldResolver<any, any> = (source, args, contex, info) => {
const defaultResolvedValue = defaultFieldResolver(source, args, contex, info);
// priority to default resolved value
if (defaultResolvedValue !== undefined) return defaultResolvedValue;
if (isRef(source)) {
return store.get({
typeName: source.$ref.typeName,
key: source.$ref.key,
fieldName: info.fieldName,
fieldArgs: args,
});
}
// we have to handle the root mutation, root query and root subscripton types
// differently, because no resolver is called at the root
if (isRootType(info.parentType, info.schema)) {
return store.get({
typeName: info.parentType.name,
key: 'ROOT',
fieldName: info.fieldName,
fieldArgs: args,
});
}
return undefined;
};
const typeResolver: GraphQLTypeResolver<any, any> = data => {
if (isRef(data)) {
return data.$ref.typeName;
}
};
const mockSubscriber: GraphQLFieldResolver<any, any> = () => ({
[Symbol.asyncIterator]() {
return {
async next() {
return {
done: true,
value: {},
};
},
};
},
});
const schemaWithMocks = mapSchema(schema, {
[MapperKind.OBJECT_FIELD]: fieldConfig => {
const newFieldConfig = {
...fieldConfig,
};
const oldResolver = fieldConfig.resolve;
if (!preserveResolvers || !oldResolver) {
newFieldConfig.resolve = mockResolver;
} else {
newFieldConfig.resolve = async (rootObject, args, context, info) => {
const [mockedValue, resolvedValue] = await Promise.all([
mockResolver(rootObject, args, context, info),
oldResolver(rootObject, args, context, info),
]);
// In case we couldn't mock
if (mockedValue instanceof Error) {
// only if value was not resolved, populate the error.
if (undefined === resolvedValue) {
throw mockedValue;
}
return resolvedValue;
}
if (resolvedValue instanceof Date && mockedValue instanceof Date) {
return undefined !== resolvedValue ? resolvedValue : mockedValue;
}
if (isObject(mockedValue) && isObject(resolvedValue)) {
// Object.assign() won't do here, as we need to all properties, including
// the non-enumerable ones and defined using Object.defineProperty
const emptyObject = Object.create(Object.getPrototypeOf(resolvedValue));
return copyOwnProps(emptyObject, resolvedValue, mockedValue);
}
return undefined !== resolvedValue ? resolvedValue : mockedValue;
};
}
const fieldSubscriber = fieldConfig.subscribe;
if (!preserveResolvers || !fieldSubscriber) {
newFieldConfig.subscribe = mockSubscriber;
} else {
newFieldConfig.subscribe = async (rootObject, args, context, info) => {
const [mockAsyncIterable, oldAsyncIterable] = await Promise.all([
mockSubscriber(rootObject, args, context, info),
fieldSubscriber(rootObject, args, context, info),
]);
return oldAsyncIterable || mockAsyncIterable;
};
}
return newFieldConfig;
},
[MapperKind.ABSTRACT_TYPE]: type => {
if (preserveResolvers && type.resolveType != null && type.resolveType.length) {
return;
}
if (isUnionType(type)) {
return new GraphQLUnionType({
...type.toConfig(),
resolveType: typeResolver,
});
} else {
return new GraphQLInterfaceType({
...type.toConfig(),
resolveType: typeResolver,
});
}
},
});
return resolvers ? addResolversToSchema(schemaWithMocks, resolvers) : schemaWithMocks;
}
const isRootType = (type: GraphQLObjectType, schema: GraphQLSchema) => {
const queryType = schema.getQueryType();
const isOnQueryType = queryType != null && queryType.name === type.name;
const mutationType = schema.getMutationType();
const isOnMutationType = mutationType != null && mutationType.name === type.name;
const subscriptionType = schema.getSubscriptionType();
const isOnSubscriptionType = subscriptionType != null && subscriptionType.name === type.name;
return isOnQueryType || isOnMutationType || isOnSubscriptionType;
};