-
Notifications
You must be signed in to change notification settings - Fork 2
/
validate-query.js
94 lines (81 loc) · 2.39 KB
/
validate-query.js
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
import ensureObject from './ensure-object.js';
import isObject from './is-object.js';
import PaveError from './pave-error.js';
import validateArgs from './validate-args.js';
const SKIP_ARGS = {};
const validateQuery = ({ context, path = [], query, schema, type }) => {
const fail = (code, extra) => {
throw new PaveError(code, { context, path, query, schema, type, ...extra });
};
do {
if (type == null) return {};
else if (!isObject(type)) {
if (schema[type]) type = schema[type];
else fail('unknownType');
} else if (type.nonNull) type = type.nonNull;
else if (type.arrayOf) type = type.arrayOf;
else if (type.oneOf) {
const _query = {};
for (const _type of type.oneOf) {
_query[`_on${_type}`] = validateQuery({
context,
path,
query,
schema,
type: _type
});
}
return _query;
} else if (type.fields) {
let { _field, ..._query } = ensureObject(query);
const merged = {};
const onKey = `_on${type.name}`;
for (const key in _query) {
if (key === onKey) Object.assign(merged, query[key]);
else if (!key.startsWith('_on')) merged[key] = query[key];
}
_query = {};
if (_field) _query._field = _field;
for (const alias in merged) {
const query = ensureObject(merged[alias]);
if (query === SKIP_ARGS) continue;
const field = query._field || alias;
let _type = type.fields[field];
if (!_type) {
if (field === '_type') _type = {};
else fail('unknownField', { alias, field });
}
_query[alias] = validateQuery({
context,
path: path.concat(alias),
query,
schema,
type: _type
});
}
return _query;
} else {
let { _args, _field, ..._query } = ensureObject(query);
_query = validateQuery({
context,
path,
query: { _args: SKIP_ARGS, ..._query },
schema,
type: type.type
});
if (_field) _query._field = _field;
if (_args !== SKIP_ARGS) {
_query._args = validateArgs({
context,
path: path.concat('_args'),
schema,
type,
value: _args
});
}
if (!type.args) delete _query._args;
return _query;
}
} while (true);
};
export default validateQuery;