-
-
Notifications
You must be signed in to change notification settings - Fork 821
/
mock.ts
451 lines (413 loc) · 14.4 KB
/
mock.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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
import {
graphql,
GraphQLSchema,
GraphQLObjectType,
GraphQLEnumType,
GraphQLUnionType,
GraphQLInterfaceType,
GraphQLList,
GraphQLType,
GraphQLField,
GraphQLResolveInfo,
getNullableType,
getNamedType,
GraphQLNamedType,
GraphQLFieldResolver,
GraphQLNonNull,
} from 'graphql';
import * as uuid from 'uuid';
import {
forEachField,
buildSchemaFromTypeDefinitions,
} from './makeExecutableSchema';
import {
IMocks,
IMockServer,
IMockOptions,
IMockFn,
IMockTypeFn,
ITypeDefinitions,
} from './Interfaces';
// This function wraps addMockFunctionsToSchema for more convenience
function mockServer(
schema: GraphQLSchema | ITypeDefinitions,
mocks: IMocks,
preserveResolvers: boolean = false,
): IMockServer {
let mySchema: GraphQLSchema;
if (!(schema instanceof GraphQLSchema)) {
// TODO: provide useful error messages here if this fails
mySchema = buildSchemaFromTypeDefinitions(schema);
} else {
mySchema = schema;
}
addMockFunctionsToSchema({ schema: mySchema, mocks, preserveResolvers });
return { query: (query, vars) => graphql(mySchema, query, {}, {}, vars) };
}
const defaultMockMap: Map<string, IMockFn> = new Map();
defaultMockMap.set('Int', () => Math.round(Math.random() * 200) - 100);
defaultMockMap.set('Float', () => Math.random() * 200 - 100);
defaultMockMap.set('String', () => 'Hello World');
defaultMockMap.set('Boolean', () => Math.random() > 0.5);
defaultMockMap.set('ID', () => uuid.v4());
// TODO allow providing a seed such that lengths of list could be deterministic
// this could be done by using casual to get a random list length if the casual
// object is global.
function addMockFunctionsToSchema({
schema,
mocks = {},
preserveResolvers = false,
}: IMockOptions): void {
if (!schema) {
throw new Error('Must provide schema to mock');
}
if (!(schema instanceof GraphQLSchema)) {
throw new Error('Value at "schema" must be of type GraphQLSchema');
}
if (!isObject(mocks)) {
throw new Error('mocks must be of type Object');
}
// use Map internally, because that API is nicer.
const mockFunctionMap: Map<string, IMockFn> = new Map();
Object.keys(mocks).forEach(typeName => {
mockFunctionMap.set(typeName, mocks[typeName]);
});
mockFunctionMap.forEach((mockFunction, mockTypeName) => {
if (typeof mockFunction !== 'function') {
throw new Error(`mockFunctionMap[${mockTypeName}] must be a function`);
}
});
const mockType = function(
type: GraphQLType,
typeName?: string,
fieldName?: string,
): GraphQLFieldResolver<any, any> {
// order of precendence for mocking:
// 1. if the object passed in already has fieldName, just use that
// --> if it's a function, that becomes your resolver
// --> if it's a value, the mock resolver will return that
// 2. if the nullableType is a list, recurse
// 2. if there's a mock defined for this typeName, that will be used
// 3. if there's no mock defined, use the default mocks for this type
return (
root: any,
args: { [key: string]: any },
context: any,
info: GraphQLResolveInfo,
): any => {
// nullability doesn't matter for the purpose of mocking.
const fieldType = getNullableType(type);
const namedFieldType = getNamedType(fieldType);
if (root && typeof root[fieldName] !== 'undefined') {
let result: any;
// if we're here, the field is already defined
if (typeof root[fieldName] === 'function') {
result = root[fieldName](root, args, context, info);
if (result instanceof MockList) {
result = result.mock(
root,
args,
context,
info,
fieldType as GraphQLList<any>,
mockType,
);
}
} else {
result = root[fieldName];
}
// Now we merge the result with the default mock for this type.
// This allows overriding defaults while writing very little code.
if (mockFunctionMap.has(namedFieldType.name)) {
result = mergeMocks(
mockFunctionMap
.get(namedFieldType.name)
.bind(null, root, args, context, info),
result,
);
}
return result;
}
if (
fieldType instanceof GraphQLList ||
fieldType instanceof GraphQLNonNull
) {
return [
mockType(fieldType.ofType)(root, args, context, info),
mockType(fieldType.ofType)(root, args, context, info),
];
}
if (
mockFunctionMap.has(fieldType.name) &&
!(
fieldType instanceof GraphQLUnionType ||
fieldType instanceof GraphQLInterfaceType
)
) {
// the object passed doesn't have this field, so we apply the default mock
return mockFunctionMap.get(fieldType.name)(root, args, context, info);
}
if (fieldType instanceof GraphQLObjectType) {
// objects don't return actual data, we only need to mock scalars!
return {};
}
// if a mock function is provided for unionType or interfaceType, execute it to resolve the concrete type
// otherwise randomly pick a type from all implementation types
if (
fieldType instanceof GraphQLUnionType ||
fieldType instanceof GraphQLInterfaceType
) {
let implementationType;
if (mockFunctionMap.has(fieldType.name)) {
const interfaceMockObj = mockFunctionMap.get(fieldType.name)(
root,
args,
context,
info,
);
if (!interfaceMockObj || !interfaceMockObj.__typename) {
return Error(`Please return a __typename in "${fieldType.name}"`);
}
implementationType = schema.getType(interfaceMockObj.__typename);
} else {
const possibleTypes = schema.getPossibleTypes(fieldType);
implementationType = getRandomElement(possibleTypes);
}
return Object.assign(
{ __typename: implementationType },
mockType(implementationType)(root, args, context, info),
);
}
if (fieldType instanceof GraphQLEnumType) {
return getRandomElement(fieldType.getValues()).value;
}
if (defaultMockMap.has(fieldType.name)) {
return defaultMockMap.get(fieldType.name)(root, args, context, info);
}
// if we get to here, we don't have a value, and we don't have a mock for this type,
// we could return undefined, but that would be hard to debug, so we throw instead.
// however, we returning it instead of throwing it, so preserveResolvers can handle the failures.
return Error(`No mock defined for type "${fieldType.name}"`);
};
};
forEachField(
schema,
(field: GraphQLField<any, any>, typeName: string, fieldName: string) => {
assignResolveType(field.type, preserveResolvers);
let mockResolver: GraphQLFieldResolver<any, any>;
// we have to handle the root mutation and root query types differently,
// because no resolver is called at the root.
/* istanbul ignore next: Must provide schema DefinitionNode with query type or a type named Query. */
const isOnQueryType: boolean = schema.getQueryType() && schema.getQueryType().name === typeName
const isOnMutationType: boolean = schema.getMutationType() && schema.getMutationType().name === typeName
if (isOnQueryType || isOnMutationType) {
if (mockFunctionMap.has(typeName)) {
const rootMock = mockFunctionMap.get(typeName);
// XXX: BUG in here, need to provide proper signature for rootMock.
if (typeof rootMock(undefined, {}, {}, {} as any)[fieldName] === 'function') {
mockResolver = (
root: any,
args: { [key: string]: any },
context: any,
info: GraphQLResolveInfo,
) => {
const updatedRoot = root || {}; // TODO: should we clone instead?
updatedRoot[fieldName] = rootMock(root, args, context, info)[
fieldName
];
// XXX this is a bit of a hack to still use mockType, which
// lets you mock lists etc. as well
// otherwise we could just set field.resolve to rootMock()[fieldName]
// it's like pretending there was a resolve function that ran before
// the root resolve function.
return mockType(field.type, typeName, fieldName)(
updatedRoot,
args,
context,
info,
);
};
}
}
}
if (!mockResolver) {
mockResolver = mockType(field.type, typeName, fieldName);
}
if (!preserveResolvers || !field.resolve) {
field.resolve = mockResolver;
} else {
const oldResolver = field.resolve;
field.resolve = (
rootObject?: any,
args?: { [key: string]: any },
context?: any,
info?: GraphQLResolveInfo,
) =>
Promise.all([
mockResolver(rootObject, args, context, info),
oldResolver(rootObject, args, context, info),
]).then(values => {
const [mockedValue, resolvedValue] = values;
// 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;
});
}
},
);
}
function isObject(thing: any) {
return thing === Object(thing) && !Array.isArray(thing);
}
// returns a random element from that ary
function getRandomElement(ary: ReadonlyArray<any>) {
const sample = Math.floor(Math.random() * ary.length);
return ary[sample];
}
function mergeObjects(a: Object, b: Object) {
return Object.assign(a, b);
}
function copyOwnPropsIfNotPresent(target: Object, source: Object) {
Object.getOwnPropertyNames(source).forEach(prop => {
if (!Object.getOwnPropertyDescriptor(target, prop)) {
Object.defineProperty(
target,
prop,
Object.getOwnPropertyDescriptor(source, prop),
);
}
});
}
function copyOwnProps(target: Object, ...sources: Object[]) {
sources.forEach(source => {
let chain = source;
while (chain) {
copyOwnPropsIfNotPresent(target, chain);
chain = Object.getPrototypeOf(chain);
}
});
return target;
}
// takes either an object or a (possibly nested) array
// and completes the customMock object with any fields
// defined on genericMock
// only merges objects or arrays. Scalars are returned as is
function mergeMocks(genericMockFunction: () => any, customMock: any): any {
if (Array.isArray(customMock)) {
return customMock.map((el: any) => mergeMocks(genericMockFunction, el));
}
if (isObject(customMock)) {
return mergeObjects(genericMockFunction(), customMock);
}
return customMock;
}
function getResolveType(namedFieldType: GraphQLNamedType) {
if (
namedFieldType instanceof GraphQLInterfaceType ||
namedFieldType instanceof GraphQLUnionType
) {
return namedFieldType.resolveType;
} else {
return undefined;
}
}
function assignResolveType(type: GraphQLType, preserveResolvers: boolean) {
const fieldType = getNullableType(type);
const namedFieldType = getNamedType(fieldType);
const oldResolveType = getResolveType(namedFieldType);
if (preserveResolvers && oldResolveType && oldResolveType.length) {
return;
}
if (
namedFieldType instanceof GraphQLUnionType ||
namedFieldType instanceof GraphQLInterfaceType
) {
// the default `resolveType` always returns null. We add a fallback
// resolution that works with how unions and interface are mocked
namedFieldType.resolveType = (
data: any,
context: any,
info: GraphQLResolveInfo,
) => {
return info.schema.getType(data.__typename) as GraphQLObjectType;
};
}
}
class MockList {
private len: number | number[];
private wrappedFunction: GraphQLFieldResolver<any, any>;
// wrappedFunction can return another MockList or a value
constructor(
len: number | number[],
wrappedFunction?: GraphQLFieldResolver<any, any>,
) {
this.len = len;
if (typeof wrappedFunction !== 'undefined') {
if (typeof wrappedFunction !== 'function') {
throw new Error(
'Second argument to MockList must be a function or undefined',
);
}
this.wrappedFunction = wrappedFunction;
}
}
public mock(
root: any,
args: { [key: string]: any },
context: any,
info: GraphQLResolveInfo,
fieldType: GraphQLList<any>,
mockTypeFunc: IMockTypeFn,
) {
let arr: any[];
if (Array.isArray(this.len)) {
arr = new Array(this.randint(this.len[0], this.len[1]));
} else {
arr = new Array(this.len);
}
for (let i = 0; i < arr.length; i++) {
if (typeof this.wrappedFunction === 'function') {
const res = this.wrappedFunction(root, args, context, info);
if (res instanceof MockList) {
const nullableType = getNullableType(fieldType.ofType) as GraphQLList<
any
>;
arr[i] = res.mock(
root,
args,
context,
info,
nullableType,
mockTypeFunc,
);
} else {
arr[i] = res;
}
} else {
arr[i] = mockTypeFunc(fieldType.ofType)(root, args, context, info);
}
}
return arr;
}
private randint(low: number, high: number): number {
return Math.floor(Math.random() * (high - low + 1) + low);
}
}
export { addMockFunctionsToSchema, MockList, mockServer };