-
-
Notifications
You must be signed in to change notification settings - Fork 174
/
Copy pathgenerator.ts
294 lines (263 loc) · 6.74 KB
/
generator.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
import {
IMiddleware,
IMiddlewareFunction,
IMiddlewareGeneratorConstructor,
} from 'graphql-middleware'
import {
GraphQLSchema,
GraphQLObjectType,
isObjectType,
isIntrospectionType,
GraphQLResolveInfo,
} from 'graphql'
import {
IRules,
IOptions,
ShieldRule,
IRuleFieldMap,
IShieldContext,
} from './types'
import {
isRuleFunction,
isRuleFieldMap,
isRule,
isLogicRule,
withDefault,
} from './utils'
import { ValidationError } from './validation'
import { IMiddlewareWithOptions } from 'graphql-middleware/dist/types'
/**
*
* @param options
*
* Generates a middleware function from a given rule and
* initializes the cache object in context.
*
*/
function generateFieldMiddlewareFromRule(
rule: ShieldRule,
options: IOptions,
): IMiddlewareFunction<object, object, IShieldContext> {
async function middleware(
resolve: (
parent: object,
args: object,
ctx: IShieldContext,
info: GraphQLResolveInfo,
) => Promise<any>,
parent: { [key: string]: any },
args: { [key: string]: any },
ctx: IShieldContext,
info: GraphQLResolveInfo,
) {
// Cache
if (!ctx) {
ctx = {} as IShieldContext
}
if (!ctx._shield) {
ctx._shield = {
cache: {},
}
}
// Execution
try {
const res = await rule.resolve(parent, args, ctx, info, options)
if (res === true) {
return await resolve(parent, args, ctx, info)
} else if (res === false) {
if (typeof options.fallbackError === 'function') {
return await options.fallbackError(null, parent, args, ctx, info)
}
return options.fallbackError
} else {
return res
}
} catch (err) {
if (options.debug) {
throw err
} else if (options.allowExternalErrors) {
return err
} else {
if (typeof options.fallbackError === 'function') {
return await options.fallbackError(err, parent, args, ctx, info)
}
return options.fallbackError
}
}
}
if (isRule(rule) && rule.extractFragment()) {
return {
fragment: rule.extractFragment(),
resolve: middleware,
} as IMiddlewareWithOptions<object, object, IShieldContext>
}
if (isLogicRule(rule)) {
return {
fragments: rule.extractFragments(),
resolve: middleware,
} as IMiddlewareWithOptions<object, object, IShieldContext>
}
return middleware as IMiddlewareFunction<object, object, IShieldContext>
}
/**
*
* @param type
* @param rules
* @param options
*
* Generates middleware from rule for a particular type.
*
*/
function applyRuleToType(
type: GraphQLObjectType,
rules: ShieldRule | IRuleFieldMap,
options: IOptions,
): IMiddleware {
if (isRuleFunction(rules)) {
/* Apply defined rule function to every field */
const fieldMap = type.getFields()
const middleware = Object.keys(fieldMap).reduce((middleware, field) => {
return {
...middleware,
[field]: generateFieldMiddlewareFromRule(rules, options),
}
}, {})
return middleware
} else if (isRuleFieldMap(rules)) {
/* Apply rules assigned to each field to each field */
const fieldMap = type.getFields()
/* Extract default type wildcard if any and remove it for validation */
const defaultTypeRule = rules['*']
delete rules['*']
/* Validation */
const fieldErrors = Object.keys(rules)
.filter((type) => !Object.prototype.hasOwnProperty.call(fieldMap, type))
.map((field) => `${type.name}.${field}`)
.join(', ')
if (fieldErrors.length > 0) {
throw new ValidationError(
`It seems like you have applied rules to ${fieldErrors} fields but Shield cannot find them in your schema.`,
)
}
/* Generation */
const middleware = Object.keys(fieldMap).reduce(
(middleware, field) => ({
...middleware,
[field]: generateFieldMiddlewareFromRule(
withDefault(defaultTypeRule || options.fallbackRule)(rules[field]),
options,
),
}),
{},
)
return middleware
} else {
/* Apply fallbackRule to type with no defined rule */
const fieldMap = type.getFields()
const middleware = Object.keys(fieldMap).reduce(
(middleware, field) => ({
...middleware,
[field]: generateFieldMiddlewareFromRule(options.fallbackRule, options),
}),
{},
)
return middleware
}
}
/**
*
* @param schema
* @param rule
* @param options
*
* Applies the same rule over entire schema.
*
*/
function applyRuleToSchema(
schema: GraphQLSchema,
rule: ShieldRule,
options: IOptions,
): IMiddleware {
const typeMap = schema.getTypeMap()
const middleware = Object.keys(typeMap)
.filter((type) => !isIntrospectionType(typeMap[type]))
.reduce((middleware, typeName) => {
const type = typeMap[typeName]
if (isObjectType(type)) {
return {
...middleware,
[typeName]: applyRuleToType(type, rule, options),
}
} else {
return middleware
}
}, {})
return middleware
}
/**
*
* @param rules
* @param wrapper
*
* Converts rule tree to middleware.
*
*/
function generateMiddlewareFromSchemaAndRuleTree(
schema: GraphQLSchema,
rules: IRules,
options: IOptions,
): IMiddleware {
if (isRuleFunction(rules)) {
/* Applies rule to entire schema. */
return applyRuleToSchema(schema, rules, options)
} else {
/**
* Checks type map and field map and applies rules
* to particular fields.
*/
const typeMap = schema.getTypeMap()
/* Validation */
const typeErrors = Object.keys(rules)
.filter((type) => !Object.prototype.hasOwnProperty.call(typeMap, type))
.join(', ')
if (typeErrors.length > 0) {
throw new ValidationError(
`It seems like you have applied rules to ${typeErrors} types but Shield cannot find them in your schema.`,
)
}
// Generation
const middleware = Object.keys(typeMap)
.filter((type) => !isIntrospectionType(typeMap[type]))
.reduce<IMiddleware>((middleware, typeName) => {
const type = typeMap[typeName]
if (isObjectType(type)) {
return {
...middleware,
[typeName]: applyRuleToType(type, rules[typeName], options),
}
} else {
return middleware
}
}, {})
return middleware
}
}
/**
*
* @param ruleTree
* @param options
*
* Generates middleware from given rules.
*
*/
export function generateMiddlewareGeneratorFromRuleTree<
TSource = any,
TContext = any,
TArgs = any
>(
ruleTree: IRules,
options: IOptions,
): IMiddlewareGeneratorConstructor<TSource, TContext, TArgs> {
return (schema: GraphQLSchema) =>
generateMiddlewareFromSchemaAndRuleTree(schema, ruleTree, options)
}