-
-
Notifications
You must be signed in to change notification settings - Fork 818
/
utils.ts
57 lines (48 loc) · 1.79 KB
/
utils.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
import { GraphQLObjectType, GraphQLSchema } from 'graphql';
import { getRootTypeNames } from '@graphql-tools/utils';
import { KeyTypeConstraints, Ref } from './types.js';
export function uuidv4() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
const r = (Math.random() * 16) | 0;
// eslint-disable-next-line eqeqeq
const v = c == 'x' ? r : (r & 0x3) | 0x8;
return v.toString(16);
});
}
export const randomListLength = () => {
// Mocking has always returned list of length 2 by default
// return 1 + Math.round(Math.random() * 10)
return 2;
};
export const takeRandom = <T>(arr: T[]) => arr[Math.floor(Math.random() * arr.length)];
export function makeRef<KeyT extends KeyTypeConstraints = string>(
typeName: string,
key: KeyT,
): Ref<KeyT> {
return { $ref: { key, typeName } };
}
export function isObject(thing: any) {
return thing === Object(thing) && !Array.isArray(thing);
}
export function copyOwnPropsIfNotPresent(target: Record<string, any>, source: Record<string, any>) {
for (const prop of Object.getOwnPropertyNames(source)) {
if (!Object.getOwnPropertyDescriptor(target, prop)) {
const propertyDescriptor = Object.getOwnPropertyDescriptor(source, prop);
Object.defineProperty(target, prop, propertyDescriptor == null ? {} : propertyDescriptor);
}
}
}
export function copyOwnProps(target: Record<string, any>, ...sources: Array<Record<string, any>>) {
for (const source of sources) {
let chain = source;
while (chain != null) {
copyOwnPropsIfNotPresent(target, chain);
chain = Object.getPrototypeOf(chain);
}
}
return target;
}
export const isRootType = (type: GraphQLObjectType, schema: GraphQLSchema) => {
const rootTypeNames = getRootTypeNames(schema);
return rootTypeNames.has(type.name);
};