/
nullabilityGuardPlugin.ts
222 lines (211 loc) · 6.82 KB
/
nullabilityGuardPlugin.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
import {
GraphQLNullableType,
GraphQLOutputType,
GraphQLResolveInfo,
isEnumType,
isInterfaceType,
isListType,
isNonNullType,
isObjectType,
isScalarType,
isUnionType,
isWrappingType,
} from 'graphql'
import { forEach } from 'iterall'
import { GraphQLPossibleOutputs } from '../definitions/_types'
import { NexusGraphQLNamedType } from '../extensions'
import { CreateFieldResolverInfo, plugin } from '../plugin'
import { AllOutputTypes, GetGen, GetGen2 } from '../typegenTypeHelpers'
import { isPromiseLike, printedGenTyping } from '../utils'
export interface NullabilityPluginFallbackFn {
ctx: GetGen<'context'>
info: GraphQLResolveInfo
type: GraphQLPossibleOutputs
}
export interface NullabilityPluginOnGuardedConfig {
fallback: any
ctx: GetGen<'context'>
info: GraphQLResolveInfo
type: GraphQLNullableType
}
export type NullFallbackValues = Partial<
{
[K in AllOutputTypes]: (obj: NullabilityPluginFallbackFn) => GetGen2<'rootTypes', K>
}
>
export type NullabilityGuardConfig = {
/**
* Whether we should guard against non-null values. Defaults to "true" if NODE_ENV === "production",
* false otherwise.
*/
shouldGuard?: boolean
/**
* When a nullish value is "guarded", meaning it is coerced into an acceptable non-null
* value, this function will be called if supplied.
*/
onGuarded?: (obj: NullabilityPluginOnGuardedConfig) => void
/**
* A mapping of typename to the value that should be used in the case of a null value.
*/
fallbackValues?: NullFallbackValues
}
const fieldDefTypes = printedGenTyping({
name: 'skipNullGuard',
optional: true,
type: 'boolean',
description: `
The nullability guard can be helpful, but is also a potentially expensive operation for lists.
We need to iterate the entire list to check for null items to guard against. Set this to true
to skip the null guard on a specific field if you know there's no potential for unsafe types.
`,
})
export const nullabilityGuardPlugin = (pluginConfig: NullabilityGuardConfig) => {
const {
shouldGuard = process.env.NODE_ENV === 'production',
fallbackValues = {},
onGuarded = (obj: NullabilityPluginOnGuardedConfig) => {
console.warn(`Nullability guard called for ${obj.info.parentType.name}.${obj.info.fieldName}`)
},
} = pluginConfig
const finalPluginConfig: Required<NullabilityGuardConfig> = {
shouldGuard,
onGuarded,
fallbackValues,
}
return plugin({
name: 'NullabilityGuard',
description: 'If we have a nullable field, we want to guard against this being an issue in production.',
fieldDefTypes,
onCreateFieldResolver(config: CreateFieldResolverInfo<{ skipNullGuard: boolean }>) {
if (config.fieldConfig.extensions?.nexus?.config.skipNullGuard) {
return
}
const { type } = config.fieldConfig
const { outerNonNull, hasListNonNull } = nonNullInfo(type)
if (outerNonNull || hasListNonNull) {
return (root, args, ctx, info, next) => {
return plugin.completeValue(
next(root, args, ctx, info),
nonNullGuard(
ctx,
info,
isNonNullType(type) ? type.ofType : type,
config,
finalPluginConfig,
outerNonNull
)
)
}
}
},
onAfterBuild(schema) {
Object.keys(schema.getTypeMap()).forEach((typeName) => {
const type = schema.getType(typeName) as NexusGraphQLNamedType
if (isScalarType(type)) {
if (fallbackValues[type.name as keyof typeof fallbackValues]) {
return
}
console.error(
`No nullability guard was provided for Scalar ${type.name}. ` +
`Provide one in the nullabilityGuard config to remove this warning.`
)
}
})
if (pluginConfig.fallbackValues) {
Object.keys(pluginConfig.fallbackValues).forEach((name) => {
const type = schema.getType(name) as NexusGraphQLNamedType
if (!type) {
return console.error(`Unknown type ${name} provided in nullabilityGuard fallbackValues config.`)
}
})
}
},
})
}
const isNullish = (val: any): boolean => val === null || val === undefined || val !== val
const nonNullGuard = (
ctx: GetGen<'context'>,
info: GraphQLResolveInfo,
type: GraphQLOutputType,
config: CreateFieldResolverInfo,
pluginConfig: Required<NullabilityGuardConfig>,
outerNonNull: boolean
) => {
const { onGuarded, fallbackValues, shouldGuard } = pluginConfig
const guardResult = (fallback: any) => {
onGuarded({ ctx, info, type, fallback })
return shouldGuard ? fallback : null
}
return (val: any) => {
// If it's a list type, return [] if the value is null,
// otherwise recurse into resolving the individual type.
if (isListType(type)) {
if (isNullish(val)) {
return outerNonNull ? guardResult([]) : null
}
let hasPromise = false
const listMembers: any[] = []
const listCompleter = nonNullGuard(
ctx,
info,
isNonNullType(type.ofType) ? type.ofType.ofType : type.ofType,
config,
pluginConfig,
isNonNullType(type.ofType)
)
forEach(val as any, (item) => {
if (!hasPromise && isPromiseLike(item)) {
hasPromise = true
}
listMembers.push(plugin.completeValue(item, listCompleter))
})
return hasPromise ? Promise.all(listMembers) : listMembers
}
if (!isNullish(val) || outerNonNull === false) {
return val
}
const typeName = type.name as keyof typeof fallbackValues
const fallbackFn = fallbackValues[typeName]
const fallbackValue = typeof fallbackFn === 'function' ? fallbackFn({ type, info, ctx }) : null
if (!isNullish(fallbackValue)) {
return guardResult(fallbackValue)
}
// If it's an object, just return an empty object and let the scalar fallbacks take care of the rest
if (isObjectType(type)) {
return guardResult({})
}
// If it's an enum, return the first member
if (isEnumType(type)) {
return guardResult(type.getValues()[0].value)
}
// If It's a union or interface, return the first type
if (isUnionType(type) || isInterfaceType(type)) {
const possibleTypes = info.schema.getPossibleTypes(type)
return guardResult({ __typename: possibleTypes[0].name })
}
// Otherwise, fail?
return val
}
}
interface NonNullInfo {
outerNonNull: boolean
hasListNonNull: boolean
}
const nonNullInfo = (type: GraphQLOutputType): NonNullInfo => {
let outerNonNull = false
let hasListNonNull = false
if (isNonNullType(type)) {
outerNonNull = true
type = type.ofType
}
while (isWrappingType(type)) {
type = type.ofType
if (isNonNullType(type)) {
hasListNonNull = true
}
}
return {
outerNonNull,
hasListNonNull,
}
}