This repository was archived by the owner on Jun 24, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathschema.js
More file actions
104 lines (90 loc) · 2.67 KB
/
schema.js
File metadata and controls
104 lines (90 loc) · 2.67 KB
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
'use strict';
const _get = require('lodash.get');
const {
GraphQLSchema,
GraphQLObjectType,
GraphQLList,
GraphQLString,
GraphQLInt
} = require('graphql');
const {EntrySysType, EntryType, IDType, CollectionMetaType} = require('./base-types.js');
const typeFieldConfigMap = require('./field-config.js');
const createBackrefsType = require('./backref-types.js');
const entryLoaderError = '\'entryLoader\' must be defined on the context.';
module.exports = {
createSchema,
createQueryType,
createQueryFields
};
function createSchema (spaceGraph, queryTypeName) {
return new GraphQLSchema({
query: createQueryType(spaceGraph, queryTypeName)
});
}
function createQueryType (spaceGraph, name = 'Query') {
return new GraphQLObjectType({
name,
fields: createQueryFields(spaceGraph)
});
}
function createQueryFields (spaceGraph) {
const ctIdToType = {};
return spaceGraph.reduce((acc, ct) => {
const defaultFieldsThunk = () => {
const fields = {sys: {type: EntrySysType}};
const BackrefsType = createBackrefsType(ct, ctIdToType);
if (BackrefsType) {
fields._backrefs = {type: BackrefsType, resolve: e => e.sys.id};
}
return fields;
};
const fieldsThunk = () => ct.fields.reduce((acc, f) => {
acc[f.id] = typeFieldConfigMap[f.type](f, ctIdToType);
return acc;
}, defaultFieldsThunk());
const Type = ctIdToType[ct.id] = new GraphQLObjectType({
name: ct.names.type,
interfaces: [EntryType],
fields: fieldsThunk,
isTypeOf: entry => {
const ctId = _get(entry, ['sys', 'contentType', 'sys', 'id']);
return ctId === ct.id;
}
});
acc[ct.names.field] = {
type: Type,
args: {id: {type: IDType}},
resolve: (_, args, ctx) => {
if (!ctx || !ctx.entryLoader) {
throw new TypeError(entryLoaderError);
}
return ctx.entryLoader.get(args.id, ct.id);
}
};
acc[ct.names.collectionField] = {
type: new GraphQLList(Type),
args: {
q: {type: GraphQLString},
skip: {type: GraphQLInt},
limit: {type: GraphQLInt}
},
resolve: (_, args, ctx) => {
if (!ctx || !ctx.entryLoader) {
throw new TypeError(entryLoaderError);
}
return ctx.entryLoader.query(ct.id, args);
}
};
acc[`_${ct.names.collectionField}Meta`] = {
type: CollectionMetaType,
args: {q: {type: GraphQLString}},
resolve: (_, args, ctx) => {
if (!ctx || !ctx.entryLoader) {
throw new TypeError(entryLoaderError);
}
return ctx.entryLoader.count(ct.id, args).then(count => ({count}));
}
};
return acc;
}, {});
}