This repository has been archived by the owner on Jan 19, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlib.ts
67 lines (65 loc) · 2.19 KB
/
lib.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
import { GraphQLList, GraphQLObjectType } from "graphql";
import { TypeComposer, GraphQLJSON } from "graphql-compose";
import * as _ from "lodash";
// graphql-leveler implementation for graphql-compose
function levelerize(tc: TypeComposer, levelerVisited: Set<string>) {
const fieldNames = tc.getFieldNames();
if (levelerVisited.has(tc.getTypeName())) {
return;
}
levelerVisited.add(tc.getTypeName());
for (const fieldName of fieldNames) {
const fieldType = tc.getFieldType(fieldName);
if (
fieldType instanceof GraphQLObjectType ||
(fieldType instanceof GraphQLList && fieldType.ofType instanceof GraphQLObjectType)
) {
const fieldTC = tc.getFieldTC(fieldName);
levelerize(tc.getFieldTC(fieldName), levelerVisited);
fieldTC.addFields({
_get: {
type: "JSON",
args: {
path: "String!",
defaultValue: "JSON",
allowUndefined: "Boolean"
},
resolve: (obj, { path, defaultValue, allowUndefined = false }) => {
const val = _.get(obj, path, defaultValue);
if (!allowUndefined && typeof val === "undefined") {
throw new Error(`The "${path}" property does not exist.`);
}
return val;
}
},
// bonus feature
_pluck: {
type: new GraphQLList(GraphQLJSON),
args: {
list: "String!",
path: "String!",
allowUndefined: "Boolean"
},
resolve: (obj, { list, path, allowUndefined = false }) => {
const theList = _.get(obj, list, []);
if (!allowUndefined && typeof theList === "undefined") {
throw new Error(`The "${list}" list does not exist.`);
}
const val = _.map(theList, path);
if (!allowUndefined && typeof val === "undefined") {
throw new Error(`The "${path}" path within list does not exist.`);
}
return val;
}
},
_root: {
type: fieldTC.getType(),
resolve: obj => obj
}
});
}
}
}
export default function (tc: TypeComposer) {
levelerize(tc, new Set<string>());
}