/
index.ts
213 lines (202 loc) · 7.31 KB
/
index.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
import { humanize } from '../../../lib/utils'
import {
type BaseListTypeInfo,
type CommonFieldConfig,
fieldType,
orderDirectionEnum,
type FieldTypeFunc,
} from '../../../types'
import { graphql } from '../../..'
import { assertReadIsNonNullAllowed } from '../../non-null-graphql'
import { filters } from '../../filters'
export type TextFieldConfig<ListTypeInfo extends BaseListTypeInfo> =
CommonFieldConfig<ListTypeInfo> & {
isIndexed?: true | 'unique'
ui?: {
displayMode?: 'input' | 'textarea'
}
validation?: {
/**
* Makes the field disallow null values and require a string at least 1 character long
*/
isRequired?: boolean
match?: { regex: RegExp, explanation?: string }
length?: { min?: number, max?: number }
}
defaultValue?: string
db?: {
isNullable?: boolean
map?: string
extendPrismaSchema?: (field: string) => string
/**
* The underlying database type.
* Only some of the types are supported on PostgreSQL and MySQL.
* The native type is not customisable on SQLite.
* See Prisma's documentation for more information about the supported types.
*
* https://www.prisma.io/docs/reference/api-reference/prisma-schema-reference#string
*/
nativeType?:
| 'Text' // PostgreSQL and MySQL
| `VarChar(${number})`
| `Char(${number})`
| `Bit(${number})` // PostgreSQL
| 'VarBit'
| 'Uuid'
| 'Xml'
| 'Inet'
| 'Citext'
| 'TinyText' // MySQL
| 'MediumText'
| 'LargeText'
}
}
export const text =
<ListTypeInfo extends BaseListTypeInfo>({
isIndexed,
defaultValue: _defaultValue,
validation: _validation,
...config
}: TextFieldConfig<ListTypeInfo> = {}): FieldTypeFunc<ListTypeInfo> =>
meta => {
for (const type of ['min', 'max'] as const) {
const val = _validation?.length?.[type]
if (val !== undefined && (!Number.isInteger(val) || val < 0)) {
throw new Error(
`The text field at ${meta.listKey}.${meta.fieldKey} specifies validation.length.${type}: ${val} but it must be a positive integer`
)
}
if (_validation?.isRequired && val !== undefined && val === 0) {
throw new Error(
`The text field at ${meta.listKey}.${meta.fieldKey} specifies validation.isRequired: true and validation.length.${type}: 0, this is not allowed because validation.isRequired implies at least a min length of 1`
)
}
}
if (
_validation?.length?.min !== undefined &&
_validation?.length?.max !== undefined &&
_validation?.length?.min > _validation?.length?.max
) {
throw new Error(
`The text field at ${meta.listKey}.${meta.fieldKey} specifies a validation.length.max that is less than the validation.length.min, and therefore has no valid options`
)
}
const validation = {
..._validation,
length: {
min: _validation?.isRequired ? _validation?.length?.min ?? 1 : _validation?.length?.min,
max: _validation?.length?.max,
},
}
// defaulted to false as a zero length string is preferred to null
const isNullable = config.db?.isNullable ?? false
const fieldLabel = config.label ?? humanize(meta.fieldKey)
assertReadIsNonNullAllowed(meta, config, isNullable)
const mode = isNullable ? 'optional' : 'required'
const defaultValue =
isNullable === false || _defaultValue !== undefined ? _defaultValue || '' : undefined
return fieldType({
kind: 'scalar',
mode,
scalar: 'String',
default: defaultValue === undefined ? undefined : { kind: 'literal', value: defaultValue },
index: isIndexed === true ? 'index' : isIndexed || undefined,
map: config.db?.map,
nativeType: config.db?.nativeType,
extendPrismaSchema: config.db?.extendPrismaSchema,
})({
...config,
hooks: {
...config.hooks,
async validateInput (args) {
const val = args.resolvedData[meta.fieldKey]
if (val === null && (validation?.isRequired || isNullable === false)) {
args.addValidationError(`${fieldLabel} is required`)
}
if (val != null) {
if (validation?.length?.min !== undefined && val.length < validation.length.min) {
if (validation.length.min === 1) {
args.addValidationError(`${fieldLabel} must not be empty`)
} else {
args.addValidationError(
`${fieldLabel} must be at least ${validation.length.min} characters long`
)
}
}
if (validation?.length?.max !== undefined && val.length > validation.length.max) {
args.addValidationError(
`${fieldLabel} must be no longer than ${validation.length.max} characters`
)
}
if (validation?.match && !validation.match.regex.test(val)) {
args.addValidationError(
validation.match.explanation || `${fieldLabel} must match ${validation.match.regex}`
)
}
}
await config.hooks?.validateInput?.(args)
},
},
input: {
uniqueWhere:
isIndexed === 'unique' ? { arg: graphql.arg({ type: graphql.String }) } : undefined,
where: {
arg: graphql.arg({
type: filters[meta.provider].String[mode],
}),
resolve: mode === 'required' ? undefined : filters.resolveString,
},
create: {
arg: graphql.arg({
type: graphql.String,
defaultValue: typeof defaultValue === 'string' ? defaultValue : undefined,
}),
resolve (val) {
if (val === undefined) {
return defaultValue ?? null
}
return val
},
},
update: { arg: graphql.arg({ type: graphql.String }) },
orderBy: { arg: graphql.arg({ type: orderDirectionEnum }) },
},
output: graphql.field({
type: graphql.String,
}),
__ksTelemetryFieldTypeName: '@keystone-6/text',
views: '@keystone-6/core/fields/types/text/views',
getAdminMeta (): TextFieldMeta {
return {
displayMode: config.ui?.displayMode ?? 'input',
shouldUseModeInsensitive: meta.provider === 'postgresql',
validation: {
isRequired: validation?.isRequired ?? false,
match: validation?.match
? {
regex: {
source: validation.match.regex.source,
flags: validation.match.regex.flags,
},
explanation: validation.match.explanation ?? null,
}
: null,
length: { max: validation?.length?.max ?? null, min: validation?.length?.min ?? null },
},
defaultValue: defaultValue ?? (isNullable ? null : ''),
isNullable,
}
},
})
}
export type TextFieldMeta = {
displayMode: 'input' | 'textarea'
shouldUseModeInsensitive: boolean
isNullable: boolean
validation: {
isRequired: boolean
match: { regex: { source: string, flags: string }, explanation: string | null } | null
length: { min: number | null, max: number | null }
}
defaultValue: string | null
}